1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * * Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * * Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in
12 * the documentation and/or other materials provided with the
13 * distribution.
14 *
15 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
18 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
19 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
21 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
22 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
23 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
24 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
25 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29 #include "linker_config.h"
30
31 #include "linker_globals.h"
32 #include "linker_debug.h"
33 #include "linker_utils.h"
34
35 #include <android-base/file.h>
36 #include <android-base/properties.h>
37 #include <android-base/scopeguard.h>
38 #include <android-base/strings.h>
39
40 #include <async_safe/log.h>
41
42 #include <limits.h>
43 #include <stdlib.h>
44 #include <unistd.h>
45
46 #include <string>
47 #include <unordered_map>
48
49 class ConfigParser {
50 public:
51 enum {
52 kPropertyAssign,
53 kPropertyAppend,
54 kSection,
55 kEndOfFile,
56 kError,
57 };
58
ConfigParser(std::string && content)59 explicit ConfigParser(std::string&& content)
60 : content_(std::move(content)), p_(0), lineno_(0), was_end_of_file_(false) {}
61
62 /*
63 * Possible return values
64 * kPropertyAssign: name is set to property name and value is set to property value
65 * kPropertyAppend: same as kPropertyAssign, but the value should be appended
66 * kSection: name is set to section name.
67 * kEndOfFile: reached end of file.
68 * kError: error_msg is set.
69 */
next_token(std::string * name,std::string * value,std::string * error_msg)70 int next_token(std::string* name, std::string* value, std::string* error_msg) {
71 std::string line;
72 while(NextLine(&line)) {
73 size_t found = line.find('#');
74 line = android::base::Trim(line.substr(0, found));
75
76 if (line.empty()) {
77 continue;
78 }
79
80 if (line[0] == '[' && line.back() == ']') {
81 *name = line.substr(1, line.size() - 2);
82 return kSection;
83 }
84
85 size_t found_assign = line.find('=');
86 size_t found_append = line.find("+=");
87 if (found_assign != std::string::npos && found_append == std::string::npos) {
88 *name = android::base::Trim(line.substr(0, found_assign));
89 *value = android::base::Trim(line.substr(found_assign + 1));
90 return kPropertyAssign;
91 }
92
93 if (found_append != std::string::npos) {
94 *name = android::base::Trim(line.substr(0, found_append));
95 *value = android::base::Trim(line.substr(found_append + 2));
96 return kPropertyAppend;
97 }
98
99 *error_msg = std::string("invalid format: ") +
100 line +
101 ", expected \"name = property\", \"name += property\", or \"[section]\"";
102 return kError;
103 }
104
105 // to avoid infinite cycles when programmer makes a mistake
106 CHECK(!was_end_of_file_);
107 was_end_of_file_ = true;
108 return kEndOfFile;
109 }
110
lineno() const111 size_t lineno() const {
112 return lineno_;
113 }
114
115 private:
NextLine(std::string * line)116 bool NextLine(std::string* line) {
117 if (p_ == std::string::npos) {
118 return false;
119 }
120
121 size_t found = content_.find('\n', p_);
122 if (found != std::string::npos) {
123 *line = content_.substr(p_, found - p_);
124 p_ = found + 1;
125 } else {
126 *line = content_.substr(p_);
127 p_ = std::string::npos;
128 }
129
130 lineno_++;
131 return true;
132 }
133
134 std::string content_;
135 size_t p_;
136 size_t lineno_;
137 bool was_end_of_file_;
138
139 DISALLOW_IMPLICIT_CONSTRUCTORS(ConfigParser);
140 };
141
142 class PropertyValue {
143 public:
144 PropertyValue() = default;
145
PropertyValue(std::string && value,size_t lineno)146 PropertyValue(std::string&& value, size_t lineno)
147 : value_(std::move(value)), lineno_(lineno) {}
148
value() const149 const std::string& value() const {
150 return value_;
151 }
152
append_value(std::string && value)153 void append_value(std::string&& value) {
154 value_ = value_ + value;
155 // lineno isn't updated as we might have cases like this:
156 // property.x = blah
157 // property.y = blah
158 // property.x += blah
159 }
160
lineno() const161 size_t lineno() const {
162 return lineno_;
163 }
164
165 private:
166 std::string value_;
167 size_t lineno_;
168 };
169
create_error_msg(const char * file,size_t lineno,const std::string & msg)170 static std::string create_error_msg(const char* file,
171 size_t lineno,
172 const std::string& msg) {
173 char buf[1024];
174 async_safe_format_buffer(buf, sizeof(buf), "%s:%zu: error: %s", file, lineno, msg.c_str());
175
176 return std::string(buf);
177 }
178
parse_config_file(const char * ld_config_file_path,const char * binary_realpath,std::unordered_map<std::string,PropertyValue> * properties,std::string * error_msg)179 static bool parse_config_file(const char* ld_config_file_path,
180 const char* binary_realpath,
181 std::unordered_map<std::string, PropertyValue>* properties,
182 std::string* error_msg) {
183 std::string content;
184 if (!android::base::ReadFileToString(ld_config_file_path, &content)) {
185 if (errno != ENOENT) {
186 *error_msg = std::string("error reading file \"") +
187 ld_config_file_path + "\": " + strerror(errno);
188 }
189 return false;
190 }
191
192 ConfigParser cp(std::move(content));
193
194 std::string section_name;
195
196 while (true) {
197 std::string name;
198 std::string value;
199 std::string error;
200
201 int result = cp.next_token(&name, &value, &error);
202 if (result == ConfigParser::kError) {
203 DL_WARN("%s:%zd: warning: couldn't parse %s (ignoring this line)",
204 ld_config_file_path,
205 cp.lineno(),
206 error.c_str());
207 continue;
208 }
209
210 if (result == ConfigParser::kSection || result == ConfigParser::kEndOfFile) {
211 return false;
212 }
213
214 if (result == ConfigParser::kPropertyAssign) {
215 if (!android::base::StartsWith(name, "dir.")) {
216 DL_WARN("%s:%zd: warning: unexpected property name \"%s\", "
217 "expected format dir.<section_name> (ignoring this line)",
218 ld_config_file_path,
219 cp.lineno(),
220 name.c_str());
221 continue;
222 }
223
224 // remove trailing '/'
225 while (!value.empty() && value.back() == '/') {
226 value.pop_back();
227 }
228
229 if (value.empty()) {
230 DL_WARN("%s:%zd: warning: property value is empty (ignoring this line)",
231 ld_config_file_path,
232 cp.lineno());
233 continue;
234 }
235
236 // If the path can be resolved, resolve it
237 char buf[PATH_MAX];
238 std::string resolved_path;
239 if (access(value.c_str(), R_OK) != 0) {
240 if (errno == ENOENT) {
241 // no need to test for non-existing path. skip.
242 continue;
243 }
244 // If not accessible, don't call realpath as it will just cause
245 // SELinux denial spam. Use the path unresolved.
246 resolved_path = value;
247 } else if (realpath(value.c_str(), buf)) {
248 resolved_path = buf;
249 } else {
250 // realpath is expected to fail with EPERM in some situations, so log
251 // the failure with INFO rather than DL_WARN. e.g. A binary in
252 // /data/local/tmp may attempt to stat /postinstall. See
253 // http://b/120996057.
254 LD_DEBUG(any, "%s:%zd: warning: path \"%s\" couldn't be resolved: %m",
255 ld_config_file_path, cp.lineno(), value.c_str());
256 resolved_path = value;
257 }
258
259 if (file_is_under_dir(binary_realpath, resolved_path)) {
260 section_name = name.substr(4);
261 break;
262 }
263 }
264 }
265
266 LD_DEBUG(any, "[ Using config section \"%s\" ]", section_name.c_str());
267
268 // skip everything until we meet a correct section
269 while (true) {
270 std::string name;
271 std::string value;
272 std::string error;
273
274 int result = cp.next_token(&name, &value, &error);
275
276 if (result == ConfigParser::kSection && name == section_name) {
277 break;
278 }
279
280 if (result == ConfigParser::kEndOfFile) {
281 *error_msg = create_error_msg(ld_config_file_path,
282 cp.lineno(),
283 std::string("section \"") + section_name + "\" not found");
284 return false;
285 }
286 }
287
288 // found the section - parse it
289 while (true) {
290 std::string name;
291 std::string value;
292 std::string error;
293
294 int result = cp.next_token(&name, &value, &error);
295
296 if (result == ConfigParser::kEndOfFile || result == ConfigParser::kSection) {
297 break;
298 }
299
300 if (result == ConfigParser::kPropertyAssign) {
301 if (properties->contains(name)) {
302 DL_WARN("%s:%zd: warning: redefining property \"%s\" (overriding previous value)",
303 ld_config_file_path,
304 cp.lineno(),
305 name.c_str());
306 }
307
308 (*properties)[name] = PropertyValue(std::move(value), cp.lineno());
309 } else if (result == ConfigParser::kPropertyAppend) {
310 if (!properties->contains(name)) {
311 DL_WARN("%s:%zd: warning: appending to undefined property \"%s\" (treating as assignment)",
312 ld_config_file_path,
313 cp.lineno(),
314 name.c_str());
315 (*properties)[name] = PropertyValue(std::move(value), cp.lineno());
316 } else {
317 if (android::base::EndsWith(name, ".links") ||
318 android::base::EndsWith(name, ".namespaces")) {
319 value = "," + value;
320 (*properties)[name].append_value(std::move(value));
321 } else if (android::base::EndsWith(name, ".paths") ||
322 android::base::EndsWith(name, ".shared_libs") ||
323 android::base::EndsWith(name, ".whitelisted") ||
324 android::base::EndsWith(name, ".allowed_libs")) {
325 value = ":" + value;
326 (*properties)[name].append_value(std::move(value));
327 } else {
328 DL_WARN("%s:%zd: warning: += isn't allowed for property \"%s\" (ignoring)",
329 ld_config_file_path,
330 cp.lineno(),
331 name.c_str());
332 }
333 }
334 }
335
336 if (result == ConfigParser::kError) {
337 DL_WARN("%s:%zd: warning: couldn't parse %s (ignoring this line)",
338 ld_config_file_path,
339 cp.lineno(),
340 error.c_str());
341 continue;
342 }
343 }
344
345 return true;
346 }
347
348 static Config g_config;
349
350 static constexpr const char* kDefaultConfigName = "default";
351 static constexpr const char* kPropertyAdditionalNamespaces = "additional.namespaces";
352
353 class Properties {
354 public:
Properties(std::unordered_map<std::string,PropertyValue> && properties)355 explicit Properties(std::unordered_map<std::string, PropertyValue>&& properties)
356 : properties_(std::move(properties)), target_sdk_version_(__ANDROID_API__) {}
357
get_strings(const std::string & name,size_t * lineno=nullptr) const358 std::vector<std::string> get_strings(const std::string& name, size_t* lineno = nullptr) const {
359 auto it = find_property(name, lineno);
360 if (it == properties_.end()) {
361 // return empty vector
362 return std::vector<std::string>();
363 }
364
365 std::vector<std::string> strings = android::base::Split(it->second.value(), ",");
366
367 for (size_t i = 0; i < strings.size(); ++i) {
368 strings[i] = android::base::Trim(strings[i]);
369 }
370
371 return strings;
372 }
373
get_bool(const std::string & name,size_t * lineno=nullptr) const374 bool get_bool(const std::string& name, size_t* lineno = nullptr) const {
375 auto it = find_property(name, lineno);
376 if (it == properties_.end()) {
377 return false;
378 }
379
380 return it->second.value() == "true";
381 }
382
get_string(const std::string & name,size_t * lineno=nullptr) const383 std::string get_string(const std::string& name, size_t* lineno = nullptr) const {
384 auto it = find_property(name, lineno);
385 return (it == properties_.end()) ? "" : it->second.value();
386 }
387
get_paths(const std::string & name,bool resolve,size_t * lineno=nullptr)388 std::vector<std::string> get_paths(const std::string& name, bool resolve, size_t* lineno = nullptr) {
389 std::string paths_str = get_string(name, lineno);
390
391 std::vector<std::string> paths;
392 split_path(paths_str.c_str(), ":", &paths);
393
394 std::vector<std::pair<std::string, std::string>> params;
395 params.push_back({ "LIB", kLibPath });
396 if (target_sdk_version_ != 0) {
397 char buf[16];
398 async_safe_format_buffer(buf, sizeof(buf), "%d", target_sdk_version_);
399 params.push_back({ "SDK_VER", buf });
400 }
401
402 static std::string vndk_ver = Config::get_vndk_version_string('-');
403 params.push_back({ "VNDK_VER", vndk_ver });
404 static std::string vndk_apex_ver = Config::get_vndk_version_string('v');
405 params.push_back({ "VNDK_APEX_VER", vndk_apex_ver });
406
407 for (auto& path : paths) {
408 format_string(&path, params);
409 }
410
411 if (resolve) {
412 std::vector<std::string> resolved_paths;
413 for (const auto& path : paths) {
414 if (path.empty()) {
415 continue;
416 }
417 // this is single threaded. no need to lock
418 auto cached = resolved_paths_.find(path);
419 if (cached == resolved_paths_.end()) {
420 resolved_paths_[path] = resolve_path(path);
421 cached = resolved_paths_.find(path);
422 }
423 CHECK(cached != resolved_paths_.end());
424 if (cached->second.empty()) {
425 continue;
426 }
427 resolved_paths.push_back(cached->second);
428 }
429
430 return resolved_paths;
431 } else {
432 return paths;
433 }
434 }
435
set_target_sdk_version(int target_sdk_version)436 void set_target_sdk_version(int target_sdk_version) {
437 target_sdk_version_ = target_sdk_version;
438 }
439
440 private:
441 std::unordered_map<std::string, PropertyValue>::const_iterator
find_property(const std::string & name,size_t * lineno) const442 find_property(const std::string& name, size_t* lineno) const {
443 auto it = properties_.find(name);
444 if (it != properties_.end() && lineno != nullptr) {
445 *lineno = it->second.lineno();
446 }
447
448 return it;
449 }
450 std::unordered_map<std::string, PropertyValue> properties_;
451 std::unordered_map<std::string, std::string> resolved_paths_;
452 int target_sdk_version_;
453
454 DISALLOW_IMPLICIT_CONSTRUCTORS(Properties);
455 };
456
read_binary_config(const char * ld_config_file_path,const char * binary_realpath,bool is_asan,bool is_hwasan,const Config ** config,std::string * error_msg)457 bool Config::read_binary_config(const char* ld_config_file_path,
458 const char* binary_realpath,
459 bool is_asan,
460 bool is_hwasan,
461 const Config** config,
462 std::string* error_msg) {
463 g_config.clear();
464
465 std::unordered_map<std::string, PropertyValue> property_map;
466 if (!parse_config_file(ld_config_file_path, binary_realpath, &property_map, error_msg)) {
467 return false;
468 }
469
470 Properties properties(std::move(property_map));
471
472 auto failure_guard = android::base::make_scope_guard([] { g_config.clear(); });
473
474 std::unordered_map<std::string, NamespaceConfig*> namespace_configs;
475
476 namespace_configs[kDefaultConfigName] = g_config.create_namespace_config(kDefaultConfigName);
477
478 std::vector<std::string> additional_namespaces = properties.get_strings(kPropertyAdditionalNamespaces);
479 for (const auto& name : additional_namespaces) {
480 namespace_configs[name] = g_config.create_namespace_config(name);
481 }
482
483 bool versioning_enabled = properties.get_bool("enable.target.sdk.version");
484 int target_sdk_version = __ANDROID_API__;
485 if (versioning_enabled) {
486 std::string version_file = dirname(binary_realpath) + "/.version";
487 std::string content;
488 if (!android::base::ReadFileToString(version_file, &content)) {
489 if (errno != ENOENT) {
490 *error_msg = std::string("error reading version file \"") +
491 version_file + "\": " + strerror(errno);
492 return false;
493 }
494 } else {
495 content = android::base::Trim(content);
496 errno = 0;
497 char* end = nullptr;
498 const char* content_str = content.c_str();
499 int result = strtol(content_str, &end, 10);
500 if (errno == 0 && *end == '\0' && result > 0) {
501 target_sdk_version = result;
502 properties.set_target_sdk_version(target_sdk_version);
503 } else {
504 *error_msg = std::string("invalid version \"") + version_file + "\": \"" + content +"\"";
505 return false;
506 }
507 }
508 }
509
510 g_config.set_target_sdk_version(target_sdk_version);
511
512 for (const auto& ns_config_it : namespace_configs) {
513 auto& name = ns_config_it.first;
514 NamespaceConfig* ns_config = ns_config_it.second;
515
516 std::string property_name_prefix = std::string("namespace.") + name;
517
518 size_t lineno = 0;
519 std::vector<std::string> linked_namespaces =
520 properties.get_strings(property_name_prefix + ".links", &lineno);
521
522 for (const auto& linked_ns_name : linked_namespaces) {
523 if (!namespace_configs.contains(linked_ns_name)) {
524 *error_msg = create_error_msg(ld_config_file_path,
525 lineno,
526 std::string("undefined namespace: ") + linked_ns_name);
527 return false;
528 }
529
530 bool allow_all_shared_libs = properties.get_bool(property_name_prefix + ".link." +
531 linked_ns_name + ".allow_all_shared_libs");
532
533 std::string shared_libs = properties.get_string(property_name_prefix +
534 ".link." +
535 linked_ns_name +
536 ".shared_libs", &lineno);
537
538 if (!allow_all_shared_libs && shared_libs.empty()) {
539 *error_msg = create_error_msg(ld_config_file_path,
540 lineno,
541 std::string("list of shared_libs for ") +
542 name +
543 "->" +
544 linked_ns_name +
545 " link is not specified or is empty.");
546 return false;
547 }
548
549 if (allow_all_shared_libs && !shared_libs.empty()) {
550 *error_msg = create_error_msg(ld_config_file_path, lineno,
551 std::string("both shared_libs and allow_all_shared_libs "
552 "are set for ") +
553 name + "->" + linked_ns_name + " link.");
554 return false;
555 }
556
557 ns_config->add_namespace_link(linked_ns_name, shared_libs, allow_all_shared_libs);
558 }
559
560 ns_config->set_isolated(properties.get_bool(property_name_prefix + ".isolated"));
561 ns_config->set_visible(properties.get_bool(property_name_prefix + ".visible"));
562
563 std::string allowed_libs =
564 properties.get_string(property_name_prefix + ".whitelisted", &lineno);
565 const std::string libs = properties.get_string(property_name_prefix + ".allowed_libs", &lineno);
566 if (!allowed_libs.empty() && !libs.empty()) {
567 allowed_libs += ":";
568 }
569 allowed_libs += libs;
570 if (!allowed_libs.empty()) {
571 ns_config->set_allowed_libs(android::base::Split(allowed_libs, ":"));
572 }
573
574 // these are affected by is_asan flag
575 if (is_asan) {
576 property_name_prefix += ".asan";
577 } else if (is_hwasan) {
578 property_name_prefix += ".hwasan";
579 }
580
581 // search paths are resolved (canonicalized). This is required mainly for
582 // the case when /vendor is a symlink to /system/vendor, which is true for
583 // non Treble-ized legacy devices.
584 ns_config->set_search_paths(properties.get_paths(property_name_prefix + ".search.paths", true));
585
586 // However, for permitted paths, we are not required to resolve the paths
587 // since they are only set for isolated namespaces, which implies the device
588 // is Treble-ized (= /vendor is not a symlink to /system/vendor).
589 // In fact, the resolving is causing an unexpected side effect of selinux
590 // denials on some executables which are not allowed to access some of the
591 // permitted paths.
592 ns_config->set_permitted_paths(properties.get_paths(property_name_prefix + ".permitted.paths", false));
593 }
594
595 failure_guard.Disable();
596 *config = &g_config;
597 return true;
598 }
599
get_vndk_version_string(const char delimiter)600 std::string Config::get_vndk_version_string(const char delimiter) {
601 std::string version = android::base::GetProperty("ro.vndk.version", "");
602 if (version != "" && version != "current") {
603 //add the delimiter char in front of the string and return it.
604 return version.insert(0, 1, delimiter);
605 }
606 return "";
607 }
608
create_namespace_config(const std::string & name)609 NamespaceConfig* Config::create_namespace_config(const std::string& name) {
610 namespace_configs_.push_back(std::unique_ptr<NamespaceConfig>(new NamespaceConfig(name)));
611 NamespaceConfig* ns_config_ptr = namespace_configs_.back().get();
612 namespace_configs_map_[name] = ns_config_ptr;
613 return ns_config_ptr;
614 }
615
clear()616 void Config::clear() {
617 namespace_configs_.clear();
618 namespace_configs_map_.clear();
619 }
620