1 /*
2  * Copyright (C) 2024 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // Check that the current test executable only links known exported libraries
18 // dynamically. Intended to be statically linked into standalone tests.
19 
20 #include <dlfcn.h>
21 #include <fcntl.h>
22 #include <gelf.h>
23 #include <libelf.h>
24 
25 #include <algorithm>
26 #include <string>
27 #include <vector>
28 
29 #include "android-base/result-gmock.h"
30 #include "android-base/result.h"
31 #include "android-base/scopeguard.h"
32 #include "android-base/strings.h"
33 #include "android-base/unique_fd.h"
34 #include "gmock/gmock.h"
35 #include "gtest/gtest.h"
36 
37 namespace {
38 
39 using ::android::base::ErrnoError;
40 using ::android::base::Error;
41 using ::android::base::Result;
42 
43 // The allow-listed libraries. Standalone tests can assume that the ART module
44 // is from the same build as the test(*), but not the platform nor any other
45 // module. Hence all dynamic libraries listed here must satisfy at least one of
46 // these conditions:
47 //
48 // -  Have a stable ABI and be available since the APEX min_sdk_version (31).
49 //    This includes NDK and system APIs.
50 // -  Be loaded from the ART APEX itself(*). Note that linker namespaces aren't
51 //    set up to allow this for libraries that aren't exported, so in practice it
52 //    is restricted to them.
53 // -  Always be pushed to device together with the test.
54 // -  Be a runtime instrumentation library or similar, e.g. for sanitizer test
55 //    builds, where everything is always built from source - platform, module,
56 //    and tests.
57 //
58 // *) (Non-MCTS) CTS tests is an exception - they must work with any future
59 // version of the module and hence restrict themselves to the exported module
60 // APIs.
61 constexpr const char* kAllowedDynamicLibDeps[] = {
62     // LLVM
63     "libclang_rt.hwasan-aarch64-android.so",
64     // Bionic
65     "libc.so",
66     "libdl.so",
67     "libdl_android.so",
68     "libm.so",
69     // Platform
70     "heapprofd_client_api.so",
71     "libbinder_ndk.so",
72     "liblog.so",
73     "libselinux.so",
74     "libz.so",
75     // Other modules
76     "libstatspull.so",
77     "libstatssocket.so",
78     // ART exported
79     "libdexfile.so",
80     "libnativebridge.so",
81     "libnativehelper.so",
82     "libnativeloader.so",
83 };
84 
GetCurrentElfObjectPath()85 Result<std::string> GetCurrentElfObjectPath() {
86   Dl_info info;
87   if (dladdr(reinterpret_cast<void*>(GetCurrentElfObjectPath), &info) == 0) {
88     return Error() << "dladdr failed to map own address to a shared object.";
89   }
90   return info.dli_fname;
91 }
92 
GetDynamicLibDeps(const std::string & filename)93 Result<std::vector<std::string>> GetDynamicLibDeps(const std::string& filename) {
94   if (elf_version(EV_CURRENT) == EV_NONE) {
95     return Errorf("libelf initialization failed: {}", elf_errmsg(-1));
96   }
97 
98   android::base::unique_fd fd(open(filename.c_str(), O_RDONLY));
99   if (fd.get() == -1) {
100     return ErrnoErrorf("Error opening {}", filename);
101   }
102 
103   Elf* elf = elf_begin(fd.get(), ELF_C_READ, /*ref=*/nullptr);
104   if (elf == nullptr) {
105     return Errorf("Error creating ELF object for {}: {}", filename, elf_errmsg(-1));
106   }
107   auto elf_cleanup = android::base::make_scope_guard([&]() { elf_end(elf); });
108 
109   std::vector<std::string> libs;
110 
111   // Find the dynamic section.
112   for (Elf_Scn* dyn_scn = nullptr; (dyn_scn = elf_nextscn(elf, dyn_scn)) != nullptr;) {
113     GElf_Shdr scn_hdr;
114     if (gelf_getshdr(dyn_scn, &scn_hdr) != &scn_hdr) {
115       return Errorf("Failed to retrieve ELF section header in {}: {}", filename, elf_errmsg(-1));
116     }
117 
118     if (scn_hdr.sh_type == SHT_DYNAMIC) {
119       Elf_Data* data = elf_getdata(dyn_scn, /*data=*/nullptr);
120 
121       // Iterate through dynamic section entries.
122       for (int i = 0; i < scn_hdr.sh_size / scn_hdr.sh_entsize; i++) {
123         GElf_Dyn dyn_entry;
124         if (gelf_getdyn(data, i, &dyn_entry) != &dyn_entry) {
125           return Errorf("Failed to get entry {} in ELF dynamic section of {}: {}",
126                         i,
127                         filename,
128                         elf_errmsg(-1));
129         }
130 
131         if (dyn_entry.d_tag == DT_NEEDED) {
132           const char* lib_name = elf_strptr(elf, scn_hdr.sh_link, dyn_entry.d_un.d_val);
133           if (lib_name == nullptr) {
134             return Errorf("Failed to get string from entry {} in ELF dynamic section of {}: {}",
135                           i,
136                           filename,
137                           elf_errmsg(-1));
138           }
139           libs.push_back(lib_name);
140         }
141       }
142       break;  // Found the dynamic section, no need to continue.
143     }
144   }
145 
146   return libs;
147 }
148 
149 }  // namespace
150 
TEST(StandaloneTestAllowedLibDeps,test)151 TEST(StandaloneTestAllowedLibDeps, test) {
152   Result<std::string> path_to_self = GetCurrentElfObjectPath();
153   ASSERT_RESULT_OK(path_to_self);
154   Result<std::vector<std::string>> dyn_lib_deps = GetDynamicLibDeps(path_to_self.value());
155   ASSERT_RESULT_OK(dyn_lib_deps);
156 
157   std::vector<std::string> disallowed_libs;
158   for (const std::string& dyn_lib_dep : dyn_lib_deps.value()) {
159     if (std::find(std::begin(kAllowedDynamicLibDeps),
160                   std::end(kAllowedDynamicLibDeps),
161                   dyn_lib_dep) == std::end(kAllowedDynamicLibDeps)) {
162       disallowed_libs.push_back(dyn_lib_dep);
163     }
164   }
165 
166   EXPECT_THAT(disallowed_libs, testing::IsEmpty())
167       << path_to_self.value() << " has disallowed shared library dependencies.";
168 }
169