blob: fc99c367706bd537265f1baf9d1f22f3cf5fd7e9 [file] [log] [blame]
Orion Hodson9b16e342019-10-09 13:29:16 +01001/*
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
Justin Yun3db26d52019-12-16 14:09:39 +090033#if defined(__ANDROID__)
34#include <android/sysprop/VndkProperties.sysprop.h>
35#endif
36
Orion Hodson9b16e342019-10-09 13:29:16 +010037#include "utils.h"
38
39namespace android::nativeloader {
40
41using namespace internal;
42using namespace ::std::string_literals;
43using android::base::ErrnoError;
Orion Hodson9b16e342019-10-09 13:29:16 +010044using android::base::Result;
45
46namespace {
47
48constexpr const char* kDefaultPublicLibrariesFile = "/etc/public.libraries.txt";
49constexpr const char* kExtendedPublicLibrariesFilePrefix = "public.libraries-";
50constexpr const char* kExtendedPublicLibrariesFileSuffix = ".txt";
51constexpr const char* kVendorPublicLibrariesFile = "/vendor/etc/public.libraries.txt";
52constexpr const char* kLlndkLibrariesFile = "/system/etc/llndk.libraries.txt";
53constexpr const char* kVndkLibrariesFile = "/system/etc/vndksp.libraries.txt";
54
55const std::vector<const std::string> kArtApexPublicLibraries = {
56 "libicuuc.so",
57 "libicui18n.so",
58};
59
60constexpr const char* kArtApexLibPath = "/apex/com.android.art/" LIB;
61
62constexpr const char* kNeuralNetworksApexPublicLibrary = "libneuralnetworks.so";
Luke Huang5c017722019-12-17 10:54:26 +080063// STOPSHIP(b/146420818): Figure out how to use stub or non-specific lib name for libcronet.
64constexpr const char* kCronetApexPublicLibrary = "libcronet.80.0.3986.0.so";
Orion Hodson9b16e342019-10-09 13:29:16 +010065
66// TODO(b/130388701): do we need this?
67std::string root_dir() {
68 static const char* android_root_env = getenv("ANDROID_ROOT");
69 return android_root_env != nullptr ? android_root_env : "/system";
70}
71
72bool debuggable() {
73 static bool debuggable = android::base::GetBoolProperty("ro.debuggable", false);
74 return debuggable;
75}
76
77std::string vndk_version_str() {
78 static std::string version = android::base::GetProperty("ro.vndk.version", "");
79 if (version != "" && version != "current") {
80 return "." + version;
81 }
82 return "";
83}
84
85// For debuggable platform builds use ANDROID_ADDITIONAL_PUBLIC_LIBRARIES environment
86// variable to add libraries to the list. This is intended for platform tests only.
87std::string additional_public_libraries() {
88 if (debuggable()) {
89 const char* val = getenv("ANDROID_ADDITIONAL_PUBLIC_LIBRARIES");
90 return val ? val : "";
91 }
92 return "";
93}
94
95void InsertVndkVersionStr(std::string* file_name) {
96 CHECK(file_name != nullptr);
97 size_t insert_pos = file_name->find_last_of(".");
98 if (insert_pos == std::string::npos) {
99 insert_pos = file_name->length();
100 }
101 file_name->insert(insert_pos, vndk_version_str());
102}
103
104const std::function<Result<bool>(const struct ConfigEntry&)> always_true =
105 [](const struct ConfigEntry&) -> Result<bool> { return true; };
106
107Result<std::vector<std::string>> ReadConfig(
108 const std::string& configFile,
109 const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
110 std::string file_content;
111 if (!base::ReadFileToString(configFile, &file_content)) {
112 return ErrnoError();
113 }
114 Result<std::vector<std::string>> result = ParseConfig(file_content, filter_fn);
115 if (!result) {
116 return Errorf("Cannot parse {}: {}", configFile, result.error().message());
117 }
118 return result;
119}
120
121void ReadExtensionLibraries(const char* dirname, std::vector<std::string>* sonames) {
122 std::unique_ptr<DIR, decltype(&closedir)> dir(opendir(dirname), closedir);
123 if (dir != nullptr) {
124 // Failing to opening the dir is not an error, which can happen in
125 // webview_zygote.
126 while (struct dirent* ent = readdir(dir.get())) {
127 if (ent->d_type != DT_REG && ent->d_type != DT_LNK) {
128 continue;
129 }
130 const std::string filename(ent->d_name);
131 std::string_view fn = filename;
132 if (android::base::ConsumePrefix(&fn, kExtendedPublicLibrariesFilePrefix) &&
133 android::base::ConsumeSuffix(&fn, kExtendedPublicLibrariesFileSuffix)) {
134 const std::string company_name(fn);
135 const std::string config_file_path = dirname + "/"s + filename;
136 LOG_ALWAYS_FATAL_IF(
137 company_name.empty(),
138 "Error extracting company name from public native library list file path \"%s\"",
139 config_file_path.c_str());
140
141 auto ret = ReadConfig(
142 config_file_path, [&company_name](const struct ConfigEntry& entry) -> Result<bool> {
143 if (android::base::StartsWith(entry.soname, "lib") &&
144 android::base::EndsWith(entry.soname, "." + company_name + ".so")) {
145 return true;
146 } else {
147 return Errorf("Library name \"{}\" does not end with the company name {}.",
148 entry.soname, company_name);
149 }
150 });
151 if (ret) {
152 sonames->insert(sonames->end(), ret->begin(), ret->end());
153 } else {
154 LOG_ALWAYS_FATAL("Error reading public native library list from \"%s\": %s",
155 config_file_path.c_str(), ret.error().message().c_str());
156 }
157 }
158 }
159 }
160}
161
162static std::string InitDefaultPublicLibraries(bool for_preload) {
163 std::string config_file = root_dir() + kDefaultPublicLibrariesFile;
164 auto sonames =
165 ReadConfig(config_file, [&for_preload](const struct ConfigEntry& entry) -> Result<bool> {
166 if (for_preload) {
167 return !entry.nopreload;
168 } else {
169 return true;
170 }
171 });
172 if (!sonames) {
173 LOG_ALWAYS_FATAL("Error reading public native library list from \"%s\": %s",
174 config_file.c_str(), sonames.error().message().c_str());
175 return "";
176 }
177
178 std::string additional_libs = additional_public_libraries();
179 if (!additional_libs.empty()) {
180 auto vec = base::Split(additional_libs, ":");
181 std::copy(vec.begin(), vec.end(), std::back_inserter(*sonames));
182 }
183
184 // If this is for preloading libs, don't remove the libs from APEXes.
185 if (for_preload) {
186 return android::base::Join(*sonames, ':');
187 }
188
189 // Remove the public libs in the art namespace.
190 // These libs are listed in public.android.txt, but we don't want the rest of android
191 // in default namespace to dlopen the libs.
192 // For example, libicuuc.so is exposed to classloader namespace from art namespace.
193 // Unfortunately, it does not have stable C symbols, and default namespace should only use
194 // stable symbols in libandroidicu.so. http://b/120786417
195 for (const std::string& lib_name : kArtApexPublicLibraries) {
196 std::string path(kArtApexLibPath);
197 path.append("/").append(lib_name);
198
199 struct stat s;
200 // Do nothing if the path in /apex does not exist.
201 // Runtime APEX must be mounted since libnativeloader is in the same APEX
202 if (stat(path.c_str(), &s) != 0) {
203 continue;
204 }
205
206 auto it = std::find(sonames->begin(), sonames->end(), lib_name);
207 if (it != sonames->end()) {
208 sonames->erase(it);
209 }
210 }
211
212 // Remove the public libs in the nnapi namespace.
213 auto it = std::find(sonames->begin(), sonames->end(), kNeuralNetworksApexPublicLibrary);
214 if (it != sonames->end()) {
215 sonames->erase(it);
216 }
217 return android::base::Join(*sonames, ':');
218}
219
220static std::string InitArtPublicLibraries() {
221 CHECK(sizeof(kArtApexPublicLibraries) > 0);
222 std::string list = android::base::Join(kArtApexPublicLibraries, ":");
223
224 std::string additional_libs = additional_public_libraries();
225 if (!additional_libs.empty()) {
226 list = list + ':' + additional_libs;
227 }
228 return list;
229}
230
231static std::string InitVendorPublicLibraries() {
232 // This file is optional, quietly ignore if the file does not exist.
233 auto sonames = ReadConfig(kVendorPublicLibrariesFile, always_true);
234 if (!sonames) {
235 return "";
236 }
237 return android::base::Join(*sonames, ':');
238}
239
Justin Yun0cc40272019-12-16 16:47:40 +0900240// read /system/etc/public.libraries-<companyname>.txt,
241// /system_ext/etc/public.libraries-<companyname>.txt and
Orion Hodson9b16e342019-10-09 13:29:16 +0100242// /product/etc/public.libraries-<companyname>.txt which contain partner defined
243// system libs that are exposed to apps. The libs in the txt files must be
244// named as lib<name>.<companyname>.so.
245static std::string InitExtendedPublicLibraries() {
246 std::vector<std::string> sonames;
247 ReadExtensionLibraries("/system/etc", &sonames);
Justin Yun0cc40272019-12-16 16:47:40 +0900248 ReadExtensionLibraries("/system_ext/etc", &sonames);
Orion Hodson9b16e342019-10-09 13:29:16 +0100249 ReadExtensionLibraries("/product/etc", &sonames);
250 return android::base::Join(sonames, ':');
251}
252
253static std::string InitLlndkLibraries() {
254 std::string config_file = kLlndkLibrariesFile;
255 InsertVndkVersionStr(&config_file);
256 auto sonames = ReadConfig(config_file, always_true);
257 if (!sonames) {
258 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
259 return "";
260 }
261 return android::base::Join(*sonames, ':');
262}
263
264static std::string InitVndkspLibraries() {
265 std::string config_file = kVndkLibrariesFile;
266 InsertVndkVersionStr(&config_file);
267 auto sonames = ReadConfig(config_file, always_true);
268 if (!sonames) {
269 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
270 return "";
271 }
272 return android::base::Join(*sonames, ':');
273}
274
275static std::string InitNeuralNetworksPublicLibraries() {
276 return kNeuralNetworksApexPublicLibrary;
277}
278
Luke Huang5c017722019-12-17 10:54:26 +0800279static std::string InitCronetPublicLibraries() {
280 return kCronetApexPublicLibrary;
281}
282
Orion Hodson9b16e342019-10-09 13:29:16 +0100283} // namespace
284
285const std::string& preloadable_public_libraries() {
286 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ true);
287 return list;
288}
289
290const std::string& default_public_libraries() {
291 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ false);
292 return list;
293}
294
295const std::string& art_public_libraries() {
296 static std::string list = InitArtPublicLibraries();
297 return list;
298}
299
300const std::string& vendor_public_libraries() {
301 static std::string list = InitVendorPublicLibraries();
302 return list;
303}
304
305const std::string& extended_public_libraries() {
306 static std::string list = InitExtendedPublicLibraries();
307 return list;
308}
309
310const std::string& neuralnetworks_public_libraries() {
311 static std::string list = InitNeuralNetworksPublicLibraries();
312 return list;
313}
314
Luke Huang5c017722019-12-17 10:54:26 +0800315const std::string& cronet_public_libraries() {
316 static std::string list = InitCronetPublicLibraries();
317 return list;
318}
319
Orion Hodson9b16e342019-10-09 13:29:16 +0100320const std::string& llndk_libraries() {
321 static std::string list = InitLlndkLibraries();
322 return list;
323}
324
325const std::string& vndksp_libraries() {
326 static std::string list = InitVndkspLibraries();
327 return list;
328}
329
Justin Yun3db26d52019-12-16 14:09:39 +0900330bool is_product_vndk_version_defined() {
331#if defined(__ANDROID__)
332 return android::sysprop::VndkProperties::product_vndk_version().has_value();
333#else
334 return false;
335#endif
336}
337
Orion Hodson9b16e342019-10-09 13:29:16 +0100338namespace internal {
339// Exported for testing
340Result<std::vector<std::string>> ParseConfig(
341 const std::string& file_content,
342 const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
343 std::vector<std::string> lines = base::Split(file_content, "\n");
344
345 std::vector<std::string> sonames;
346 for (auto& line : lines) {
347 auto trimmed_line = base::Trim(line);
348 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
349 continue;
350 }
351
352 std::vector<std::string> tokens = android::base::Split(trimmed_line, " ");
353 if (tokens.size() < 1 || tokens.size() > 3) {
354 return Errorf("Malformed line \"{}\"", line);
355 }
356 struct ConfigEntry entry = {.soname = "", .nopreload = false, .bitness = ALL};
357 size_t i = tokens.size();
358 while (i-- > 0) {
359 if (tokens[i] == "nopreload") {
360 entry.nopreload = true;
361 } else if (tokens[i] == "32" || tokens[i] == "64") {
362 if (entry.bitness != ALL) {
363 return Errorf("Malformed line \"{}\": bitness can be specified only once", line);
364 }
365 entry.bitness = tokens[i] == "32" ? ONLY_32 : ONLY_64;
366 } else {
367 if (i != 0) {
368 return Errorf("Malformed line \"{}\"", line);
369 }
370 entry.soname = tokens[i];
371 }
372 }
373
374 // skip 32-bit lib on 64-bit process and vice versa
375#if defined(__LP64__)
376 if (entry.bitness == ONLY_32) continue;
377#else
378 if (entry.bitness == ONLY_64) continue;
379#endif
380
381 Result<bool> ret = filter_fn(entry);
382 if (!ret) {
383 return ret.error();
384 }
385 if (*ret) {
386 // filter_fn has returned true.
387 sonames.push_back(entry.soname);
388 }
389 }
390 return sonames;
391}
392
393} // namespace internal
394
395} // namespace android::nativeloader