1 // Copyright 2024 The BoringSSL Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "test_data.h"
16
17 #include <stdio.h>
18 #include <stdlib.h>
19
20 #include "file_util.h"
21
22 #if defined(BORINGSSL_USE_BAZEL_RUNFILES)
23 #include "tools/cpp/runfiles/runfiles.h"
24
25 using bazel::tools::cpp::runfiles::Runfiles;
26 #endif
27
28 #if !defined(BORINGSSL_CUSTOM_GET_TEST_DATA)
GetTestData(const char * path)29 std::string GetTestData(const char *path) {
30 #if defined(BORINGSSL_USE_BAZEL_RUNFILES)
31 std::string error;
32 std::unique_ptr<Runfiles> runfiles(
33 Runfiles::CreateForTest(BAZEL_CURRENT_REPOSITORY, &error));
34 if (runfiles == nullptr) {
35 fprintf(stderr, "Could not initialize runfiles: %s\n", error.c_str());
36 abort();
37 }
38
39 std::string full_path = runfiles->Rlocation(std::string("boringssl/") + path);
40 if (full_path.empty()) {
41 fprintf(stderr, "Could not find runfile '%s'.\n", path);
42 abort();
43 }
44 #else
45 const char *root = getenv("BORINGSSL_TEST_DATA_ROOT");
46 root = root != nullptr ? root : ".";
47
48 std::string full_path = root;
49 full_path.push_back('/');
50 full_path.append(path);
51 #endif
52
53 bssl::ScopedFILE file(fopen(full_path.c_str(), "rb"));
54 if (file == nullptr) {
55 fprintf(stderr, "Could not open '%s'.\n", full_path.c_str());
56 abort();
57 }
58
59 std::string ret;
60 for (;;) {
61 char buf[512];
62 size_t n = fread(buf, 1, sizeof(buf), file.get());
63 if (n == 0) {
64 if (feof(file.get())) {
65 return ret;
66 }
67 fprintf(stderr, "Error reading from '%s'.\n", full_path.c_str());
68 abort();
69 }
70 ret.append(buf, n);
71 }
72 }
73 #endif // !BORINGSSL_CUSTOM_GET_TEST_DATA
74