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 <map>
25 #include <memory>
26 #include <regex>
27 #include <string>
28
29 #include <android-base/file.h>
30 #include <android-base/logging.h>
31 #include <android-base/properties.h>
32 #include <android-base/result.h>
33 #include <android-base/strings.h>
34 #include <log/log.h>
35
36 #if defined(ART_TARGET_ANDROID)
37 #include <android-modules-utils/sdk_level.h>
38 #include <android/sysprop/VndkProperties.sysprop.h>
39 #endif
40
41 #include "utils.h"
42
43 namespace android::nativeloader {
44
45 using android::base::ErrnoError;
46 using android::base::Result;
47 using internal::ConfigEntry;
48 using internal::ParseConfig;
49 using internal::ParseApexLibrariesConfig;
50
51 namespace {
52
53 constexpr const char* kDefaultPublicLibrariesFile = "/etc/public.libraries.txt";
54 constexpr const char* kExtendedPublicLibrariesFilePrefix = "public.libraries-";
55 constexpr const char* kExtendedPublicLibrariesFileSuffix = ".txt";
56 constexpr const char* kApexLibrariesConfigFile = "/linkerconfig/apex.libraries.config.txt";
57 constexpr const char* kVendorPublicLibrariesFile = "/vendor/etc/public.libraries.txt";
58 constexpr const char* kLlndkLibrariesFile = "/apex/com.android.vndk.v{}/etc/llndk.libraries.{}.txt";
59 constexpr const char* kLlndkLibrariesNoVndkFile = "/system/etc/llndk.libraries.txt";
60 constexpr const char* kVndkLibrariesFile = "/apex/com.android.vndk.v{}/etc/vndksp.libraries.{}.txt";
61
62
63 // TODO(b/130388701): do we need this?
root_dir()64 std::string root_dir() {
65 static const char* android_root_env = getenv("ANDROID_ROOT");
66 return android_root_env != nullptr ? android_root_env : "/system";
67 }
68
vndk_version_str(bool use_product_vndk)69 std::string vndk_version_str(bool use_product_vndk) {
70 if (use_product_vndk) {
71 static std::string product_vndk_version = get_vndk_version(true);
72 return product_vndk_version;
73 } else {
74 static std::string vendor_vndk_version = get_vndk_version(false);
75 return vendor_vndk_version;
76 }
77 }
78
79 // insert vndk version in every {} placeholder
InsertVndkVersionStr(std::string * file_name,bool use_product_vndk)80 void InsertVndkVersionStr(std::string* file_name, bool use_product_vndk) {
81 CHECK(file_name != nullptr);
82 const std::string version = vndk_version_str(use_product_vndk);
83 size_t pos = file_name->find("{}");
84 while (pos != std::string::npos) {
85 file_name->replace(pos, 2, version);
86 pos = file_name->find("{}", pos + version.size());
87 }
88 }
89
90 const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
__anon2cb3f6050202(const struct ConfigEntry&) 91 [](const struct ConfigEntry&) -> Result<bool> { return true; };
92
ReadConfig(const std::string & configFile,const std::function<Result<bool> (const ConfigEntry &)> & filter_fn)93 Result<std::vector<std::string>> ReadConfig(
94 const std::string& configFile,
95 const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
96 std::string file_content;
97 if (!base::ReadFileToString(configFile, &file_content)) {
98 return ErrnoError() << "Failed to read " << configFile;
99 }
100 Result<std::vector<std::string>> result = ParseConfig(file_content, filter_fn);
101 if (!result.ok()) {
102 return Errorf("Cannot parse {}: {}", configFile, result.error().message());
103 }
104 return result;
105 }
106
ReadExtensionLibraries(const char * dirname,std::vector<std::string> * sonames)107 void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
108 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
109 if (dir != nullptr) {
110 // Failing to opening the dir is not an error, which can happen in
111 // webview_zygote.
112 while (struct dirent* ent = readdir(dir.get())) {
113 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
114 continue;
115 }
116 const std::string filename(ent->d_name);
117 std::string_view fn = filename;
118 if (android::base::ConsumePrefix(&fn, kExtendedPublicLibrariesFilePrefix) &&
119 android::base::ConsumeSuffix(&fn, kExtendedPublicLibrariesFileSuffix)) {
120 const std::string company_name(fn);
121 const std::string config_file_path = std::string(dirname) + std::string("/") + filename;
122 LOG_ALWAYS_FATAL_IF(
123 company_name.empty(),
124 "Error extracting company name from public native library list file path \"%s\"",
125 config_file_path.c_str());
126
127 Result<std::vector<std::string>> ret = ReadConfig(
128 config_file_path, [&company_name](const struct ConfigEntry& entry) -> Result<bool> {
129 if (entry.soname.starts_with("lib") &&
130 entry.soname.ends_with("." + company_name + ".so")) {
131 return true;
132 } else {
133 return Errorf(
134 "Library name \"{}\" does not start with \"lib\" and/or "
135 "does not end with the company name \"{}\".",
136 entry.soname,
137 company_name);
138 }
139 });
140 if (ret.ok()) {
141 sonames->insert(sonames->end(), ret->begin(), ret->end());
142 } else {
143 LOG_ALWAYS_FATAL("Error reading extension library list: %s",
144 ret.error().message().c_str());
145 }
146 }
147 }
148 }
149 }
150
InitDefaultPublicLibraries(bool for_preload)151 static std::string InitDefaultPublicLibraries(bool for_preload) {
152 std::string config_file = root_dir() + kDefaultPublicLibrariesFile;
153 Result<std::vector<std::string>> sonames =
154 ReadConfig(config_file, [&for_preload](const struct ConfigEntry& entry) -> Result<bool> {
155 if (for_preload) {
156 return !entry.nopreload;
157 } else {
158 return true;
159 }
160 });
161 if (!sonames.ok()) {
162 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
163 return "";
164 }
165
166 // If this is for preloading libs, don't remove the libs from APEXes.
167 if (!for_preload) {
168 // Remove the public libs provided by apexes because these libs are available
169 // from apex namespaces.
170 for (const auto& [_, library_list] : apex_public_libraries()) {
171 std::vector<std::string> public_libs = base::Split(library_list, ":");
172 sonames->erase(std::remove_if(sonames->begin(),
173 sonames->end(),
174 [&public_libs](const std::string& v) {
175 return std::find(public_libs.begin(), public_libs.end(), v) !=
176 public_libs.end();
177 }),
178 sonames->end());
179 }
180 }
181
182 std::string libs = android::base::Join(*sonames, ':');
183 ALOGD("InitDefaultPublicLibraries for_preload=%d: %s", for_preload, libs.c_str());
184 return libs;
185 }
186
InitVendorPublicLibraries()187 static std::string InitVendorPublicLibraries() {
188 // This file is optional, quietly ignore if the file does not exist.
189 Result<std::vector<std::string>> sonames = ReadConfig(kVendorPublicLibrariesFile, always_true);
190 if (!sonames.ok()) {
191 ALOGI("InitVendorPublicLibraries skipped: %s", sonames.error().message().c_str());
192 return "";
193 }
194 std::string libs = android::base::Join(*sonames, ':');
195 ALOGD("InitVendorPublicLibraries: %s", libs.c_str());
196 return libs;
197 }
198
199 // If ro.product.vndk.version is defined, /product/etc/public.libraries-<companyname>.txt contains
200 // the product public libraries that are loaded from the product namespace. Otherwise, the file
201 // contains the extended public libraries that are loaded from the system namespace.
InitProductPublicLibraries()202 static std::string InitProductPublicLibraries() {
203 std::vector<std::string> sonames;
204 if (is_product_treblelized()) {
205 ReadExtensionLibraries("/product/etc", &sonames);
206 }
207 std::string libs = android::base::Join(sonames, ':');
208 ALOGD("InitProductPublicLibraries: %s", libs.c_str());
209 return libs;
210 }
211
212 // read /system/etc/public.libraries-<companyname>.txt,
213 // /system_ext/etc/public.libraries-<companyname>.txt and
214 // /product/etc/public.libraries-<companyname>.txt which contain partner defined
215 // system libs that are exposed to apps. The libs in the txt files must be
216 // named as lib<name>.<companyname>.so.
InitExtendedPublicLibraries()217 static std::string InitExtendedPublicLibraries() {
218 std::vector<std::string> sonames;
219 ReadExtensionLibraries("/system/etc", &sonames);
220 ReadExtensionLibraries("/system_ext/etc", &sonames);
221 if (!is_product_treblelized()) {
222 ReadExtensionLibraries("/product/etc", &sonames);
223 }
224 std::string libs = android::base::Join(sonames, ':');
225 ALOGD("InitExtendedPublicLibraries: %s", libs.c_str());
226 return libs;
227 }
228
IsVendorVndkEnabled()229 bool IsVendorVndkEnabled() {
230 #if defined(ART_TARGET_ANDROID)
231 return android::base::GetProperty("ro.vndk.version", "") != "";
232 #else
233 return true;
234 #endif
235 }
236
IsProductVndkEnabled()237 bool IsProductVndkEnabled() {
238 #if defined(ART_TARGET_ANDROID)
239 return android::base::GetProperty("ro.product.vndk.version", "") != "";
240 #else
241 return true;
242 #endif
243 }
244
InitLlndkLibrariesVendor()245 static std::string InitLlndkLibrariesVendor() {
246 std::string config_file;
247 if (IsVendorVndkEnabled()) {
248 config_file = kLlndkLibrariesFile;
249 InsertVndkVersionStr(&config_file, false);
250 } else {
251 config_file = kLlndkLibrariesNoVndkFile;
252 }
253 Result<std::vector<std::string>> sonames = ReadConfig(config_file, always_true);
254 if (!sonames.ok()) {
255 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
256 return "";
257 }
258 std::string libs = android::base::Join(*sonames, ':');
259 ALOGD("InitLlndkLibrariesVendor: %s", libs.c_str());
260 return libs;
261 }
262
InitLlndkLibrariesProduct()263 static std::string InitLlndkLibrariesProduct() {
264 if (!is_product_treblelized()) {
265 ALOGD("InitLlndkLibrariesProduct: Product is not treblelized");
266 return "";
267 }
268 std::string config_file;
269 if (IsProductVndkEnabled()) {
270 config_file = kLlndkLibrariesFile;
271 InsertVndkVersionStr(&config_file, true);
272 } else {
273 config_file = kLlndkLibrariesNoVndkFile;
274 }
275 Result<std::vector<std::string>> sonames = ReadConfig(config_file, always_true);
276 if (!sonames.ok()) {
277 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
278 return "";
279 }
280 std::string libs = android::base::Join(*sonames, ':');
281 ALOGD("InitLlndkLibrariesProduct: %s", libs.c_str());
282 return libs;
283 }
284
InitVndkspLibrariesVendor()285 static std::string InitVndkspLibrariesVendor() {
286 if (!IsVendorVndkEnabled()) {
287 ALOGD("InitVndkspLibrariesVendor: VNDK is deprecated with vendor");
288 return "";
289 }
290
291 std::string config_file = kVndkLibrariesFile;
292 InsertVndkVersionStr(&config_file, false);
293 Result<std::vector<std::string>> sonames = ReadConfig(config_file, always_true);
294 if (!sonames.ok()) {
295 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
296 return "";
297 }
298 std::string libs = android::base::Join(*sonames, ':');
299 ALOGD("InitVndkspLibrariesVendor: %s", libs.c_str());
300 return libs;
301 }
302
InitVndkspLibrariesProduct()303 static std::string InitVndkspLibrariesProduct() {
304 if (!IsProductVndkEnabled()) {
305 ALOGD("InitVndkspLibrariesProduct: VNDK is deprecated with product");
306 return "";
307 }
308 std::string config_file = kVndkLibrariesFile;
309 InsertVndkVersionStr(&config_file, true);
310 Result<std::vector<std::string>> sonames = ReadConfig(config_file, always_true);
311 if (!sonames.ok()) {
312 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
313 return "";
314 }
315 std::string libs = android::base::Join(*sonames, ':');
316 ALOGD("InitVndkspLibrariesProduct: %s", libs.c_str());
317 return libs;
318 }
319
InitApexLibraries(const std::string & tag)320 static std::map<std::string, std::string> InitApexLibraries(const std::string& tag) {
321 std::string file_content;
322 if (!base::ReadFileToString(kApexLibrariesConfigFile, &file_content)) {
323 // config is optional
324 ALOGI("InitApexLibraries skipped: %s", strerror(errno));
325 return {};
326 }
327 Result<std::map<std::string, std::string>> config = ParseApexLibrariesConfig(file_content, tag);
328 if (!config.ok()) {
329 LOG_ALWAYS_FATAL("%s: %s", kApexLibrariesConfigFile, config.error().message().c_str());
330 return {};
331 }
332 ALOGD("InitApexLibraries:\n %s",
333 [&config]() {
334 std::vector<std::string> lib_list;
335 lib_list.reserve(config->size());
336 for (std::pair<std::string, std::string> elem : *config) {
337 lib_list.emplace_back(elem.first + ": " + elem.second);
338 }
339 return android::base::Join(lib_list, "\n ");
340 }()
341 .c_str());
342 return *config;
343 }
344
345 struct ApexLibrariesConfigLine {
346 std::string tag;
347 std::string apex_namespace;
348 std::string library_list;
349 };
350
351 const std::regex kApexNamespaceRegex("[0-9a-zA-Z_]+");
352 const std::regex kLibraryListRegex("[0-9a-zA-Z.:@+_-]+");
353
ParseApexLibrariesConfigLine(const std::string & line)354 Result<ApexLibrariesConfigLine> ParseApexLibrariesConfigLine(const std::string& line) {
355 std::vector<std::string> tokens = base::Split(line, " ");
356 if (tokens.size() != 3) {
357 return Errorf("Malformed line \"{}\"", line);
358 }
359 if (tokens[0] != "jni" && tokens[0] != "public") {
360 return Errorf("Invalid tag \"{}\"", line);
361 }
362 if (!std::regex_match(tokens[1], kApexNamespaceRegex)) {
363 return Errorf("Invalid apex_namespace \"{}\"", line);
364 }
365 if (!std::regex_match(tokens[2], kLibraryListRegex)) {
366 return Errorf("Invalid library_list \"{}\"", line);
367 }
368 return ApexLibrariesConfigLine{std::move(tokens[0]), std::move(tokens[1]), std::move(tokens[2])};
369 }
370
371 } // namespace
372
preloadable_public_libraries()373 const std::string& preloadable_public_libraries() {
374 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ true);
375 return list;
376 }
377
default_public_libraries()378 const std::string& default_public_libraries() {
379 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ false);
380 return list;
381 }
382
vendor_public_libraries()383 const std::string& vendor_public_libraries() {
384 static std::string list = InitVendorPublicLibraries();
385 return list;
386 }
387
product_public_libraries()388 const std::string& product_public_libraries() {
389 static std::string list = InitProductPublicLibraries();
390 return list;
391 }
392
extended_public_libraries()393 const std::string& extended_public_libraries() {
394 static std::string list = InitExtendedPublicLibraries();
395 return list;
396 }
397
llndk_libraries_product()398 const std::string& llndk_libraries_product() {
399 static std::string list = InitLlndkLibrariesProduct();
400 return list;
401 }
402
llndk_libraries_vendor()403 const std::string& llndk_libraries_vendor() {
404 static std::string list = InitLlndkLibrariesVendor();
405 return list;
406 }
407
vndksp_libraries_product()408 const std::string& vndksp_libraries_product() {
409 static std::string list = InitVndkspLibrariesProduct();
410 return list;
411 }
412
vndksp_libraries_vendor()413 const std::string& vndksp_libraries_vendor() {
414 static std::string list = InitVndkspLibrariesVendor();
415 return list;
416 }
417
apex_jni_libraries(const std::string & apex_ns_name)418 const std::string& apex_jni_libraries(const std::string& apex_ns_name) {
419 static std::map<std::string, std::string> jni_libraries = InitApexLibraries("jni");
420 return jni_libraries[apex_ns_name];
421 }
422
apex_public_libraries()423 const std::map<std::string, std::string>& apex_public_libraries() {
424 static std::map<std::string, std::string> public_libraries = InitApexLibraries("public");
425 return public_libraries;
426 }
427
is_product_treblelized()428 bool is_product_treblelized() {
429 #if defined(ART_TARGET_ANDROID)
430 // Product is treblelized iff the sdk version is newer than U
431 // or launching version is R or newer or ro.product.vndk.version is defined
432 return android::modules::sdklevel::IsAtLeastV() ||
433 android::base::GetIntProperty("ro.product.first_api_level", 0) >= __ANDROID_API_R__ ||
434 android::sysprop::VndkProperties::product_vndk_version().has_value();
435 #else
436 return false;
437 #endif
438 }
439
get_vndk_version(bool is_product_vndk)440 std::string get_vndk_version(bool is_product_vndk) {
441 #if defined(ART_TARGET_ANDROID)
442 if (is_product_vndk) {
443 return android::sysprop::VndkProperties::product_vndk_version().value_or("");
444 }
445 return android::sysprop::VndkProperties::vendor_vndk_version().value_or("");
446 #else
447 if (is_product_vndk) {
448 return android::base::GetProperty("ro.product.vndk.version", "");
449 }
450 return android::base::GetProperty("ro.vndk.version", "");
451 #endif
452 }
453
454 namespace internal {
455 // Exported for testing
ParseConfig(const std::string & file_content,const std::function<Result<bool> (const ConfigEntry &)> & filter_fn)456 Result<std::vector<std::string>> ParseConfig(
457 const std::string& file_content,
458 const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
459 std::vector<std::string> lines = base::Split(file_content, "\n");
460
461 std::vector<std::string> sonames;
462 for (std::string& line : lines) {
463 std::string trimmed_line = base::Trim(line);
464 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
465 continue;
466 }
467
468 std::vector<std::string> tokens = android::base::Split(trimmed_line, " ");
469 if (tokens.size() < 1 || tokens.size() > 3) {
470 return Errorf("Malformed line \"{}\"", line);
471 }
472 struct ConfigEntry entry = {.soname = "", .nopreload = false, .bitness = ALL};
473 size_t i = tokens.size();
474 while (i-- > 0) {
475 if (tokens[i] == "nopreload") {
476 entry.nopreload = true;
477 } else if (tokens[i] == "32" || tokens[i] == "64") {
478 if (entry.bitness != ALL) {
479 return Errorf("Malformed line \"{}\": bitness can be specified only once", line);
480 }
481 entry.bitness = tokens[i] == "32" ? ONLY_32 : ONLY_64;
482 } else {
483 if (i != 0) {
484 return Errorf("Malformed line \"{}\"", line);
485 }
486 entry.soname = tokens[i];
487 }
488 }
489
490 // skip 32-bit lib on 64-bit process and vice versa
491 #if defined(__LP64__)
492 if (entry.bitness == ONLY_32) continue;
493 #else
494 if (entry.bitness == ONLY_64) continue;
495 #endif
496
497 // TODO(b/206676167): Remove this check when renderscript is officially removed.
498 #if defined(__riscv)
499 // skip renderscript lib on riscv target
500 if (entry.soname == "libRS.so") continue;
501 #endif
502
503 Result<bool> ret = filter_fn(entry);
504 if (!ret.ok()) {
505 return ret.error();
506 }
507 if (*ret) {
508 // filter_fn has returned true.
509 sonames.push_back(entry.soname);
510 }
511 }
512 return sonames;
513 }
514
515 // Parses apex.libraries.config.txt file generated by linkerconfig which looks like
516 // system/linkerconfig/testdata/golden_output/stages/apex.libraries.config.txt
517 // and returns mapping of <apex namespace> to <library list> which matches <tag>.
518 //
519 // The file is line-based and each line consists of "<tag> <apex namespace> <library list>".
520 //
521 // <tag> explains what <library list> is. (e.g "jni", "public")
522 // <library list> is colon-separated list of library names. (e.g "libfoo.so:libbar.so")
523 //
524 // If <tag> is "jni", <library list> is the list of JNI libraries exposed by <apex namespace>.
525 // If <tag> is "public", <library list> is the list of public libraries exposed by <apex namespace>.
526 // Public libraries are the libs listed in /system/etc/public.libraries.txt.
ParseApexLibrariesConfig(const std::string & file_content,const std::string & tag)527 Result<std::map<std::string, std::string>> ParseApexLibrariesConfig(const std::string& file_content, const std::string& tag) {
528 std::map<std::string, std::string> entries;
529 std::vector<std::string> lines = base::Split(file_content, "\n");
530 for (std::string& line : lines) {
531 std::string trimmed_line = base::Trim(line);
532 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
533 continue;
534 }
535 Result<ApexLibrariesConfigLine> config_line = ParseApexLibrariesConfigLine(trimmed_line);
536 if (!config_line.ok()) {
537 return config_line.error();
538 }
539 if (config_line->tag != tag) {
540 continue;
541 }
542 entries[config_line->apex_namespace] = config_line->library_list;
543 }
544 return entries;
545 }
546
547 } // namespace internal
548
549 } // namespace android::nativeloader
550