xref: /aosp_15_r20/external/boringssl/src/crypto/test/test_data.cc (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (c) 2024, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
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(Runfiles::CreateForTest(&error));
33   if (runfiles == nullptr) {
34     fprintf(stderr, "Could not initialize runfiles: %s\n", error.c_str());
35     abort();
36   }
37 
38   std::string full_path = runfiles->Rlocation(std::string("boringssl/") + path);
39   if (full_path.empty()) {
40     fprintf(stderr, "Could not find runfile '%s'.\n", path);
41     abort();
42   }
43 #else
44   const char *root = getenv("BORINGSSL_TEST_DATA_ROOT");
45   root = root != nullptr ? root : ".";
46 
47   std::string full_path = root;
48   full_path.push_back('/');
49   full_path.append(path);
50 #endif
51 
52   bssl::ScopedFILE file(fopen(full_path.c_str(), "rb"));
53   if (file == nullptr) {
54     fprintf(stderr, "Could not open '%s'.\n", full_path.c_str());
55     abort();
56   }
57 
58   std::string ret;
59   for (;;) {
60     char buf[512];
61     size_t n = fread(buf, 1, sizeof(buf), file.get());
62     if (n == 0) {
63       if (feof(file.get())) {
64         return ret;
65       }
66       fprintf(stderr, "Error reading from '%s'.\n", full_path.c_str());
67       abort();
68     }
69     ret.append(buf, n);
70   }
71 }
72 #endif  // !BORINGSSL_CUSTOM_GET_TEST_DATA
73