• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2020 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 #include "linkerconfig/apex.h"
17 
18 #include <algorithm>
19 #include <cstring>
20 #include <regex>
21 #include <set>
22 #include <string>
23 #include <string_view>
24 #include <vector>
25 
26 #include <android-base/file.h>
27 #include <android-base/result.h>
28 #include <android-base/strings.h>
29 #include <apexutil.h>
30 #include <unistd.h>
31 
32 #include "linkerconfig/configparser.h"
33 #include "linkerconfig/environment.h"
34 #include "linkerconfig/log.h"
35 #include "linkerconfig/stringutil.h"
36 
37 // include after log.h to avoid macro redefinition error
38 #include "com_android_apex.h"
39 
40 using android::base::ErrnoError;
41 using android::base::Error;
42 using android::base::ReadFileToString;
43 using android::base::Result;
44 using android::base::StartsWith;
45 
46 namespace {
PathExists(const std::string & path)47 bool PathExists(const std::string& path) {
48   return access(path.c_str(), F_OK) == 0;
49 }
50 
ReadPublicLibraries(const std::string & filepath)51 Result<std::set<std::string>> ReadPublicLibraries(const std::string& filepath) {
52   std::string file_content;
53   if (!android::base::ReadFileToString(filepath, &file_content)) {
54     return ErrnoError();
55   }
56   std::vector<std::string> lines = android::base::Split(file_content, "\n");
57   std::set<std::string> sonames;
58   for (auto& line : lines) {
59     auto trimmed_line = android::base::Trim(line);
60     if (trimmed_line[0] == '#' || trimmed_line.empty()) {
61       continue;
62     }
63     std::vector<std::string> tokens = android::base::Split(trimmed_line, " ");
64     if (tokens.size() < 1 || tokens.size() > 3) {
65       return Errorf("Malformed line \"{}\"", line);
66     }
67     sonames.insert(tokens[0]);
68   }
69   return sonames;
70 }
71 
Intersect(const std::vector<std::string> & as,const std::set<std::string> & bs)72 std::vector<std::string> Intersect(const std::vector<std::string>& as,
73                                    const std::set<std::string>& bs) {
74   std::vector<std::string> intersect;
75   std::copy_if(as.begin(),
76                as.end(),
77                std::back_inserter(intersect),
78                [&bs](const auto& a) { return bs.find(a) != bs.end(); });
79   return intersect;
80 }
81 
IsValidForPath(const uint_fast8_t c)82 bool IsValidForPath(const uint_fast8_t c) {
83   if (c >= 'a' && c <= 'z') return true;
84   if (c >= 'A' && c <= 'Z') return true;
85   if (c >= '0' && c <= '9') return true;
86   if (c == '-' || c == '_' || c == '.') return true;
87   return false;
88 }
89 
VerifyPath(const std::string & path)90 Result<void> VerifyPath(const std::string& path) {
91   const size_t length = path.length();
92   constexpr char lib_dir[] = "${LIB}";
93   constexpr size_t lib_dir_len = (sizeof lib_dir) - 1;
94   const std::string_view path_view(path);
95 
96   if (length == 0) {
97     return Error() << "Empty path is not allowed";
98   }
99 
100   for (size_t i = 0; i < length; i++) {
101     uint_fast8_t current_char = path[i];
102     if (current_char == '/') {
103       i++;
104       if (i >= length) {
105         return {};
106       } else if (path[i] == '/') {
107         return Error() << "'/' should not appear twice in " << path;
108       } else if (i + lib_dir_len <= length &&
109                  path_view.substr(i, lib_dir_len) == lib_dir) {
110         i += lib_dir_len - 1;
111       } else {
112         for (; i < length; i++) {
113           current_char = path[i];
114           if (current_char == '/') {
115             i--;
116             break;
117           }
118 
119           if (!IsValidForPath(current_char)) {
120             return Error() << "Invalid char '" << current_char << "' in "
121                            << path;
122           }
123         }
124       }
125     } else {
126       return Error() << "Invalid char '" << current_char << "' in " << path
127                      << " at " << i;
128     }
129   }
130 
131   return {};
132 }
133 }  // namespace
134 
135 namespace android {
136 namespace linkerconfig {
137 namespace modules {
138 
ScanActiveApexes(const std::string & root)139 Result<std::map<std::string, ApexInfo>> ScanActiveApexes(const std::string& root) {
140   std::map<std::string, ApexInfo> apexes;
141   const auto apex_root = root + apex::kApexRoot;
142   for (const auto& [path, manifest] : apex::GetActivePackages(apex_root)) {
143     bool has_bin = PathExists(path + "/bin");
144     bool has_lib = PathExists(path + "/lib") || PathExists(path + "/lib64");
145     bool has_shared_lib = manifest.requiresharedapexlibs().size() != 0;
146 
147     std::vector<std::string> permitted_paths;
148     bool visible = false;
149 
150     std::string linker_config_path = path + "/etc/linker.config.pb";
151     if (PathExists(linker_config_path)) {
152       auto linker_config = ParseLinkerConfig(linker_config_path);
153 
154       if (linker_config.ok()) {
155         permitted_paths = {linker_config->permittedpaths().begin(),
156                            linker_config->permittedpaths().end()};
157         for (const std::string& path : permitted_paths) {
158           Result<void> verify_permitted_path = VerifyPath(path);
159           if (!verify_permitted_path.ok()) {
160             return Error() << "Failed to validate path from APEX linker config"
161                            << linker_config_path << " : "
162                            << verify_permitted_path.error();
163           }
164         }
165         visible = linker_config->visible();
166       } else {
167         return Error() << "Failed to read APEX linker config : "
168                        << linker_config.error();
169       }
170     }
171 
172     ApexInfo info(manifest.name(),
173                   TrimPrefix(path, root),
174                   {manifest.providenativelibs().begin(),
175                    manifest.providenativelibs().end()},
176                   {manifest.requirenativelibs().begin(),
177                    manifest.requirenativelibs().end()},
178                   {manifest.jnilibs().begin(), manifest.jnilibs().end()},
179                   std::move(permitted_paths),
180                   has_bin,
181                   has_lib,
182                   visible,
183                   has_shared_lib);
184     apexes.emplace(manifest.name(), std::move(info));
185   }
186 
187   if (!apexes.empty()) {
188     const std::string info_list_file = apex_root + "/apex-info-list.xml";
189     auto info_list =
190         com::android::apex::readApexInfoList(info_list_file.c_str());
191     if (info_list.has_value()) {
192       for (const auto& info : info_list->getApexInfo()) {
193         apexes[info.getModuleName()].original_path =
194             info.getPreinstalledModulePath();
195       }
196     } else {
197       return ErrnoError() << "Can't read " << info_list_file;
198     }
199 
200     const std::string public_libraries_file =
201         root + "/system/etc/public.libraries.txt";
202     auto public_libraries = ReadPublicLibraries(public_libraries_file);
203     if (public_libraries.ok()) {
204       for (auto& [name, apex] : apexes) {
205         // Only system apexes can provide public libraries.
206         if (!apex.InSystem()) {
207           continue;
208         }
209         apex.public_libs = Intersect(apex.provide_libs, *public_libraries);
210       }
211     } else {
212       // Do not fail when public.libraries.txt is missing for minimal Android
213       // environment with no ART.
214       LOG(WARNING) << "Can't read " << public_libraries_file << ": "
215                    << public_libraries.error();
216     }
217   }
218 
219   return apexes;
220 }
221 
InSystem() const222 bool ApexInfo::InSystem() const {
223   return StartsWith(original_path, "/system/apex/") ||
224          StartsWith(original_path, "/system_ext/apex/") ||
225          (!IsProductVndkVersionDefined() &&
226           StartsWith(original_path, "/product/apex/"));
227 }
228 
InProduct() const229 bool ApexInfo::InProduct() const {
230   return IsProductVndkVersionDefined() &&
231          StartsWith(original_path, "/product/apex/");
232 }
233 
InVendor() const234 bool ApexInfo::InVendor() const {
235   return StartsWith(original_path, "/vendor/apex/") ||
236          StartsWith(original_path, "/odm/apex/");
237 }
238 
239 }  // namespace modules
240 }  // namespace linkerconfig
241 }  // namespace android