1 /*
2 * Copyright (C) 2019 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 #define LOG_TAG "nativeloader"
18
19 #include "public_libraries.h"
20
21 #include <dirent.h>
22
23 #include <algorithm>
24 #include <memory>
25
26 #include <android-base/file.h>
27 #include <android-base/logging.h>
28 #include <android-base/properties.h>
29 #include <android-base/result.h>
30 #include <android-base/strings.h>
31 #include <log/log.h>
32
33 #if defined(__ANDROID__)
34 #include <android/sysprop/VndkProperties.sysprop.h>
35 #endif
36
37 #include "utils.h"
38
39 namespace android::nativeloader {
40
41 using android::base::ErrnoError;
42 using android::base::Result;
43 using internal::ConfigEntry;
44 using internal::ParseConfig;
45 using std::literals::string_literals::operator""s;
46
47 namespace {
48
49 constexpr const char* kDefaultPublicLibrariesFile = "/etc/public.libraries.txt";
50 constexpr const char* kExtendedPublicLibrariesFilePrefix = "public.libraries-";
51 constexpr const char* kExtendedPublicLibrariesFileSuffix = ".txt";
52 constexpr const char* kVendorPublicLibrariesFile = "/vendor/etc/public.libraries.txt";
53 constexpr const char* kLlndkLibrariesFile = "/apex/com.android.vndk.v{}/etc/llndk.libraries.{}.txt";
54 constexpr const char* kVndkLibrariesFile = "/apex/com.android.vndk.v{}/etc/vndksp.libraries.{}.txt";
55
56 const std::vector<const std::string> kArtApexPublicLibraries = {
57 "libicuuc.so",
58 "libicui18n.so",
59 };
60
61 constexpr const char* kArtApexLibPath = "/apex/com.android.art/" LIB;
62
63 constexpr const char* kNeuralNetworksApexPublicLibrary = "libneuralnetworks.so";
64
65 constexpr const char* kStatsdApexPublicLibrary = "libstats_jni.so";
66
67 // TODO(b/130388701): do we need this?
root_dir()68 std::string root_dir() {
69 static const char* android_root_env = getenv("ANDROID_ROOT");
70 return android_root_env != nullptr ? android_root_env : "/system";
71 }
72
debuggable()73 bool debuggable() {
74 static bool debuggable = android::base::GetBoolProperty("ro.debuggable", false);
75 return debuggable;
76 }
77
vndk_version_str(bool use_product_vndk)78 std::string vndk_version_str(bool use_product_vndk) {
79 if (use_product_vndk) {
80 static std::string product_vndk_version = get_vndk_version(true);
81 return product_vndk_version;
82 } else {
83 static std::string vendor_vndk_version = get_vndk_version(false);
84 return vendor_vndk_version;
85 }
86 }
87
88 // For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
89 // variable to add libraries to the list. This is intended for platform tests only.
additional_public_libraries()90 std::string additional_public_libraries() {
91 if (debuggable()) {
92 const char* val = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
93 return val ? val : "";
94 }
95 return "";
96 }
97
98 // insert vndk version in every {} placeholder
InsertVndkVersionStr(std::string * file_name,bool use_product_vndk)99 void InsertVndkVersionStr(std::string* file_name, bool use_product_vndk) {
100 CHECK(file_name != nullptr);
101 auto version = vndk_version_str(use_product_vndk);
102 size_t pos = file_name->find("{}");
103 while (pos != std::string::npos) {
104 file_name->replace(pos, 2, version);
105 pos = file_name->find("{}", pos + version.size());
106 }
107 }
108
109 const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
__anon2cb3f6050202(const struct ConfigEntry&) 110 [](const struct ConfigEntry&) -> Result<bool> { return true; };
111
ReadConfig(const std::string & configFile,const std::function<Result<bool> (const ConfigEntry &)> & filter_fn)112 Result<std::vector<std::string>> ReadConfig(
113 const std::string& configFile,
114 const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
115 std::string file_content;
116 if (!base::ReadFileToString(configFile, &file_content)) {
117 return ErrnoError();
118 }
119 Result<std::vector<std::string>> result = ParseConfig(file_content, filter_fn);
120 if (!result.ok()) {
121 return Errorf("Cannot parse {}: {}", configFile, result.error().message());
122 }
123 return result;
124 }
125
ReadExtensionLibraries(const char * dirname,std::vector<std::string> * sonames)126 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
127 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
128 if (dir != nullptr) {
129 // Failing to opening the dir is not an error, which can happen in
130 // webview_zygote.
131 while (struct dirent* ent = readdir(dir.get())) {
132 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
133 continue;
134 }
135 const std::string filename(ent->d_name);
136 std::string_view fn = filename;
137 if (android::base::ConsumePrefix(&fn, kExtendedPublicLibrariesFilePrefix) &&
138 android::base::ConsumeSuffix(&fn, kExtendedPublicLibrariesFileSuffix)) {
139 const std::string company_name(fn);
140 const std::string config_file_path = dirname + "/"s + filename;
141 LOG_ALWAYS_FATAL_IF(
142 company_name.empty(),
143 "Error extracting company name from public native library list file path \"%s\"",
144 config_file_path.c_str());
145
146 auto ret = ReadConfig(
147 config_file_path, [&company_name](const struct ConfigEntry& entry) -> Result<bool> {
148 if (android::base::StartsWith(entry.soname, "lib") &&
149 android::base::EndsWith(entry.soname, "." + company_name + ".so")) {
150 return true;
151 } else {
152 return Errorf("Library name \"{}\" does not end with the company name {}.",
153 entry.soname, company_name);
154 }
155 });
156 if (ret.ok()) {
157 sonames->insert(sonames->end(), ret->begin(), ret->end());
158 } else {
159 LOG_ALWAYS_FATAL("Error reading public native library list from \"%s\": %s",
160 config_file_path.c_str(), ret.error().message().c_str());
161 }
162 }
163 }
164 }
165 }
166
InitDefaultPublicLibraries(bool for_preload)167 static std::string InitDefaultPublicLibraries(bool for_preload) {
168 std::string config_file = root_dir() + kDefaultPublicLibrariesFile;
169 auto sonames =
170 ReadConfig(config_file, [&for_preload](const struct ConfigEntry& entry) -> Result<bool> {
171 if (for_preload) {
172 return !entry.nopreload;
173 } else {
174 return true;
175 }
176 });
177 if (!sonames.ok()) {
178 LOG_ALWAYS_FATAL("Error reading public native library list from \"%s\": %s",
179 config_file.c_str(), sonames.error().message().c_str());
180 return "";
181 }
182
183 std::string additional_libs = additional_public_libraries();
184 if (!additional_libs.empty()) {
185 auto vec = base::Split(additional_libs, ":");
186 std::copy(vec.begin(), vec.end(), std::back_inserter(*sonames));
187 }
188
189 // If this is for preloading libs, don't remove the libs from APEXes.
190 if (for_preload) {
191 return android::base::Join(*sonames, ':');
192 }
193
194 // Remove the public libs in the art namespace.
195 // These libs are listed in public.android.txt, but we don't want the rest of android
196 // in default namespace to dlopen the libs.
197 // For example, libicuuc.so is exposed to classloader namespace from art namespace.
198 // Unfortunately, it does not have stable C symbols, and default namespace should only use
199 // stable symbols in libandroidicu.so. http://b/120786417
200 for (const std::string& lib_name : kArtApexPublicLibraries) {
201 std::string path(kArtApexLibPath);
202 path.append("/").append(lib_name);
203
204 struct stat s;
205 // Do nothing if the path in /apex does not exist.
206 // Runtime APEX must be mounted since libnativeloader is in the same APEX
207 if (stat(path.c_str(), &s) != 0) {
208 continue;
209 }
210
211 auto it = std::find(sonames->begin(), sonames->end(), lib_name);
212 if (it != sonames->end()) {
213 sonames->erase(it);
214 }
215 }
216
217 // Remove the public libs in the nnapi namespace.
218 auto it = std::find(sonames->begin(), sonames->end(), kNeuralNetworksApexPublicLibrary);
219 if (it != sonames->end()) {
220 sonames->erase(it);
221 }
222 return android::base::Join(*sonames, ':');
223 }
224
InitArtPublicLibraries()225 static std::string InitArtPublicLibraries() {
226 CHECK_GT((int)sizeof(kArtApexPublicLibraries), 0);
227 std::string list = android::base::Join(kArtApexPublicLibraries, ":");
228
229 std::string additional_libs = additional_public_libraries();
230 if (!additional_libs.empty()) {
231 list = list + ':' + additional_libs;
232 }
233 return list;
234 }
235
InitVendorPublicLibraries()236 static std::string InitVendorPublicLibraries() {
237 // This file is optional, quietly ignore if the file does not exist.
238 auto sonames = ReadConfig(kVendorPublicLibrariesFile, always_true);
239 if (!sonames.ok()) {
240 return "";
241 }
242 return android::base::Join(*sonames, ':');
243 }
244
245 // read /system/etc/public.libraries-<companyname>.txt,
246 // /system_ext/etc/public.libraries-<companyname>.txt and
247 // /product/etc/public.libraries-<companyname>.txt which contain partner defined
248 // system libs that are exposed to apps. The libs in the txt files must be
249 // named as lib<name>.<companyname>.so.
InitExtendedPublicLibraries()250 static std::string InitExtendedPublicLibraries() {
251 std::vector<std::string> sonames;
252 ReadExtensionLibraries("/system/etc", &sonames);
253 ReadExtensionLibraries("/system_ext/etc", &sonames);
254 ReadExtensionLibraries("/product/etc", &sonames);
255 return android::base::Join(sonames, ':');
256 }
257
InitLlndkLibrariesVendor()258 static std::string InitLlndkLibrariesVendor() {
259 std::string config_file = kLlndkLibrariesFile;
260 InsertVndkVersionStr(&config_file, false);
261 auto sonames = ReadConfig(config_file, always_true);
262 if (!sonames.ok()) {
263 LOG_ALWAYS_FATAL("%s: %s", config_file.c_str(), sonames.error().message().c_str());
264 return "";
265 }
266 return android::base::Join(*sonames, ':');
267 }
268
InitLlndkLibrariesProduct()269 static std::string InitLlndkLibrariesProduct() {
270 if (!is_product_vndk_version_defined()) {
271 return "";
272 }
273 std::string config_file = kLlndkLibrariesFile;
274 InsertVndkVersionStr(&config_file, true);
275 auto sonames = ReadConfig(config_file, always_true);
276 if (!sonames.ok()) {
277 LOG_ALWAYS_FATAL("%s: %s", config_file.c_str(), sonames.error().message().c_str());
278 return "";
279 }
280 return android::base::Join(*sonames, ':');
281 }
282
InitVndkspLibrariesVendor()283 static std::string InitVndkspLibrariesVendor() {
284 std::string config_file = kVndkLibrariesFile;
285 InsertVndkVersionStr(&config_file, false);
286 auto sonames = ReadConfig(config_file, always_true);
287 if (!sonames.ok()) {
288 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
289 return "";
290 }
291 return android::base::Join(*sonames, ':');
292 }
293
InitVndkspLibrariesProduct()294 static std::string InitVndkspLibrariesProduct() {
295 if (!is_product_vndk_version_defined()) {
296 return "";
297 }
298 std::string config_file = kVndkLibrariesFile;
299 InsertVndkVersionStr(&config_file, true);
300 auto sonames = ReadConfig(config_file, always_true);
301 if (!sonames.ok()) {
302 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
303 return "";
304 }
305 return android::base::Join(*sonames, ':');
306 }
307
InitNeuralNetworksPublicLibraries()308 static std::string InitNeuralNetworksPublicLibraries() {
309 return kNeuralNetworksApexPublicLibrary;
310 }
311
InitStatsdPublicLibraries()312 static std::string InitStatsdPublicLibraries() {
313 return kStatsdApexPublicLibrary;
314 }
315
316 } // namespace
317
preloadable_public_libraries()318 const std::string& preloadable_public_libraries() {
319 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ true);
320 return list;
321 }
322
default_public_libraries()323 const std::string& default_public_libraries() {
324 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ false);
325 return list;
326 }
327
art_public_libraries()328 const std::string& art_public_libraries() {
329 static std::string list = InitArtPublicLibraries();
330 return list;
331 }
332
vendor_public_libraries()333 const std::string& vendor_public_libraries() {
334 static std::string list = InitVendorPublicLibraries();
335 return list;
336 }
337
extended_public_libraries()338 const std::string& extended_public_libraries() {
339 static std::string list = InitExtendedPublicLibraries();
340 return list;
341 }
342
neuralnetworks_public_libraries()343 const std::string& neuralnetworks_public_libraries() {
344 static std::string list = InitNeuralNetworksPublicLibraries();
345 return list;
346 }
347
statsd_public_libraries()348 const std::string& statsd_public_libraries() {
349 static std::string list = InitStatsdPublicLibraries();
350 return list;
351 }
352
llndk_libraries_product()353 const std::string& llndk_libraries_product() {
354 static std::string list = InitLlndkLibrariesProduct();
355 return list;
356 }
357
llndk_libraries_vendor()358 const std::string& llndk_libraries_vendor() {
359 static std::string list = InitLlndkLibrariesVendor();
360 return list;
361 }
362
vndksp_libraries_product()363 const std::string& vndksp_libraries_product() {
364 static std::string list = InitVndkspLibrariesProduct();
365 return list;
366 }
367
vndksp_libraries_vendor()368 const std::string& vndksp_libraries_vendor() {
369 static std::string list = InitVndkspLibrariesVendor();
370 return list;
371 }
372
is_product_vndk_version_defined()373 bool is_product_vndk_version_defined() {
374 #if defined(__ANDROID__)
375 return android::sysprop::VndkProperties::product_vndk_version().has_value();
376 #else
377 return false;
378 #endif
379 }
380
get_vndk_version(bool is_product_vndk)381 std::string get_vndk_version(bool is_product_vndk) {
382 #if defined(__ANDROID__)
383 if (is_product_vndk) {
384 return android::sysprop::VndkProperties::product_vndk_version().value_or("");
385 }
386 return android::sysprop::VndkProperties::vendor_vndk_version().value_or("");
387 #else
388 if (is_product_vndk) {
389 return android::base::GetProperty("ro.product.vndk.version", "");
390 }
391 return android::base::GetProperty("ro.vndk.version", "");
392 #endif
393 }
394
395 namespace internal {
396 // Exported for testing
ParseConfig(const std::string & file_content,const std::function<Result<bool> (const ConfigEntry &)> & filter_fn)397 Result<std::vector<std::string>> ParseConfig(
398 const std::string& file_content,
399 const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
400 std::vector<std::string> lines = base::Split(file_content, "\n");
401
402 std::vector<std::string> sonames;
403 for (auto& line : lines) {
404 auto trimmed_line = base::Trim(line);
405 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
406 continue;
407 }
408
409 std::vector<std::string> tokens = android::base::Split(trimmed_line, " ");
410 if (tokens.size() < 1 || tokens.size() > 3) {
411 return Errorf("Malformed line \"{}\"", line);
412 }
413 struct ConfigEntry entry = {.soname = "", .nopreload = false, .bitness = ALL};
414 size_t i = tokens.size();
415 while (i-- > 0) {
416 if (tokens[i] == "nopreload") {
417 entry.nopreload = true;
418 } else if (tokens[i] == "32" || tokens[i] == "64") {
419 if (entry.bitness != ALL) {
420 return Errorf("Malformed line \"{}\": bitness can be specified only once", line);
421 }
422 entry.bitness = tokens[i] == "32" ? ONLY_32 : ONLY_64;
423 } else {
424 if (i != 0) {
425 return Errorf("Malformed line \"{}\"", line);
426 }
427 entry.soname = tokens[i];
428 }
429 }
430
431 // skip 32-bit lib on 64-bit process and vice versa
432 #if defined(__LP64__)
433 if (entry.bitness == ONLY_32) continue;
434 #else
435 if (entry.bitness == ONLY_64) continue;
436 #endif
437
438 Result<bool> ret = filter_fn(entry);
439 if (!ret.ok()) {
440 return ret.error();
441 }
442 if (*ret) {
443 // filter_fn has returned true.
444 sonames.push_back(entry.soname);
445 }
446 }
447 return sonames;
448 }
449
450 } // namespace internal
451
452 } // namespace android::nativeloader
453