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