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