blob: d2a1b7fb838abf466be7d762421881ca6b1ee6bd [file] [log] [blame]
Calin Juravle87e2cb62017-06-13 21:48:45 -07001/*
2 * Copyright (C) 2017 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 "class_loader_context.h"
18
Andreas Gampef9411702018-09-06 17:16:57 -070019#include <android-base/parseint.h>
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +000020#include <android-base/strings.h>
Andreas Gampef9411702018-09-06 17:16:57 -070021
Calin Juravle57d0acc2017-07-11 17:41:30 -070022#include "art_field-inl.h"
Vladimir Marko78baed52018-10-11 10:44:58 +010023#include "base/casts.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070024#include "base/dchecked_vector.h"
Andreas Gampe19f54162019-05-14 16:16:28 -070025#include "base/file_utils.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070026#include "base/stl_util.h"
27#include "class_linker.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070028#include "class_loader_utils.h"
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000029#include "class_root.h"
David Sehr013fd802018-01-11 22:55:24 -080030#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080031#include "dex/dex_file.h"
32#include "dex/dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070033#include "handle_scope-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010034#include "jni/jni_internal.h"
Vladimir Markobdc93b42019-03-29 16:12:04 +000035#include "mirror/class_loader-inl.h"
Alex Lighta9bbc082019-11-14 14:51:41 -080036#include "mirror/object.h"
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000037#include "mirror/object_array-alloc-inl.h"
38#include "nativehelper/scoped_local_ref.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070039#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070040#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070041#include "runtime.h"
42#include "scoped_thread_state_change-inl.h"
43#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070044#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070045
46namespace art {
47
48static constexpr char kPathClassLoaderString[] = "PCL";
49static constexpr char kDelegateLastClassLoaderString[] = "DLC";
David Brazdil1a9ac532019-03-05 11:57:13 +000050static constexpr char kInMemoryDexClassLoaderString[] = "IMC";
Calin Juravle87e2cb62017-06-13 21:48:45 -070051static constexpr char kClassLoaderOpeningMark = '[';
52static constexpr char kClassLoaderClosingMark = ']';
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000053static constexpr char kClassLoaderSharedLibraryOpeningMark = '{';
54static constexpr char kClassLoaderSharedLibraryClosingMark = '}';
55static constexpr char kClassLoaderSharedLibrarySeparator = '#';
Calin Juravle7b0648a2017-07-07 18:40:50 -070056static constexpr char kClassLoaderSeparator = ';';
57static constexpr char kClasspathSeparator = ':';
58static constexpr char kDexFileChecksumSeparator = '*';
David Brazdil93d339d2019-03-27 09:56:45 +000059static constexpr char kInMemoryDexClassLoaderDexLocationMagic[] = "<unknown>";
Calin Juravle87e2cb62017-06-13 21:48:45 -070060
61ClassLoaderContext::ClassLoaderContext()
62 : special_shared_library_(false),
63 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070064 dex_files_open_result_(false),
Calin Juravle41acdc12017-07-18 17:45:32 -070065 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070066
67ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
68 : special_shared_library_(false),
69 dex_files_open_attempted_(true),
70 dex_files_open_result_(true),
71 owns_the_dex_files_(owns_the_dex_files) {}
72
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000073// Utility method to add parent and shared libraries of `info` into
74// the `work_list`.
75static void AddToWorkList(
76 ClassLoaderContext::ClassLoaderInfo* info,
77 std::vector<ClassLoaderContext::ClassLoaderInfo*>& work_list) {
78 if (info->parent != nullptr) {
79 work_list.push_back(info->parent.get());
80 }
81 for (size_t i = 0; i < info->shared_libraries.size(); ++i) {
82 work_list.push_back(info->shared_libraries[i].get());
83 }
84}
85
Calin Juravle57d0acc2017-07-11 17:41:30 -070086ClassLoaderContext::~ClassLoaderContext() {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000087 if (!owns_the_dex_files_ && class_loader_chain_ != nullptr) {
Calin Juravle57d0acc2017-07-11 17:41:30 -070088 // If the context does not own the dex/oat files release the unique pointers to
89 // make sure we do not de-allocate them.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000090 std::vector<ClassLoaderInfo*> work_list;
91 work_list.push_back(class_loader_chain_.get());
92 while (!work_list.empty()) {
93 ClassLoaderInfo* info = work_list.back();
94 work_list.pop_back();
95 for (std::unique_ptr<OatFile>& oat_file : info->opened_oat_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -070096 oat_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -070097 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000098 for (std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -070099 dex_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -0700100 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000101 AddToWorkList(info, work_list);
Calin Juravle57d0acc2017-07-11 17:41:30 -0700102 }
103 }
104}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700105
Calin Juravle19915892017-08-03 17:10:36 +0000106std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
107 return Create("");
108}
109
Calin Juravle87e2cb62017-06-13 21:48:45 -0700110std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
111 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
112 if (result->Parse(spec)) {
113 return result;
114 } else {
115 return nullptr;
116 }
117}
118
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000119static size_t FindMatchingSharedLibraryCloseMarker(const std::string& spec,
120 size_t shared_library_open_index) {
121 // Counter of opened shared library marker we've encountered so far.
122 uint32_t counter = 1;
123 // The index at which we're operating in the loop.
124 uint32_t string_index = shared_library_open_index + 1;
125 size_t shared_library_close = std::string::npos;
126 while (counter != 0) {
127 shared_library_close =
128 spec.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index);
129 size_t shared_library_open =
130 spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, string_index);
131 if (shared_library_close == std::string::npos) {
132 // No matching closing marker. Return an error.
133 break;
134 }
135
136 if ((shared_library_open == std::string::npos) ||
137 (shared_library_close < shared_library_open)) {
138 // We have seen a closing marker. Decrement the counter.
139 --counter;
140 // Move the search index forward.
141 string_index = shared_library_close + 1;
142 } else {
143 // New nested opening marker. Increment the counter and move the search
144 // index after the marker.
145 ++counter;
146 string_index = shared_library_open + 1;
147 }
148 }
149 return shared_library_close;
150}
151
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000152// The expected format is:
153// "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]{ClassLoaderType2[...]}".
Calin Juravle7b0648a2017-07-07 18:40:50 -0700154// The checksum part of the format is expected only if parse_cheksums is true.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000155std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseClassLoaderSpec(
156 const std::string& class_loader_spec,
157 bool parse_checksums) {
158 ClassLoaderType class_loader_type = ExtractClassLoaderType(class_loader_spec);
159 if (class_loader_type == kInvalidClassLoader) {
160 return nullptr;
161 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000162
163 // InMemoryDexClassLoader's dex location is always bogus. Special-case it.
164 if (class_loader_type == kInMemoryDexClassLoader) {
165 if (parse_checksums) {
166 // Make sure that OpenDexFiles() will never be attempted on this context
167 // because the dex locations of IMC do not correspond to real files.
168 CHECK(!dex_files_open_attempted_ || !dex_files_open_result_)
169 << "Parsing spec not supported when context created from a ClassLoader object";
170 dex_files_open_attempted_ = true;
171 dex_files_open_result_ = false;
172 } else {
173 // Checksums are not provided and dex locations themselves have no meaning
174 // (although we keep them in the spec to simplify parsing). Treat this as
175 // an unknown class loader.
David Brazdil93d339d2019-03-27 09:56:45 +0000176 // We can hit this case if dex2oat is invoked with a spec containing IMC.
177 // Because the dex file data is only available at runtime, we cannot proceed.
David Brazdil1a9ac532019-03-05 11:57:13 +0000178 return nullptr;
179 }
180 }
181
Calin Juravle87e2cb62017-06-13 21:48:45 -0700182 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
183 size_t type_str_size = strlen(class_loader_type_str);
184
185 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
186
187 // Check the opening and closing markers.
188 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000189 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700190 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000191 if ((class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) &&
192 (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderSharedLibraryClosingMark)) {
193 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700194 }
195
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000196 size_t closing_index = class_loader_spec.find_first_of(kClassLoaderClosingMark);
197
Calin Juravle87e2cb62017-06-13 21:48:45 -0700198 // At this point we know the format is ok; continue and extract the classpath.
199 // Note that class loaders with an empty class path are allowed.
200 std::string classpath = class_loader_spec.substr(type_str_size + 1,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000201 closing_index - type_str_size - 1);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700202
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000203 std::unique_ptr<ClassLoaderInfo> info(new ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700204
205 if (!parse_checksums) {
David Brazdil93d339d2019-03-27 09:56:45 +0000206 DCHECK(class_loader_type != kInMemoryDexClassLoader);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000207 Split(classpath, kClasspathSeparator, &info->classpath);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700208 } else {
209 std::vector<std::string> classpath_elements;
210 Split(classpath, kClasspathSeparator, &classpath_elements);
211 for (const std::string& element : classpath_elements) {
212 std::vector<std::string> dex_file_with_checksum;
213 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
214 if (dex_file_with_checksum.size() != 2) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000215 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700216 }
217 uint32_t checksum = 0;
Tom Cherry7bc8e8f2018-10-05 14:34:13 -0700218 if (!android::base::ParseUint(dex_file_with_checksum[1].c_str(), &checksum)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000219 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700220 }
David Brazdil93d339d2019-03-27 09:56:45 +0000221 if ((class_loader_type == kInMemoryDexClassLoader) &&
222 (dex_file_with_checksum[0] != kInMemoryDexClassLoaderDexLocationMagic)) {
223 return nullptr;
224 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000225
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000226 info->classpath.push_back(dex_file_with_checksum[0]);
227 info->checksums.push_back(checksum);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700228 }
229 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700230
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000231 if ((class_loader_spec[class_loader_spec.length() - 1] == kClassLoaderSharedLibraryClosingMark) &&
232 (class_loader_spec[class_loader_spec.length() - 2] != kClassLoaderSharedLibraryOpeningMark)) {
233 // Non-empty list of shared libraries.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000234 size_t start_index = class_loader_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark);
235 if (start_index == std::string::npos) {
236 return nullptr;
237 }
238 std::string shared_libraries_spec =
239 class_loader_spec.substr(start_index + 1, class_loader_spec.length() - start_index - 2);
240 std::vector<std::string> shared_libraries;
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000241 size_t cursor = 0;
242 while (cursor != shared_libraries_spec.length()) {
243 size_t shared_library_separator =
244 shared_libraries_spec.find_first_of(kClassLoaderSharedLibrarySeparator, cursor);
245 size_t shared_library_open =
246 shared_libraries_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, cursor);
247 std::string shared_library_spec;
248 if (shared_library_separator == std::string::npos) {
249 // Only one shared library, for example:
250 // PCL[...]
251 shared_library_spec =
252 shared_libraries_spec.substr(cursor, shared_libraries_spec.length() - cursor);
253 cursor = shared_libraries_spec.length();
254 } else if ((shared_library_open == std::string::npos) ||
255 (shared_library_open > shared_library_separator)) {
256 // We found a shared library without nested shared libraries, for example:
257 // PCL[...]#PCL[...]{...}
258 shared_library_spec =
259 shared_libraries_spec.substr(cursor, shared_library_separator - cursor);
260 cursor = shared_library_separator + 1;
261 } else {
262 // The shared library contains nested shared libraries. Find the matching closing shared
263 // marker for it.
264 size_t closing_marker =
265 FindMatchingSharedLibraryCloseMarker(shared_libraries_spec, shared_library_open);
266 if (closing_marker == std::string::npos) {
267 // No matching closing marker, return an error.
268 return nullptr;
269 }
270 shared_library_spec = shared_libraries_spec.substr(cursor, closing_marker + 1 - cursor);
271 cursor = closing_marker + 1;
272 if (cursor != shared_libraries_spec.length() &&
273 shared_libraries_spec[cursor] == kClassLoaderSharedLibrarySeparator) {
274 // Pass the shared library separator marker.
275 ++cursor;
276 }
277 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000278 std::unique_ptr<ClassLoaderInfo> shared_library(
279 ParseInternal(shared_library_spec, parse_checksums));
280 if (shared_library == nullptr) {
281 return nullptr;
282 }
283 info->shared_libraries.push_back(std::move(shared_library));
284 }
285 }
286
287 return info;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700288}
289
290// Extracts the class loader type from the given spec.
291// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
292// recognized.
293ClassLoaderContext::ClassLoaderType
294ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
David Brazdil1a9ac532019-03-05 11:57:13 +0000295 const ClassLoaderType kValidTypes[] = { kPathClassLoader,
296 kDelegateLastClassLoader,
297 kInMemoryDexClassLoader };
Calin Juravle87e2cb62017-06-13 21:48:45 -0700298 for (const ClassLoaderType& type : kValidTypes) {
299 const char* type_str = GetClassLoaderTypeName(type);
300 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
301 return type;
302 }
303 }
304 return kInvalidClassLoader;
305}
306
307// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
308// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
309// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700310bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700311 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700312 // By default we load the dex files in a PathClassLoader.
313 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
314 // tests)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000315 class_loader_chain_.reset(new ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700316 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700317 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700318
Calin Juravle87e2cb62017-06-13 21:48:45 -0700319 // Stop early if we detect the special shared library, which may be passed as the classpath
320 // for dex2oat when we want to skip the shared libraries check.
321 if (spec == OatFile::kSpecialSharedLibrary) {
322 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
323 special_shared_library_ = true;
324 return true;
325 }
326
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000327 CHECK(class_loader_chain_ == nullptr);
328 class_loader_chain_.reset(ParseInternal(spec, parse_checksums));
329 return class_loader_chain_ != nullptr;
330}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700331
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000332ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal(
333 const std::string& spec, bool parse_checksums) {
334 CHECK(!spec.empty());
335 CHECK_NE(spec, OatFile::kSpecialSharedLibrary);
336 std::string remaining = spec;
337 std::unique_ptr<ClassLoaderInfo> first(nullptr);
338 ClassLoaderInfo* previous_iteration = nullptr;
339 while (!remaining.empty()) {
340 std::string class_loader_spec;
341 size_t first_class_loader_separator = remaining.find_first_of(kClassLoaderSeparator);
342 size_t first_shared_library_open =
343 remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark);
344 if (first_class_loader_separator == std::string::npos) {
345 // Only one class loader, for example:
346 // PCL[...]
347 class_loader_spec = remaining;
348 remaining = "";
349 } else if ((first_shared_library_open == std::string::npos) ||
350 (first_shared_library_open > first_class_loader_separator)) {
351 // We found a class loader spec without shared libraries, for example:
352 // PCL[...];PCL[...]{...}
353 class_loader_spec = remaining.substr(0, first_class_loader_separator);
354 remaining = remaining.substr(first_class_loader_separator + 1,
355 remaining.size() - first_class_loader_separator - 1);
356 } else {
357 // The class loader spec contains shared libraries. Find the matching closing
358 // shared library marker for it.
359
Yi Kongd5fe17e2019-10-01 16:18:47 -0700360 size_t shared_library_close =
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000361 FindMatchingSharedLibraryCloseMarker(remaining, first_shared_library_open);
362 if (shared_library_close == std::string::npos) {
363 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
364 return nullptr;
365 }
366 class_loader_spec = remaining.substr(0, shared_library_close + 1);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000367
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000368 // Compute the remaining string to analyze.
369 if (remaining.size() == shared_library_close + 1) {
370 remaining = "";
371 } else if ((remaining.size() == shared_library_close + 2) ||
372 (remaining.at(shared_library_close + 1) != kClassLoaderSeparator)) {
373 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
374 return nullptr;
375 } else {
376 remaining = remaining.substr(shared_library_close + 2,
377 remaining.size() - shared_library_close - 2);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000378 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700379 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000380
381 std::unique_ptr<ClassLoaderInfo> info =
382 ParseClassLoaderSpec(class_loader_spec, parse_checksums);
383 if (info == nullptr) {
384 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
385 return nullptr;
386 }
387 if (first == nullptr) {
Andreas Gampe41c911f2018-11-19 11:34:16 -0800388 first = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000389 previous_iteration = first.get();
390 } else {
391 CHECK(previous_iteration != nullptr);
Andreas Gampe41c911f2018-11-19 11:34:16 -0800392 previous_iteration->parent = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000393 previous_iteration = previous_iteration->parent.get();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700394 }
395 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000396 return first.release();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700397}
398
399// Opens requested class path files and appends them to opened_dex_files. If the dex files have
400// been stripped, this opens them from their oat files (which get added to opened_oat_files).
David Brazdil89821862019-03-19 13:57:43 +0000401bool ClassLoaderContext::OpenDexFiles(InstructionSet isa,
402 const std::string& classpath_dir,
403 const std::vector<int>& fds) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700404 if (dex_files_open_attempted_) {
405 // Do not attempt to re-open the files if we already tried.
406 return dex_files_open_result_;
407 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700408
409 dex_files_open_attempted_ = true;
410 // Assume we can open all dex files. If not, we will set this to false as we go.
411 dex_files_open_result_ = true;
412
413 if (special_shared_library_) {
414 // Nothing to open if the context is a special shared library.
415 return true;
416 }
417
418 // Note that we try to open all dex files even if some fail.
419 // We may get resource-only apks which we cannot load.
420 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
421 // no dex files. So that we can distinguish the real failures...
David Sehr013fd802018-01-11 22:55:24 -0800422 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000423 std::vector<ClassLoaderInfo*> work_list;
Nicolas Geoffray9893c472018-11-13 15:39:53 +0000424 CHECK(class_loader_chain_ != nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000425 work_list.push_back(class_loader_chain_.get());
David Brazdil89821862019-03-19 13:57:43 +0000426 size_t dex_file_index = 0;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000427 while (!work_list.empty()) {
428 ClassLoaderInfo* info = work_list.back();
429 work_list.pop_back();
David Brazdil93d339d2019-03-27 09:56:45 +0000430 DCHECK(info->type != kInMemoryDexClassLoader) << __FUNCTION__ << " not supported for IMC";
431
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000432 size_t opened_dex_files_index = info->opened_dex_files.size();
433 for (const std::string& cp_elem : info->classpath) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700434 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000435 std::string location = cp_elem;
436 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000437 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700438 }
439
David Brazdil89821862019-03-19 13:57:43 +0000440 // If file descriptors were provided for the class loader context dex paths,
441 // get the descriptor which correponds to this dex path. We assume the `fds`
442 // vector follows the same order as a flattened class loader context.
443 int fd = -1;
444 if (!fds.empty()) {
445 if (dex_file_index >= fds.size()) {
446 LOG(WARNING) << "Number of FDs is smaller than number of dex files in the context";
447 dex_files_open_result_ = false;
448 return false;
449 }
450
451 fd = fds[dex_file_index++];
452 DCHECK_GE(fd, 0);
453 }
454
Calin Juravle87e2cb62017-06-13 21:48:45 -0700455 std::string error_msg;
456 // When opening the dex files from the context we expect their checksum to match their
457 // contents. So pass true to verify_checksum.
David Brazdil89821862019-03-19 13:57:43 +0000458 if (fd < 0) {
459 if (!dex_file_loader.Open(location.c_str(),
460 location.c_str(),
461 Runtime::Current()->IsVerificationEnabled(),
462 /*verify_checksum=*/ true,
463 &error_msg,
464 &info->opened_dex_files)) {
465 // If we fail to open the dex file because it's been stripped, try to
466 // open the dex file from its corresponding oat file.
467 // This could happen when we need to recompile a pre-build whose dex
468 // code has been stripped (for example, if the pre-build is only
469 // quicken and we want to re-compile it speed-profile).
470 // TODO(calin): Use the vdex directly instead of going through the oat file.
471 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
472 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
473 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
474 if (oat_file != nullptr &&
475 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
476 info->opened_oat_files.push_back(std::move(oat_file));
477 info->opened_dex_files.insert(info->opened_dex_files.end(),
478 std::make_move_iterator(oat_dex_files.begin()),
479 std::make_move_iterator(oat_dex_files.end()));
480 } else {
481 LOG(WARNING) << "Could not open dex files from location: " << location;
482 dex_files_open_result_ = false;
483 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700484 }
David Brazdil89821862019-03-19 13:57:43 +0000485 } else if (!dex_file_loader.Open(fd,
486 location.c_str(),
487 Runtime::Current()->IsVerificationEnabled(),
488 /*verify_checksum=*/ true,
489 &error_msg,
490 &info->opened_dex_files)) {
491 LOG(WARNING) << "Could not open dex files from fd " << fd << " for location: " << location;
492 dex_files_open_result_ = false;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700493 }
494 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700495
496 // We finished opening the dex files from the classpath.
497 // Now update the classpath and the checksum with the locations of the dex files.
498 //
499 // We do this because initially the classpath contains the paths of the dex files; and
500 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
501 // file paths with the actual dex locations being loaded.
502 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
503 // location in the class paths.
504 // Note that this will also remove the paths that could not be opened.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000505 info->original_classpath = std::move(info->classpath);
506 info->classpath.clear();
507 info->checksums.clear();
508 for (size_t k = opened_dex_files_index; k < info->opened_dex_files.size(); k++) {
509 std::unique_ptr<const DexFile>& dex = info->opened_dex_files[k];
510 info->classpath.push_back(dex->GetLocation());
511 info->checksums.push_back(dex->GetLocationChecksum());
Calin Juravlec5b215f2017-09-12 14:49:37 -0700512 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000513 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700514 }
515
David Brazdil89821862019-03-19 13:57:43 +0000516 // Check that if file descriptors were provided, there were exactly as many
517 // as we have encountered while iterating over this class loader context.
518 if (dex_file_index != fds.size()) {
519 LOG(WARNING) << fds.size() << " FDs provided but only " << dex_file_index
520 << " dex files are in the class loader context";
521 dex_files_open_result_ = false;
522 }
523
Calin Juravle87e2cb62017-06-13 21:48:45 -0700524 return dex_files_open_result_;
525}
526
527bool ClassLoaderContext::RemoveLocationsFromClassPaths(
528 const dchecked_vector<std::string>& locations) {
529 CHECK(!dex_files_open_attempted_)
530 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
531
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000532 if (class_loader_chain_ == nullptr) {
533 return false;
534 }
535
Calin Juravle87e2cb62017-06-13 21:48:45 -0700536 std::set<std::string> canonical_locations;
537 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700538 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700539 }
540 bool removed_locations = false;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000541 std::vector<ClassLoaderInfo*> work_list;
542 work_list.push_back(class_loader_chain_.get());
543 while (!work_list.empty()) {
544 ClassLoaderInfo* info = work_list.back();
545 work_list.pop_back();
546 size_t initial_size = info->classpath.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700547 auto kept_it = std::remove_if(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000548 info->classpath.begin(),
549 info->classpath.end(),
Calin Juravle87e2cb62017-06-13 21:48:45 -0700550 [canonical_locations](const std::string& location) {
551 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700552 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700553 });
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000554 info->classpath.erase(kept_it, info->classpath.end());
555 if (initial_size != info->classpath.size()) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700556 removed_locations = true;
557 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000558 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700559 }
560 return removed_locations;
561}
562
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700563std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700564 return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700565}
566
Mathieu Chartierc4440772018-04-16 14:40:56 -0700567std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
568 ClassLoaderContext* stored_context) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700569 return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700570}
571
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800572std::map<std::string, std::string>
573ClassLoaderContext::EncodeClassPathContexts(const std::string& base_dir) const {
574 CheckDexFilesOpened("EncodeClassPathContexts");
575 if (class_loader_chain_ == nullptr) {
576 return std::map<std::string, std::string>{};
577 }
578
579 std::map<std::string, std::string> results;
580 std::vector<std::string> dex_locations;
581 std::vector<uint32_t> checksums;
582 dex_locations.reserve(class_loader_chain_->original_classpath.size());
583
584 std::ostringstream encoded_libs_and_parent_stream;
585 EncodeSharedLibAndParent(*class_loader_chain_,
586 base_dir,
587 /*for_dex2oat=*/true,
588 /*stored_info=*/nullptr,
589 encoded_libs_and_parent_stream);
590 std::string encoded_libs_and_parent(encoded_libs_and_parent_stream.str());
591
592 std::set<std::string> seen_locations;
593 for (const std::string& path : class_loader_chain_->classpath) {
594 // The classpath will contain multiple entries for multidex files, so make sure this is the
595 // first time we're seeing this file.
596 const std::string base_location(DexFileLoader::GetBaseLocation(path));
597 if (!seen_locations.insert(base_location).second) {
598 continue;
599 }
600
601 std::ostringstream out;
602 EncodeClassPath(base_dir, dex_locations, checksums, class_loader_chain_->type, out);
603 out << encoded_libs_and_parent;
604 results.emplace(base_location, out.str());
605
606 dex_locations.push_back(base_location);
607 }
608
609 return results;
610}
611
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700612std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700613 bool for_dex2oat,
614 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700615 CheckDexFilesOpened("EncodeContextForOatFile");
616 if (special_shared_library_) {
617 return OatFile::kSpecialSharedLibrary;
618 }
619
Mathieu Chartierc4440772018-04-16 14:40:56 -0700620 if (stored_context != nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000621 DCHECK_EQ(GetParentChainSize(), stored_context->GetParentChainSize());
Mathieu Chartierc4440772018-04-16 14:40:56 -0700622 }
623
Calin Juravle7b0648a2017-07-07 18:40:50 -0700624 std::ostringstream out;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000625 if (class_loader_chain_ == nullptr) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700626 // We can get in this situation if the context was created with a class path containing the
627 // source dex files which were later removed (happens during run-tests).
628 out << GetClassLoaderTypeName(kPathClassLoader)
629 << kClassLoaderOpeningMark
630 << kClassLoaderClosingMark;
631 return out.str();
632 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700633
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000634 EncodeContextInternal(
635 *class_loader_chain_,
636 base_dir,
637 for_dex2oat,
638 (stored_context == nullptr ? nullptr : stored_context->class_loader_chain_.get()),
639 out);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700640 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700641}
642
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800643void ClassLoaderContext::EncodeClassPath(const std::string& base_dir,
644 const std::vector<std::string>& dex_locations,
645 const std::vector<uint32_t>& checksums,
646 ClassLoaderType type,
647 std::ostringstream& out) const {
648 CHECK(checksums.empty() || dex_locations.size() == checksums.size());
649 out << GetClassLoaderTypeName(type);
650 out << kClassLoaderOpeningMark;
651 const size_t len = dex_locations.size();
652 for (size_t k = 0; k < len; k++) {
653 std::string location = dex_locations[k];
654 if (k > 0) {
655 out << kClasspathSeparator;
656 }
657 if (type == kInMemoryDexClassLoader) {
658 out << kInMemoryDexClassLoaderDexLocationMagic;
659 } else if (!base_dir.empty()
660 && location.substr(0, base_dir.length()) == base_dir) {
661 // Find paths that were relative and convert them back from absolute.
662 out << location.substr(base_dir.length() + 1).c_str();
663 } else {
664 out << location.c_str();
665 }
666 if (!checksums.empty()) {
667 out << kDexFileChecksumSeparator;
668 out << checksums[k];
669 }
670 }
671 out << kClassLoaderClosingMark;
672}
673
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000674void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info,
675 const std::string& base_dir,
676 bool for_dex2oat,
677 ClassLoaderInfo* stored_info,
678 std::ostringstream& out) const {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800679 std::vector<std::string> locations;
680 std::vector<uint32_t> checksums;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000681 std::set<std::string> seen_locations;
682 SafeMap<std::string, std::string> remap;
683 if (stored_info != nullptr) {
684 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
685 // Note that we don't care if the same name appears twice.
686 remap.Put(info.original_classpath[k], stored_info->classpath[k]);
687 }
688 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800689
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000690 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
691 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
692 if (for_dex2oat) {
693 // dex2oat only needs the base location. It cannot accept multidex locations.
694 // So ensure we only add each file once.
695 bool new_insert = seen_locations.insert(
696 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
697 if (!new_insert) {
698 continue;
699 }
700 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800701
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000702 std::string location = dex_file->GetLocation();
703 // If there is a stored class loader remap, fix up the multidex strings.
704 if (!remap.empty()) {
705 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
706 auto it = remap.find(base_dex_location);
707 CHECK(it != remap.end()) << base_dex_location;
708 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
709 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800710 locations.emplace_back(std::move(location));
711
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000712 // dex2oat does not need the checksums.
713 if (!for_dex2oat) {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800714 checksums.push_back(dex_file->GetLocationChecksum());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000715 }
716 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800717 EncodeClassPath(base_dir, locations, checksums, info.type, out);
718 EncodeSharedLibAndParent(info, base_dir, for_dex2oat, stored_info, out);
719}
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000720
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800721void ClassLoaderContext::EncodeSharedLibAndParent(const ClassLoaderInfo& info,
722 const std::string& base_dir,
723 bool for_dex2oat,
724 ClassLoaderInfo* stored_info,
725 std::ostringstream& out) const {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000726 if (!info.shared_libraries.empty()) {
727 out << kClassLoaderSharedLibraryOpeningMark;
728 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
729 if (i > 0) {
730 out << kClassLoaderSharedLibrarySeparator;
731 }
732 EncodeContextInternal(
733 *info.shared_libraries[i].get(),
734 base_dir,
735 for_dex2oat,
736 (stored_info == nullptr ? nullptr : stored_info->shared_libraries[i].get()),
737 out);
738 }
739 out << kClassLoaderSharedLibraryClosingMark;
740 }
741 if (info.parent != nullptr) {
742 out << kClassLoaderSeparator;
743 EncodeContextInternal(
744 *info.parent.get(),
745 base_dir,
746 for_dex2oat,
747 (stored_info == nullptr ? nullptr : stored_info->parent.get()),
748 out);
749 }
750}
751
752// Returns the WellKnownClass for the given class loader type.
753static jclass GetClassLoaderClass(ClassLoaderContext::ClassLoaderType type) {
754 switch (type) {
755 case ClassLoaderContext::kPathClassLoader:
756 return WellKnownClasses::dalvik_system_PathClassLoader;
757 case ClassLoaderContext::kDelegateLastClassLoader:
758 return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +0000759 case ClassLoaderContext::kInMemoryDexClassLoader:
760 return WellKnownClasses::dalvik_system_InMemoryDexClassLoader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000761 case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch.
762 }
763 LOG(FATAL) << "Invalid class loader type " << type;
764 UNREACHABLE();
765}
766
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000767static std::string FlattenClasspath(const std::vector<std::string>& classpath) {
768 return android::base::Join(classpath, ':');
769}
770
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000771static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal(
772 Thread* self,
773 ScopedObjectAccess& soa,
774 const ClassLoaderContext::ClassLoaderInfo& info,
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000775 bool for_shared_library,
776 VariableSizedHandleScope& map_scope,
777 std::map<std::string, Handle<mirror::ClassLoader>>& canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000778 bool add_compilation_sources,
779 const std::vector<const DexFile*>& compilation_sources)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000780 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000781 if (for_shared_library) {
782 // Check if the shared library has already been created.
783 auto search = canonicalized_libraries.find(FlattenClasspath(info.classpath));
784 if (search != canonicalized_libraries.end()) {
785 return search->second.Get();
786 }
787 }
788
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000789 StackHandleScope<3> hs(self);
790 MutableHandle<mirror::ObjectArray<mirror::ClassLoader>> libraries(
791 hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr));
792
793 if (!info.shared_libraries.empty()) {
794 libraries.Assign(mirror::ObjectArray<mirror::ClassLoader>::Alloc(
795 self,
796 GetClassRoot<mirror::ObjectArray<mirror::ClassLoader>>(),
797 info.shared_libraries.size()));
798 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
799 // We should only add the compilation sources to the first class loader.
800 libraries->Set(i,
801 CreateClassLoaderInternal(
802 self,
803 soa,
804 *info.shared_libraries[i].get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000805 /* for_shared_library= */ true,
806 map_scope,
807 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000808 /* add_compilation_sources= */ false,
809 compilation_sources));
810 }
811 }
812
813 MutableHandle<mirror::ClassLoader> parent = hs.NewHandle<mirror::ClassLoader>(nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000814 if (info.parent != nullptr) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000815 // We should only add the compilation sources to the first class loader.
816 parent.Assign(CreateClassLoaderInternal(
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000817 self,
818 soa,
819 *info.parent.get(),
820 /* for_shared_library= */ false,
821 map_scope,
822 canonicalized_libraries,
823 /* add_compilation_sources= */ false,
824 compilation_sources));
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000825 }
826 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
827 info.opened_dex_files);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000828 if (add_compilation_sources) {
829 // For the first class loader, its classpath comes first, followed by compilation sources.
830 // This ensures that whenever we need to resolve classes from it the classpath elements
831 // come first.
832 class_path_files.insert(class_path_files.end(),
833 compilation_sources.begin(),
834 compilation_sources.end());
835 }
836 Handle<mirror::Class> loader_class = hs.NewHandle<mirror::Class>(
837 soa.Decode<mirror::Class>(GetClassLoaderClass(info.type)));
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000838 ObjPtr<mirror::ClassLoader> loader =
839 Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
840 self,
841 class_path_files,
842 loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +0000843 parent,
844 libraries);
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000845 if (for_shared_library) {
846 canonicalized_libraries[FlattenClasspath(info.classpath)] =
847 map_scope.NewHandle<mirror::ClassLoader>(loader);
848 }
849 return loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000850}
851
Calin Juravle87e2cb62017-06-13 21:48:45 -0700852jobject ClassLoaderContext::CreateClassLoader(
853 const std::vector<const DexFile*>& compilation_sources) const {
854 CheckDexFilesOpened("CreateClassLoader");
855
856 Thread* self = Thread::Current();
857 ScopedObjectAccess soa(self);
858
Calin Juravlec79470d2017-07-12 17:37:42 -0700859 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700860
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000861 if (class_loader_chain_ == nullptr) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000862 CHECK(special_shared_library_);
Calin Juravlec79470d2017-07-12 17:37:42 -0700863 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700864 }
865
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000866 // Create a map of canonicalized shared libraries. As we're holding objects,
867 // we're creating a variable size handle scope to put handles in the map.
868 VariableSizedHandleScope map_scope(self);
869 std::map<std::string, Handle<mirror::ClassLoader>> canonicalized_libraries;
870
871 // Create the class loader.
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000872 ObjPtr<mirror::ClassLoader> loader =
873 CreateClassLoaderInternal(self,
874 soa,
875 *class_loader_chain_.get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000876 /* for_shared_library= */ false,
877 map_scope,
878 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000879 /* add_compilation_sources= */ true,
880 compilation_sources);
881 // Make it a global ref and return.
882 ScopedLocalRef<jobject> local_ref(
883 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
884 return soa.Env()->NewGlobalRef(local_ref.get());
Calin Juravle87e2cb62017-06-13 21:48:45 -0700885}
886
887std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
888 CheckDexFilesOpened("FlattenOpenedDexFiles");
889
890 std::vector<const DexFile*> result;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000891 if (class_loader_chain_ == nullptr) {
892 return result;
893 }
894 std::vector<ClassLoaderInfo*> work_list;
895 work_list.push_back(class_loader_chain_.get());
896 while (!work_list.empty()) {
897 ClassLoaderInfo* info = work_list.back();
898 work_list.pop_back();
899 for (const std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700900 result.push_back(dex_file.get());
901 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000902 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700903 }
904 return result;
905}
906
David Brazdil89821862019-03-19 13:57:43 +0000907std::string ClassLoaderContext::FlattenDexPaths() const {
908 if (class_loader_chain_ == nullptr) {
909 return "";
910 }
911
912 std::vector<std::string> result;
913 std::vector<ClassLoaderInfo*> work_list;
914 work_list.push_back(class_loader_chain_.get());
915 while (!work_list.empty()) {
916 ClassLoaderInfo* info = work_list.back();
917 work_list.pop_back();
918 for (const std::string& dex_path : info->classpath) {
919 result.push_back(dex_path);
920 }
921 AddToWorkList(info, work_list);
922 }
923 return FlattenClasspath(result);
924}
925
Calin Juravle87e2cb62017-06-13 21:48:45 -0700926const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
927 switch (type) {
928 case kPathClassLoader: return kPathClassLoaderString;
929 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
David Brazdil1a9ac532019-03-05 11:57:13 +0000930 case kInMemoryDexClassLoader: return kInMemoryDexClassLoaderString;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700931 default:
932 LOG(FATAL) << "Invalid class loader type " << type;
933 UNREACHABLE();
934 }
935}
936
937void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
938 CHECK(dex_files_open_attempted_)
939 << "Dex files were not successfully opened before the call to " << calling_method
940 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
941}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700942
Calin Juravle57d0acc2017-07-11 17:41:30 -0700943// Collects the dex files from the give Java dex_file object. Only the dex files with
944// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
945static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
946 ArtField* const cookie_field,
947 std::vector<const DexFile*>* out_dex_files)
948 REQUIRES_SHARED(Locks::mutator_lock_) {
949 if (java_dex_file == nullptr) {
950 return true;
951 }
952 // On the Java side, the dex files are stored in the cookie field.
Vladimir Marko4617d582019-03-28 13:48:31 +0000953 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
Calin Juravle57d0acc2017-07-11 17:41:30 -0700954 if (long_array == nullptr) {
955 // This should never happen so log a warning.
956 LOG(ERROR) << "Unexpected null cookie";
957 return false;
958 }
959 int32_t long_array_size = long_array->GetLength();
960 // Index 0 from the long array stores the oat file. The dex files start at index 1.
961 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +0100962 const DexFile* cp_dex_file =
963 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700964 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
965 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
966 // cp_dex_file can be null.
967 out_dex_files->push_back(cp_dex_file);
968 }
969 }
970 return true;
971}
972
973// Collects all the dex files loaded by the given class loader.
974// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
975// a null list of dex elements or a null dex element).
976static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
977 Handle<mirror::ClassLoader> class_loader,
978 std::vector<const DexFile*>* out_dex_files)
979 REQUIRES_SHARED(Locks::mutator_lock_) {
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800980 CHECK(IsInstanceOfBaseDexClassLoader(soa, class_loader));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700981
982 // All supported class loaders inherit from BaseDexClassLoader.
983 // We need to get the DexPathList and loop through it.
984 ArtField* const cookie_field =
985 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
986 ArtField* const dex_file_field =
987 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
988 ObjPtr<mirror::Object> dex_path_list =
989 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
990 GetObject(class_loader.Get());
991 CHECK(cookie_field != nullptr);
992 CHECK(dex_file_field != nullptr);
993 if (dex_path_list == nullptr) {
994 // This may be null if the current class loader is under construction and it does not
995 // have its fields setup yet.
996 return true;
997 }
998 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
999 ObjPtr<mirror::Object> dex_elements_obj =
1000 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1001 GetObject(dex_path_list);
1002 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1003 // at the mCookie which is a DexFile vector.
1004 if (dex_elements_obj == nullptr) {
1005 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
1006 // and assume we have no elements.
1007 return true;
1008 } else {
1009 StackHandleScope<1> hs(soa.Self());
1010 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
1011 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
Alex Lighta9bbc082019-11-14 14:51:41 -08001012 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001013 if (element == nullptr) {
1014 // Should never happen, log an error and break.
1015 // TODO(calin): It's unclear if we should just assert here.
1016 // This code was propagated to oat_file_manager from the class linker where it would
1017 // throw a NPE. For now, return false which will mark this class loader as unsupported.
1018 LOG(ERROR) << "Unexpected null in the dex element list";
1019 return false;
1020 }
1021 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
1022 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1023 return false;
1024 }
1025 }
1026 }
1027
1028 return true;
1029}
1030
1031static bool GetDexFilesFromDexElementsArray(
1032 ScopedObjectAccessAlreadyRunnable& soa,
1033 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1034 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
1035 DCHECK(dex_elements != nullptr);
1036
1037 ArtField* const cookie_field =
1038 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
1039 ArtField* const dex_file_field =
1040 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Vladimir Marko0984e482019-03-27 16:41:41 +00001041 const ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001042 WellKnownClasses::dalvik_system_DexPathList__Element);
Vladimir Marko0984e482019-03-27 16:41:41 +00001043 const ObjPtr<mirror::Class> dexfile_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001044 WellKnownClasses::dalvik_system_DexFile);
1045
Alex Lighta9bbc082019-11-14 14:51:41 -08001046 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001047 // We can hit a null element here because this is invoked with a partially filled dex_elements
1048 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
1049 // list of dex files which were opened before.
1050 if (element == nullptr) {
1051 continue;
1052 }
1053
1054 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
1055 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
1056 // a historical glitch. All the java code opens dex files using an array of Elements.
1057 ObjPtr<mirror::Object> dex_file;
1058 if (element_class == element->GetClass()) {
1059 dex_file = dex_file_field->GetObject(element);
1060 } else if (dexfile_class == element->GetClass()) {
1061 dex_file = element;
1062 } else {
1063 LOG(ERROR) << "Unsupported element in dex_elements: "
1064 << mirror::Class::PrettyClass(element->GetClass());
1065 return false;
1066 }
1067
1068 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1069 return false;
1070 }
1071 }
1072 return true;
1073}
1074
1075// Adds the `class_loader` info to the `context`.
1076// The dex file present in `dex_elements` array (if not null) will be added at the end of
1077// the classpath.
1078// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
1079// BootClassLoader. Note that the class loader chain is expected to be short.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001080bool ClassLoaderContext::CreateInfoFromClassLoader(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001081 ScopedObjectAccessAlreadyRunnable& soa,
1082 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001083 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1084 ClassLoaderInfo* child_info,
1085 bool is_shared_library)
Calin Juravle57d0acc2017-07-11 17:41:30 -07001086 REQUIRES_SHARED(Locks::mutator_lock_) {
1087 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
1088 // Nothing to do for the boot class loader as we don't add its dex files to the context.
1089 return true;
1090 }
1091
1092 ClassLoaderContext::ClassLoaderType type;
1093 if (IsPathOrDexClassLoader(soa, class_loader)) {
1094 type = kPathClassLoader;
1095 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
1096 type = kDelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +00001097 } else if (IsInMemoryDexClassLoader(soa, class_loader)) {
1098 type = kInMemoryDexClassLoader;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001099 } else {
1100 LOG(WARNING) << "Unsupported class loader";
1101 return false;
1102 }
1103
1104 // Inspect the class loader for its dex files.
1105 std::vector<const DexFile*> dex_files_loaded;
1106 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
1107
1108 // If we have a dex_elements array extract its dex elements now.
1109 // This is used in two situations:
1110 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
1111 // passing the list of already open dex files each time. This ensures that we see the
1112 // correct context even if the ClassLoader under construction is not fully build.
1113 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
1114 // appending them to the current class loader. When the new code paths are loaded in
1115 // BaseDexClassLoader, the paths already present in the class loader will be passed
1116 // in the dex_elements array.
1117 if (dex_elements != nullptr) {
1118 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
1119 }
1120
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001121 ClassLoaderInfo* info = new ClassLoaderContext::ClassLoaderInfo(type);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001122 // Attach the `ClassLoaderInfo` now, before populating dex files, as only the
1123 // `ClassLoaderContext` knows whether these dex files should be deleted or not.
1124 if (child_info == nullptr) {
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001125 class_loader_chain_.reset(info);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001126 } else if (is_shared_library) {
1127 child_info->shared_libraries.push_back(std::unique_ptr<ClassLoaderInfo>(info));
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001128 } else {
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001129 child_info->parent.reset(info);
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001130 }
1131
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001132 // Now that `info` is in the chain, populate dex files.
Calin Juravle57d0acc2017-07-11 17:41:30 -07001133 for (const DexFile* dex_file : dex_files_loaded) {
David Brazdil93d339d2019-03-27 09:56:45 +00001134 // Dex location of dex files loaded with InMemoryDexClassLoader is always bogus.
1135 // Use a magic value for the classpath instead.
1136 info->classpath.push_back((type == kInMemoryDexClassLoader)
1137 ? kInMemoryDexClassLoaderDexLocationMagic
1138 : dex_file->GetLocation());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001139 info->checksums.push_back(dex_file->GetLocationChecksum());
1140 info->opened_dex_files.emplace_back(dex_file);
Calin Juravle57d0acc2017-07-11 17:41:30 -07001141 }
1142
Calin Juravle57d0acc2017-07-11 17:41:30 -07001143 // Note that dex_elements array is null here. The elements are considered to be part of the
1144 // current class loader and are not passed to the parents.
1145 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001146
1147 // Add the shared libraries.
1148 StackHandleScope<3> hs(Thread::Current());
1149 ArtField* field =
1150 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1151 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
1152 if (raw_shared_libraries != nullptr) {
1153 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries =
1154 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>());
1155 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08001156 for (auto library : shared_libraries.Iterate<mirror::ClassLoader>()) {
1157 temp_loader.Assign(library);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001158 if (!CreateInfoFromClassLoader(
1159 soa, temp_loader, null_dex_elements, info, /*is_shared_library=*/ true)) {
1160 return false;
1161 }
1162 }
1163 }
1164
1165 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
1166 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
1167 if (!CreateInfoFromClassLoader(
1168 soa, parent, null_dex_elements, info, /*is_shared_library=*/ false)) {
1169 return false;
1170 }
1171 return true;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001172}
1173
1174std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
1175 jobject class_loader,
1176 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -07001177 CHECK(class_loader != nullptr);
1178
Calin Juravle57d0acc2017-07-11 17:41:30 -07001179 ScopedObjectAccess soa(Thread::Current());
1180 StackHandleScope<2> hs(soa.Self());
1181 Handle<mirror::ClassLoader> h_class_loader =
1182 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1183 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
1184 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001185 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/ false));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001186 if (!result->CreateInfoFromClassLoader(
1187 soa, h_class_loader, h_dex_elements, nullptr, /*is_shared_library=*/ false)) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001188 return nullptr;
1189 }
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001190 return result;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001191}
1192
Dan Zimmermanb682ea42019-12-23 06:59:06 -08001193std::map<std::string, std::string>
1194ClassLoaderContext::EncodeClassPathContextsForClassLoader(jobject class_loader) {
1195 std::unique_ptr<ClassLoaderContext> clc =
1196 ClassLoaderContext::CreateContextForClassLoader(class_loader, nullptr);
1197 if (clc != nullptr) {
1198 return clc->EncodeClassPathContexts("");
1199 }
1200
1201 ScopedObjectAccess soa(Thread::Current());
1202 StackHandleScope<1> hs(soa.Self());
1203 Handle<mirror::ClassLoader> h_class_loader =
1204 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1205 if (!IsInstanceOfBaseDexClassLoader(soa, h_class_loader)) {
1206 return std::map<std::string, std::string>{};
1207 }
1208
1209 std::vector<const DexFile*> dex_files_loaded;
1210 CollectDexFilesFromSupportedClassLoader(soa, h_class_loader, &dex_files_loaded);
1211
1212 std::map<std::string, std::string> results;
1213 for (const DexFile* dex_file : dex_files_loaded) {
1214 results.emplace(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1215 ClassLoaderContext::kUnsupportedClassLoaderContextEncoding);
1216 }
1217 return results;
1218}
1219
Dan Zimmermanc9fa7702020-01-31 13:35:12 -08001220bool ClassLoaderContext::IsValidEncoding(const std::string& possible_encoded_class_loader_context) {
1221 return ClassLoaderContext::Create(possible_encoded_class_loader_context.c_str()) != nullptr
1222 || possible_encoded_class_loader_context == kUnsupportedClassLoaderContextEncoding;
1223}
1224
Mathieu Chartieradc90862018-05-11 13:03:06 -07001225ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
1226 const std::string& context_spec,
1227 bool verify_names,
1228 bool verify_checksums) const {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001229 if (verify_names || verify_checksums) {
1230 DCHECK(dex_files_open_attempted_);
1231 DCHECK(dex_files_open_result_);
1232 }
Calin Juravlec5b215f2017-09-12 14:49:37 -07001233
Calin Juravle3f918642017-07-11 19:04:20 -07001234 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001235 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -07001236 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -07001237 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001238 }
1239
Calin Juravlec5b215f2017-09-12 14:49:37 -07001240 // Special shared library contexts always match. They essentially instruct the runtime
1241 // to ignore the class path check because the oat file is known to be loaded in different
1242 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
1243 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -07001244 if (expected_context.special_shared_library_) {
1245 // Special case where we are the only entry in the class path.
Nicolas Geoffray9893c472018-11-13 15:39:53 +00001246 if (class_loader_chain_ != nullptr &&
1247 class_loader_chain_->parent == nullptr &&
1248 class_loader_chain_->classpath.size() == 0) {
Mathieu Chartieradc90862018-05-11 13:03:06 -07001249 return VerificationResult::kVerifies;
1250 }
1251 return VerificationResult::kForcedToSkipChecks;
1252 } else if (special_shared_library_) {
1253 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -07001254 }
1255
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001256 ClassLoaderInfo* info = class_loader_chain_.get();
1257 ClassLoaderInfo* expected = expected_context.class_loader_chain_.get();
1258 CHECK(info != nullptr);
1259 CHECK(expected != nullptr);
1260 if (!ClassLoaderInfoMatch(*info, *expected, context_spec, verify_names, verify_checksums)) {
Mathieu Chartieradc90862018-05-11 13:03:06 -07001261 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001262 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001263 return VerificationResult::kVerifies;
1264}
Calin Juravle3f918642017-07-11 19:04:20 -07001265
Vladimir Marko36ec5982019-11-28 10:55:16 +00001266// Returns true if absolute `path` ends with relative `suffix` starting at
1267// a directory name boundary, i.e. after a '/'. For example, "foo/bar"
1268// is a valid suffix of "/data/foo/bar" but not "/data-foo/bar".
1269static inline bool AbsolutePathHasRelativeSuffix(const std::string& path,
1270 const std::string& suffix) {
1271 DCHECK(IsAbsoluteLocation(path));
1272 DCHECK(!IsAbsoluteLocation(suffix));
1273 return (path.size() > suffix.size()) &&
1274 (path[path.size() - suffix.size() - 1u] == '/') &&
1275 (std::string_view(path).substr(/*pos*/ path.size() - suffix.size()) == suffix);
1276}
1277
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001278bool ClassLoaderContext::ClassLoaderInfoMatch(
1279 const ClassLoaderInfo& info,
1280 const ClassLoaderInfo& expected_info,
1281 const std::string& context_spec,
1282 bool verify_names,
1283 bool verify_checksums) const {
1284 if (info.type != expected_info.type) {
1285 LOG(WARNING) << "ClassLoaderContext type mismatch"
1286 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
1287 << ", found=" << GetClassLoaderTypeName(info.type)
1288 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1289 return false;
1290 }
1291 if (info.classpath.size() != expected_info.classpath.size()) {
1292 LOG(WARNING) << "ClassLoaderContext classpath size mismatch"
1293 << ". expected=" << expected_info.classpath.size()
1294 << ", found=" << info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001295 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001296 return false;
1297 }
Calin Juravle3f918642017-07-11 19:04:20 -07001298
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001299 if (verify_checksums) {
1300 DCHECK_EQ(info.classpath.size(), info.checksums.size());
1301 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
1302 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001303
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001304 if (verify_names) {
Calin Juravle3f918642017-07-11 19:04:20 -07001305 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001306 // Compute the dex location that must be compared.
1307 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
1308 // because even if they refer to the same file, one could be encoded as a relative location
1309 // and the other as an absolute one.
1310 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
1311 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
Vladimir Marko36ec5982019-11-28 10:55:16 +00001312 bool dex_names_match = false;
1313
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001314
1315 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
1316 // If both locations are absolute or relative then compare them as they are.
1317 // This is usually the case for: shared libraries and secondary dex files.
Vladimir Marko36ec5982019-11-28 10:55:16 +00001318 dex_names_match = (info.classpath[k] == expected_info.classpath[k]);
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001319 } else if (is_dex_name_absolute) {
1320 // The runtime name is absolute but the compiled name (the expected one) is relative.
1321 // This is the case for split apks which depend on base or on other splits.
Vladimir Marko36ec5982019-11-28 10:55:16 +00001322 dex_names_match =
1323 AbsolutePathHasRelativeSuffix(info.classpath[k], expected_info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +00001324 } else if (is_expected_dex_name_absolute) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001325 // The runtime name is relative but the compiled name is absolute.
1326 // There is no expected use case that would end up here as dex files are always loaded
1327 // with their absolute location. However, be tolerant and do the best effort (in case
1328 // there are unexpected new use case...).
Vladimir Marko36ec5982019-11-28 10:55:16 +00001329 dex_names_match =
1330 AbsolutePathHasRelativeSuffix(expected_info.classpath[k], info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +00001331 } else {
1332 // Both locations are relative. In this case there's not much we can be sure about
1333 // except that the names are the same. The checksum will ensure that the files are
1334 // are same. This should not happen outside testing and manual invocations.
Vladimir Marko36ec5982019-11-28 10:55:16 +00001335 dex_names_match = (info.classpath[k] == expected_info.classpath[k]);
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001336 }
1337
1338 // Compare the locations.
Vladimir Marko36ec5982019-11-28 10:55:16 +00001339 if (!dex_names_match) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001340 LOG(WARNING) << "ClassLoaderContext classpath element mismatch"
Calin Juravle3f918642017-07-11 19:04:20 -07001341 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001342 << ", found=" << info.classpath[k]
1343 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001344 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001345 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001346
1347 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -07001348 if (info.checksums[k] != expected_info.checksums[k]) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001349 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch"
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001350 << ". expected=" << expected_info.checksums[k]
1351 << ", found=" << info.checksums[k]
1352 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001353 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001354 }
1355 }
1356 }
Calin Juravle3f918642017-07-11 19:04:20 -07001357
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001358 if (info.shared_libraries.size() != expected_info.shared_libraries.size()) {
1359 LOG(WARNING) << "ClassLoaderContext shared library size mismatch. "
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001360 << "Expected=" << expected_info.shared_libraries.size()
1361 << ", found=" << info.shared_libraries.size()
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001362 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1363 return false;
Calin Juravlec79470d2017-07-12 17:37:42 -07001364 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001365 for (size_t i = 0; i < info.shared_libraries.size(); ++i) {
1366 if (!ClassLoaderInfoMatch(*info.shared_libraries[i].get(),
1367 *expected_info.shared_libraries[i].get(),
1368 context_spec,
1369 verify_names,
1370 verify_checksums)) {
1371 return false;
1372 }
1373 }
1374 if (info.parent.get() == nullptr) {
1375 if (expected_info.parent.get() != nullptr) {
1376 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1377 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1378 return false;
1379 }
1380 return true;
1381 } else if (expected_info.parent.get() == nullptr) {
1382 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1383 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1384 return false;
1385 } else {
1386 return ClassLoaderInfoMatch(*info.parent.get(),
1387 *expected_info.parent.get(),
1388 context_spec,
1389 verify_names,
1390 verify_checksums);
1391 }
Calin Juravlec79470d2017-07-12 17:37:42 -07001392}
1393
Calin Juravle87e2cb62017-06-13 21:48:45 -07001394} // namespace art