1 /*
2 * Copyright (C) 2021 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 #include "derive_classpath.h"
18 #include <android-base/file.h>
19 #include <android-base/logging.h>
20 #include <android-base/strings.h>
21 #include <android-modules-utils/sdk_level.h>
22 #include <android-modules-utils/unbounded_sdk_level.h>
23 #include <glob.h>
24 #include <regex>
25 #include <sstream>
26
27 #include "packages/modules/common/proto/classpaths.pb.h"
28
29 namespace android {
30 namespace derive_classpath {
31
32 using Filepaths = std::vector<std::string>;
33 using Classpaths = std::unordered_map<Classpath, Filepaths>;
34
35 // Matches path of format: /apex/<module-name>@<version-digits-only>/*
36 static const std::regex kBindMountedApex("/apex/[^/]+@[0-9]+/");
37 // Capture module name in following formats:
38 // - /apex/<module-name>/*
39 // - /apex/<module-name>@*/*
40 static const std::regex kApexPathRegex("(/apex/[^@/]+)(?:@[^@/]+)?/");
41
42 static const std::string kBootclasspathFragmentLocation = "/etc/classpaths/bootclasspath.pb";
43 static const std::string kSystemserverclasspathFragmentLocation =
44 "/etc/classpaths/systemserverclasspath.pb";
45
getBootclasspathFragmentGlobPatterns(const Args & args)46 std::vector<std::string> getBootclasspathFragmentGlobPatterns(const Args& args) {
47 // Scan only specific directory for fragments if scan_dir is specified
48 if (!args.scan_dirs.empty()) {
49 std::vector<std::string> patterns;
50 for (const auto& scan_dir : args.scan_dirs) {
51 patterns.push_back(scan_dir + kBootclasspathFragmentLocation);
52 }
53 return patterns;
54 }
55
56 // Defines the order of individual fragments to be merged for BOOTCLASSPATH:
57 // 1. Jars in ART module always come first;
58 // 2. Jars defined as part of /system/etc/classpaths;
59 // 3. Jars defined in all non-ART apexes that expose /apex/*/etc/classpaths fragments.
60 //
61 // Notes:
62 // - Relative order in the individual fragment files is not changed when merging.
63 // - If a fragment file is matched by multiple globs, the first one is used; i.e. ART module
64 // fragment is only parsed once, even if there is a "/apex/*/" pattern later.
65 // - If there are multiple files matched for a glob pattern with wildcards, the results are sorted
66 // by pathname (default glob behaviour); i.e. all fragment files are sorted within a single
67 // "pattern block".
68 std::vector<std::string> patterns = {
69 // ART module is a special case and must come first before any other classpath entries.
70 "/apex/com.android.art" + kBootclasspathFragmentLocation,
71 };
72 if (args.system_bootclasspath_fragment.empty()) {
73 patterns.emplace_back("/system" + kBootclasspathFragmentLocation);
74 } else {
75 // TODO: Avoid applying glob(3) expansion later to this path. Although the caller should not
76 // provide a path that contains '*', it can technically happen. Instead of checking the string
77 // format, we should just avoid the glob(3) for this string.
78 patterns.emplace_back(args.system_bootclasspath_fragment);
79 }
80 patterns.emplace_back("/apex/*" + kBootclasspathFragmentLocation);
81 return patterns;
82 }
83
getSystemserverclasspathFragmentGlobPatterns(const Args & args)84 std::vector<std::string> getSystemserverclasspathFragmentGlobPatterns(const Args& args) {
85 // Scan only specific directory for fragments if scan_dir is specified
86 if (!args.scan_dirs.empty()) {
87 std::vector<std::string> patterns;
88 for (const auto& scan_dir : args.scan_dirs) {
89 patterns.push_back(scan_dir + kSystemserverclasspathFragmentLocation);
90 }
91 return patterns;
92 }
93
94 // Defines the order of individual fragments to be merged for SYSTEMSERVERCLASSPATH.
95 //
96 // ART system server jars are not special in this case, and are considered to be part of all the
97 // other apexes that may expose system server jars.
98 //
99 // All notes from getBootclasspathFragmentGlobPatterns apply here.
100 std::vector<std::string> patterns;
101 if (args.system_systemserverclasspath_fragment.empty()) {
102 patterns.emplace_back("/system" + kSystemserverclasspathFragmentLocation);
103 } else {
104 // TODO: Avoid applying glob(3) expansion later to this path. See above.
105 patterns.emplace_back(args.system_systemserverclasspath_fragment);
106 }
107 patterns.emplace_back("/apex/*" + kSystemserverclasspathFragmentLocation);
108 return patterns;
109 };
110
111 // Finds all classpath fragment files that match the glob pattern and appends them to `fragments`.
112 //
113 // If a newly found fragment is already present in `fragments`, it is skipped to avoid duplicates.
114 // Note that appended fragment files are sorted by pathnames, which is a default behaviour for
115 // glob().
116 //
117 // glob_pattern_prefix is only populated for unit tests so that we can search for pattern in a test
118 // directory instead of from root.
GlobClasspathFragments(Filepaths * fragments,const std::string & glob_pattern_prefix,const std::string & pattern)119 bool GlobClasspathFragments(Filepaths* fragments, const std::string& glob_pattern_prefix,
120 const std::string& pattern) {
121 glob_t glob_result;
122 const int ret = glob((glob_pattern_prefix + pattern).c_str(), GLOB_MARK, nullptr, &glob_result);
123 if (ret != 0 && ret != GLOB_NOMATCH) {
124 globfree(&glob_result);
125 LOG(ERROR) << "Failed to glob " << glob_pattern_prefix + pattern;
126 return false;
127 }
128
129 for (size_t i = 0; i < glob_result.gl_pathc; i++) {
130 std::string path = glob_result.gl_pathv[i];
131 // Skip <name>@<ver> dirs, as they are bind-mounted to <name>
132 // Remove glob_pattern_prefix first since kBindMountedAPex has prefix requirement
133 if (std::regex_search(path.substr(glob_pattern_prefix.size()), kBindMountedApex)) {
134 continue;
135 }
136 // Make sure we don't push duplicate fragments from previously processed patterns
137 if (std::find(fragments->begin(), fragments->end(), path) == fragments->end()) {
138 fragments->push_back(path);
139 }
140 }
141 globfree(&glob_result);
142 return true;
143 }
144
145 // Writes the contents of *CLASSPATH variables to /data in the format expected by `load_exports`
146 // action from init.rc. See platform/system/core/init/README.md.
WriteClasspathExports(Classpaths classpaths,std::string_view output_path)147 bool WriteClasspathExports(Classpaths classpaths, std::string_view output_path) {
148 LOG(INFO) << "WriteClasspathExports " << output_path;
149
150 std::stringstream out;
151 out << "export BOOTCLASSPATH " << android::base::Join(classpaths[BOOTCLASSPATH], ':') << '\n';
152 out << "export DEX2OATBOOTCLASSPATH "
153 << android::base::Join(classpaths[DEX2OATBOOTCLASSPATH], ':') << '\n';
154 out << "export SYSTEMSERVERCLASSPATH "
155 << android::base::Join(classpaths[SYSTEMSERVERCLASSPATH], ':') << '\n';
156 out << "export STANDALONE_SYSTEMSERVER_JARS "
157 << android::base::Join(classpaths[STANDALONE_SYSTEMSERVER_JARS], ':') << '\n';
158
159 const std::string& content = out.str();
160 LOG(INFO) << "WriteClasspathExports content\n" << content;
161
162 const std::string path_str(output_path);
163 if (android::base::StartsWith(path_str, "/data/")) {
164 // When writing to /data, write to a temp file first to make sure the partition is not full.
165 const std::string temp_str(path_str + ".tmp");
166 if (!android::base::WriteStringToFile(content, temp_str, /*follow_symlinks=*/true)) {
167 return false;
168 }
169 return rename(temp_str.c_str(), path_str.c_str()) == 0;
170 } else {
171 return android::base::WriteStringToFile(content, path_str, /*follow_symlinks=*/true);
172 }
173 }
174
ReadClasspathFragment(ExportedClasspathsJars * fragment,const std::string & filepath)175 bool ReadClasspathFragment(ExportedClasspathsJars* fragment, const std::string& filepath) {
176 LOG(INFO) << "ReadClasspathFragment " << filepath;
177 std::string contents;
178 if (!android::base::ReadFileToString(filepath, &contents)) {
179 PLOG(ERROR) << "Failed to read " << filepath;
180 return false;
181 }
182 if (!fragment->ParseFromString(contents)) {
183 LOG(ERROR) << "Failed to parse " << filepath;
184 return false;
185 }
186 return true;
187 }
188
189 // Returns an allowed prefix for a jar filepaths declared in a given fragment.
190 // For a given apex fragment, it returns the apex path - "/apex/com.android.foo" - as an allowed
191 // prefix for jars. This can be used to enforce that an apex fragment only exports jars located in
192 // that apex. For system fragment, it returns an empty string to allow any jars to be exported by
193 // the platform.
GetAllowedJarPathPrefix(const std::string & fragment_path)194 std::string GetAllowedJarPathPrefix(const std::string& fragment_path) {
195 std::smatch match;
196 if (std::regex_search(fragment_path, match, kApexPathRegex)) {
197 return match[1];
198 }
199 return "";
200 }
201
202 // Finds and parses all classpath fragments on device matching given glob patterns.
ParseFragments(const Args & args,Classpaths & classpaths,bool boot_jars)203 bool ParseFragments(const Args& args, Classpaths& classpaths, bool boot_jars) {
204 LOG(INFO) << "ParseFragments for " << (boot_jars ? "bootclasspath" : "systemserverclasspath");
205
206 auto glob_patterns = boot_jars ? getBootclasspathFragmentGlobPatterns(args)
207 : getSystemserverclasspathFragmentGlobPatterns(args);
208
209 Filepaths fragments;
210 for (const auto& pattern : glob_patterns) {
211 if (!GlobClasspathFragments(&fragments, args.glob_pattern_prefix, pattern)) {
212 return false;
213 }
214 }
215
216 for (const auto& fragment_path : fragments) {
217 ExportedClasspathsJars exportedJars;
218 if (!ReadClasspathFragment(&exportedJars, fragment_path)) {
219 return false;
220 }
221
222 // Either a path to the apex, or an empty string
223 const std::string& allowed_jar_prefix = GetAllowedJarPathPrefix(fragment_path);
224
225 for (const Jar& jar : exportedJars.jars()) {
226 const std::string& jar_path = jar.path();
227 CHECK(android::base::StartsWith(jar_path, allowed_jar_prefix))
228 << fragment_path << " must not export a jar from outside of the apex: " << jar_path;
229
230 const Classpath classpath = jar.classpath();
231 CHECK(boot_jars ^
232 (classpath == SYSTEMSERVERCLASSPATH || classpath == STANDALONE_SYSTEMSERVER_JARS))
233 << fragment_path << " must not export a jar for " << Classpath_Name(classpath);
234
235 if (!jar.min_sdk_version().empty()) {
236 const auto& min_sdk_version = jar.min_sdk_version();
237 if (!android::modules::sdklevel::unbounded::IsAtLeast(min_sdk_version.c_str())) {
238 LOG(INFO) << "not installing " << jar_path << " with min_sdk_version " << min_sdk_version;
239 continue;
240 }
241 }
242
243 if (!jar.max_sdk_version().empty()) {
244 const auto& max_sdk_version = jar.max_sdk_version();
245 if (!android::modules::sdklevel::unbounded::IsAtMost(max_sdk_version.c_str())) {
246 LOG(INFO) << "not installing " << jar_path << " with max_sdk_version " << max_sdk_version;
247 continue;
248 }
249 }
250
251 classpaths[classpath].push_back(jar_path);
252 }
253 }
254 return true;
255 }
256
257 // Generates /data/system/environ/classpath exports file by globing and merging individual
258 // classpaths.proto config fragments. The exports file is read by init.rc to setenv *CLASSPATH
259 // environ variables at runtime.
GenerateClasspathExports(const Args & args)260 bool GenerateClasspathExports(const Args& args) {
261 // Parse all known classpath fragments
262 CHECK(android::modules::sdklevel::IsAtLeastS())
263 << "derive_classpath must only be run on Android 12 or above";
264
265 Classpaths classpaths;
266 if (!ParseFragments(args, classpaths, /*boot_jars=*/true)) {
267 LOG(ERROR) << "Failed to parse BOOTCLASSPATH fragments";
268 return false;
269 }
270 if (!ParseFragments(args, classpaths, /*boot_jars=*/false)) {
271 LOG(ERROR) << "Failed to parse SYSTEMSERVERCLASSPATH fragments";
272 return false;
273 }
274
275 // Write export actions for init.rc
276 if (!WriteClasspathExports(classpaths, args.output_path)) {
277 PLOG(ERROR) << "Failed to write " << args.output_path;
278 return false;
279 }
280 return true;
281 }
282
283 } // namespace derive_classpath
284 } // namespace android
285