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