blob: 11c30701d91cbce3675fe9f593c858191d4dcfdb [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
235// read /system/etc/public.libraries-<companyname>.txt and
236// /product/etc/public.libraries-<companyname>.txt which contain partner defined
237// system libs that are exposed to apps. The libs in the txt files must be
238// named as lib<name>.<companyname>.so.
239static std::string InitExtendedPublicLibraries() {
240 std::vector<std::string> sonames;
241 ReadExtensionLibraries("/system/etc", &sonames);
242 ReadExtensionLibraries("/product/etc", &sonames);
243 return android::base::Join(sonames, ':');
244}
245
246static std::string InitLlndkLibraries() {
247 std::string config_file = kLlndkLibrariesFile;
248 InsertVndkVersionStr(&config_file);
249 auto sonames = ReadConfig(config_file, always_true);
250 if (!sonames) {
251 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
252 return "";
253 }
254 return android::base::Join(*sonames, ':');
255}
256
257static std::string InitVndkspLibraries() {
258 std::string config_file = kVndkLibrariesFile;
259 InsertVndkVersionStr(&config_file);
260 auto sonames = ReadConfig(config_file, always_true);
261 if (!sonames) {
262 LOG_ALWAYS_FATAL("%s", sonames.error().message().c_str());
263 return "";
264 }
265 return android::base::Join(*sonames, ':');
266}
267
268static std::string InitNeuralNetworksPublicLibraries() {
269 return kNeuralNetworksApexPublicLibrary;
270}
271
272} // namespace
273
274const std::string& preloadable_public_libraries() {
275 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ true);
276 return list;
277}
278
279const std::string& default_public_libraries() {
280 static std::string list = InitDefaultPublicLibraries(/*for_preload*/ false);
281 return list;
282}
283
284const std::string& art_public_libraries() {
285 static std::string list = InitArtPublicLibraries();
286 return list;
287}
288
289const std::string& vendor_public_libraries() {
290 static std::string list = InitVendorPublicLibraries();
291 return list;
292}
293
294const std::string& extended_public_libraries() {
295 static std::string list = InitExtendedPublicLibraries();
296 return list;
297}
298
299const std::string& neuralnetworks_public_libraries() {
300 static std::string list = InitNeuralNetworksPublicLibraries();
301 return list;
302}
303
304const std::string& llndk_libraries() {
305 static std::string list = InitLlndkLibraries();
306 return list;
307}
308
309const std::string& vndksp_libraries() {
310 static std::string list = InitVndkspLibraries();
311 return list;
312}
313
314namespace internal {
315// Exported for testing
316Result<std::vector<std::string>> ParseConfig(
317 const std::string& file_content,
318 const std::function<Result<bool>(const ConfigEntry& /* entry */)>& filter_fn) {
319 std::vector<std::string> lines = base::Split(file_content, "\n");
320
321 std::vector<std::string> sonames;
322 for (auto& line : lines) {
323 auto trimmed_line = base::Trim(line);
324 if (trimmed_line[0] == '#' || trimmed_line.empty()) {
325 continue;
326 }
327
328 std::vector<std::string> tokens = android::base::Split(trimmed_line, " ");
329 if (tokens.size() < 1 || tokens.size() > 3) {
330 return Errorf("Malformed line \"{}\"", line);
331 }
332 struct ConfigEntry entry = {.soname = "", .nopreload = false, .bitness = ALL};
333 size_t i = tokens.size();
334 while (i-- > 0) {
335 if (tokens[i] == "nopreload") {
336 entry.nopreload = true;
337 } else if (tokens[i] == "32" || tokens[i] == "64") {
338 if (entry.bitness != ALL) {
339 return Errorf("Malformed line \"{}\": bitness can be specified only once", line);
340 }
341 entry.bitness = tokens[i] == "32" ? ONLY_32 : ONLY_64;
342 } else {
343 if (i != 0) {
344 return Errorf("Malformed line \"{}\"", line);
345 }
346 entry.soname = tokens[i];
347 }
348 }
349
350 // skip 32-bit lib on 64-bit process and vice versa
351#if defined(__LP64__)
352 if (entry.bitness == ONLY_32) continue;
353#else
354 if (entry.bitness == ONLY_64) continue;
355#endif
356
357 Result<bool> ret = filter_fn(entry);
358 if (!ret) {
359 return ret.error();
360 }
361 if (*ret) {
362 // filter_fn has returned true.
363 sonames.push_back(entry.soname);
364 }
365 }
366 return sonames;
367}
368
369} // namespace internal
370
371} // namespace android::nativeloader