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