blob: 74f464c0bd73fba48f2c90270a95a64a29e5ad63 [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
Calin Juravlea63a2e92020-04-15 20:02:00 -070019#include <algorithm>
20
Andreas Gampef9411702018-09-06 17:16:57 -070021#include <android-base/parseint.h>
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +000022#include <android-base/strings.h>
Andreas Gampef9411702018-09-06 17:16:57 -070023
Calin Juravle57d0acc2017-07-11 17:41:30 -070024#include "art_field-inl.h"
Vladimir Marko78baed52018-10-11 10:44:58 +010025#include "base/casts.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070026#include "base/dchecked_vector.h"
Andreas Gampe19f54162019-05-14 16:16:28 -070027#include "base/file_utils.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070028#include "base/stl_util.h"
29#include "class_linker.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070030#include "class_loader_utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010031#include "class_root-inl.h"
David Sehr013fd802018-01-11 22:55:24 -080032#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080033#include "dex/dex_file.h"
34#include "dex/dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070035#include "handle_scope-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010036#include "jni/jni_internal.h"
Vladimir Markobdc93b42019-03-29 16:12:04 +000037#include "mirror/class_loader-inl.h"
Alex Lighta9bbc082019-11-14 14:51:41 -080038#include "mirror/object.h"
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000039#include "mirror/object_array-alloc-inl.h"
40#include "nativehelper/scoped_local_ref.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070041#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070042#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070043#include "runtime.h"
44#include "scoped_thread_state_change-inl.h"
45#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070046#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070047
48namespace art {
49
50static constexpr char kPathClassLoaderString[] = "PCL";
51static constexpr char kDelegateLastClassLoaderString[] = "DLC";
David Brazdil1a9ac532019-03-05 11:57:13 +000052static constexpr char kInMemoryDexClassLoaderString[] = "IMC";
Calin Juravle87e2cb62017-06-13 21:48:45 -070053static constexpr char kClassLoaderOpeningMark = '[';
54static constexpr char kClassLoaderClosingMark = ']';
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000055static constexpr char kClassLoaderSharedLibraryOpeningMark = '{';
56static constexpr char kClassLoaderSharedLibraryClosingMark = '}';
57static constexpr char kClassLoaderSharedLibrarySeparator = '#';
Calin Juravle7b0648a2017-07-07 18:40:50 -070058static constexpr char kClassLoaderSeparator = ';';
59static constexpr char kClasspathSeparator = ':';
60static constexpr char kDexFileChecksumSeparator = '*';
David Brazdil93d339d2019-03-27 09:56:45 +000061static constexpr char kInMemoryDexClassLoaderDexLocationMagic[] = "<unknown>";
Calin Juravle87e2cb62017-06-13 21:48:45 -070062
63ClassLoaderContext::ClassLoaderContext()
64 : special_shared_library_(false),
65 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070066 dex_files_open_result_(false),
Calin Juravle41acdc12017-07-18 17:45:32 -070067 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070068
69ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
70 : special_shared_library_(false),
71 dex_files_open_attempted_(true),
72 dex_files_open_result_(true),
73 owns_the_dex_files_(owns_the_dex_files) {}
74
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000075// Utility method to add parent and shared libraries of `info` into
76// the `work_list`.
77static void AddToWorkList(
78 ClassLoaderContext::ClassLoaderInfo* info,
79 std::vector<ClassLoaderContext::ClassLoaderInfo*>& work_list) {
80 if (info->parent != nullptr) {
81 work_list.push_back(info->parent.get());
82 }
83 for (size_t i = 0; i < info->shared_libraries.size(); ++i) {
84 work_list.push_back(info->shared_libraries[i].get());
85 }
86}
87
Calin Juravle57d0acc2017-07-11 17:41:30 -070088ClassLoaderContext::~ClassLoaderContext() {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000089 if (!owns_the_dex_files_ && class_loader_chain_ != nullptr) {
Calin Juravle57d0acc2017-07-11 17:41:30 -070090 // If the context does not own the dex/oat files release the unique pointers to
91 // make sure we do not de-allocate them.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000092 std::vector<ClassLoaderInfo*> work_list;
93 work_list.push_back(class_loader_chain_.get());
94 while (!work_list.empty()) {
95 ClassLoaderInfo* info = work_list.back();
96 work_list.pop_back();
97 for (std::unique_ptr<OatFile>& oat_file : info->opened_oat_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -070098 oat_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -070099 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000100 for (std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700101 dex_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -0700102 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000103 AddToWorkList(info, work_list);
Calin Juravle57d0acc2017-07-11 17:41:30 -0700104 }
105 }
106}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700107
Calin Juravle19915892017-08-03 17:10:36 +0000108std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
109 return Create("");
110}
111
Calin Juravle87e2cb62017-06-13 21:48:45 -0700112std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
113 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
114 if (result->Parse(spec)) {
115 return result;
116 } else {
117 return nullptr;
118 }
119}
120
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000121static size_t FindMatchingSharedLibraryCloseMarker(const std::string& spec,
122 size_t shared_library_open_index) {
123 // Counter of opened shared library marker we've encountered so far.
124 uint32_t counter = 1;
125 // The index at which we're operating in the loop.
126 uint32_t string_index = shared_library_open_index + 1;
127 size_t shared_library_close = std::string::npos;
128 while (counter != 0) {
129 shared_library_close =
130 spec.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index);
131 size_t shared_library_open =
132 spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, string_index);
133 if (shared_library_close == std::string::npos) {
134 // No matching closing marker. Return an error.
135 break;
136 }
137
138 if ((shared_library_open == std::string::npos) ||
139 (shared_library_close < shared_library_open)) {
140 // We have seen a closing marker. Decrement the counter.
141 --counter;
142 // Move the search index forward.
143 string_index = shared_library_close + 1;
144 } else {
145 // New nested opening marker. Increment the counter and move the search
146 // index after the marker.
147 ++counter;
148 string_index = shared_library_open + 1;
149 }
150 }
151 return shared_library_close;
152}
153
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000154// The expected format is:
155// "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]{ClassLoaderType2[...]}".
Calin Juravle7b0648a2017-07-07 18:40:50 -0700156// The checksum part of the format is expected only if parse_cheksums is true.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000157std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseClassLoaderSpec(
158 const std::string& class_loader_spec,
159 bool parse_checksums) {
160 ClassLoaderType class_loader_type = ExtractClassLoaderType(class_loader_spec);
161 if (class_loader_type == kInvalidClassLoader) {
162 return nullptr;
163 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000164
165 // InMemoryDexClassLoader's dex location is always bogus. Special-case it.
166 if (class_loader_type == kInMemoryDexClassLoader) {
167 if (parse_checksums) {
168 // Make sure that OpenDexFiles() will never be attempted on this context
169 // because the dex locations of IMC do not correspond to real files.
170 CHECK(!dex_files_open_attempted_ || !dex_files_open_result_)
171 << "Parsing spec not supported when context created from a ClassLoader object";
172 dex_files_open_attempted_ = true;
173 dex_files_open_result_ = false;
174 } else {
175 // Checksums are not provided and dex locations themselves have no meaning
176 // (although we keep them in the spec to simplify parsing). Treat this as
177 // an unknown class loader.
David Brazdil93d339d2019-03-27 09:56:45 +0000178 // We can hit this case if dex2oat is invoked with a spec containing IMC.
179 // Because the dex file data is only available at runtime, we cannot proceed.
David Brazdil1a9ac532019-03-05 11:57:13 +0000180 return nullptr;
181 }
182 }
183
Calin Juravle87e2cb62017-06-13 21:48:45 -0700184 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
185 size_t type_str_size = strlen(class_loader_type_str);
186
187 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
188
189 // Check the opening and closing markers.
190 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000191 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700192 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000193 if ((class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) &&
194 (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderSharedLibraryClosingMark)) {
195 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700196 }
197
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000198 size_t closing_index = class_loader_spec.find_first_of(kClassLoaderClosingMark);
199
Calin Juravle87e2cb62017-06-13 21:48:45 -0700200 // At this point we know the format is ok; continue and extract the classpath.
201 // Note that class loaders with an empty class path are allowed.
202 std::string classpath = class_loader_spec.substr(type_str_size + 1,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000203 closing_index - type_str_size - 1);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700204
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000205 std::unique_ptr<ClassLoaderInfo> info(new ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700206
207 if (!parse_checksums) {
David Brazdil93d339d2019-03-27 09:56:45 +0000208 DCHECK(class_loader_type != kInMemoryDexClassLoader);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000209 Split(classpath, kClasspathSeparator, &info->classpath);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700210 } else {
211 std::vector<std::string> classpath_elements;
212 Split(classpath, kClasspathSeparator, &classpath_elements);
213 for (const std::string& element : classpath_elements) {
214 std::vector<std::string> dex_file_with_checksum;
215 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
216 if (dex_file_with_checksum.size() != 2) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000217 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700218 }
219 uint32_t checksum = 0;
Tom Cherry7bc8e8f2018-10-05 14:34:13 -0700220 if (!android::base::ParseUint(dex_file_with_checksum[1].c_str(), &checksum)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000221 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700222 }
David Brazdil93d339d2019-03-27 09:56:45 +0000223 if ((class_loader_type == kInMemoryDexClassLoader) &&
224 (dex_file_with_checksum[0] != kInMemoryDexClassLoaderDexLocationMagic)) {
225 return nullptr;
226 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000227
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000228 info->classpath.push_back(dex_file_with_checksum[0]);
229 info->checksums.push_back(checksum);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700230 }
231 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700232
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000233 if ((class_loader_spec[class_loader_spec.length() - 1] == kClassLoaderSharedLibraryClosingMark) &&
234 (class_loader_spec[class_loader_spec.length() - 2] != kClassLoaderSharedLibraryOpeningMark)) {
235 // Non-empty list of shared libraries.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000236 size_t start_index = class_loader_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark);
237 if (start_index == std::string::npos) {
238 return nullptr;
239 }
240 std::string shared_libraries_spec =
241 class_loader_spec.substr(start_index + 1, class_loader_spec.length() - start_index - 2);
242 std::vector<std::string> shared_libraries;
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000243 size_t cursor = 0;
244 while (cursor != shared_libraries_spec.length()) {
245 size_t shared_library_separator =
246 shared_libraries_spec.find_first_of(kClassLoaderSharedLibrarySeparator, cursor);
247 size_t shared_library_open =
248 shared_libraries_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, cursor);
249 std::string shared_library_spec;
250 if (shared_library_separator == std::string::npos) {
251 // Only one shared library, for example:
252 // PCL[...]
253 shared_library_spec =
254 shared_libraries_spec.substr(cursor, shared_libraries_spec.length() - cursor);
255 cursor = shared_libraries_spec.length();
256 } else if ((shared_library_open == std::string::npos) ||
257 (shared_library_open > shared_library_separator)) {
258 // We found a shared library without nested shared libraries, for example:
259 // PCL[...]#PCL[...]{...}
260 shared_library_spec =
261 shared_libraries_spec.substr(cursor, shared_library_separator - cursor);
262 cursor = shared_library_separator + 1;
263 } else {
264 // The shared library contains nested shared libraries. Find the matching closing shared
265 // marker for it.
266 size_t closing_marker =
267 FindMatchingSharedLibraryCloseMarker(shared_libraries_spec, shared_library_open);
268 if (closing_marker == std::string::npos) {
269 // No matching closing marker, return an error.
270 return nullptr;
271 }
272 shared_library_spec = shared_libraries_spec.substr(cursor, closing_marker + 1 - cursor);
273 cursor = closing_marker + 1;
274 if (cursor != shared_libraries_spec.length() &&
275 shared_libraries_spec[cursor] == kClassLoaderSharedLibrarySeparator) {
276 // Pass the shared library separator marker.
277 ++cursor;
278 }
279 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000280 std::unique_ptr<ClassLoaderInfo> shared_library(
281 ParseInternal(shared_library_spec, parse_checksums));
282 if (shared_library == nullptr) {
283 return nullptr;
284 }
285 info->shared_libraries.push_back(std::move(shared_library));
286 }
287 }
288
289 return info;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700290}
291
292// Extracts the class loader type from the given spec.
293// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
294// recognized.
295ClassLoaderContext::ClassLoaderType
296ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
David Brazdil1a9ac532019-03-05 11:57:13 +0000297 const ClassLoaderType kValidTypes[] = { kPathClassLoader,
298 kDelegateLastClassLoader,
299 kInMemoryDexClassLoader };
Calin Juravle87e2cb62017-06-13 21:48:45 -0700300 for (const ClassLoaderType& type : kValidTypes) {
301 const char* type_str = GetClassLoaderTypeName(type);
302 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
303 return type;
304 }
305 }
306 return kInvalidClassLoader;
307}
308
309// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
310// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
311// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700312bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700313 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700314 // By default we load the dex files in a PathClassLoader.
315 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
316 // tests)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000317 class_loader_chain_.reset(new ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700318 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700319 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700320
Calin Juravle87e2cb62017-06-13 21:48:45 -0700321 // Stop early if we detect the special shared library, which may be passed as the classpath
322 // for dex2oat when we want to skip the shared libraries check.
323 if (spec == OatFile::kSpecialSharedLibrary) {
Tom Cherry556ace12020-07-24 15:09:55 -0700324 // TODO(calin): move this out from parsing to the oat manager to prevent log spam.
325 VLOG(oat) << "The ClassLoaderContext is a special shared library.";
Calin Juravle87e2cb62017-06-13 21:48:45 -0700326 special_shared_library_ = true;
327 return true;
328 }
329
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000330 CHECK(class_loader_chain_ == nullptr);
331 class_loader_chain_.reset(ParseInternal(spec, parse_checksums));
332 return class_loader_chain_ != nullptr;
333}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700334
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000335ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal(
336 const std::string& spec, bool parse_checksums) {
337 CHECK(!spec.empty());
338 CHECK_NE(spec, OatFile::kSpecialSharedLibrary);
339 std::string remaining = spec;
340 std::unique_ptr<ClassLoaderInfo> first(nullptr);
341 ClassLoaderInfo* previous_iteration = nullptr;
342 while (!remaining.empty()) {
343 std::string class_loader_spec;
344 size_t first_class_loader_separator = remaining.find_first_of(kClassLoaderSeparator);
345 size_t first_shared_library_open =
346 remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark);
347 if (first_class_loader_separator == std::string::npos) {
348 // Only one class loader, for example:
349 // PCL[...]
350 class_loader_spec = remaining;
351 remaining = "";
352 } else if ((first_shared_library_open == std::string::npos) ||
353 (first_shared_library_open > first_class_loader_separator)) {
354 // We found a class loader spec without shared libraries, for example:
355 // PCL[...];PCL[...]{...}
356 class_loader_spec = remaining.substr(0, first_class_loader_separator);
357 remaining = remaining.substr(first_class_loader_separator + 1,
358 remaining.size() - first_class_loader_separator - 1);
359 } else {
360 // The class loader spec contains shared libraries. Find the matching closing
361 // shared library marker for it.
362
Yi Kongd5fe17e2019-10-01 16:18:47 -0700363 size_t shared_library_close =
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000364 FindMatchingSharedLibraryCloseMarker(remaining, first_shared_library_open);
365 if (shared_library_close == std::string::npos) {
366 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
367 return nullptr;
368 }
369 class_loader_spec = remaining.substr(0, shared_library_close + 1);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000370
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000371 // Compute the remaining string to analyze.
372 if (remaining.size() == shared_library_close + 1) {
373 remaining = "";
374 } else if ((remaining.size() == shared_library_close + 2) ||
375 (remaining.at(shared_library_close + 1) != kClassLoaderSeparator)) {
376 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
377 return nullptr;
378 } else {
379 remaining = remaining.substr(shared_library_close + 2,
380 remaining.size() - shared_library_close - 2);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000381 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700382 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000383
384 std::unique_ptr<ClassLoaderInfo> info =
385 ParseClassLoaderSpec(class_loader_spec, parse_checksums);
386 if (info == nullptr) {
387 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
388 return nullptr;
389 }
390 if (first == nullptr) {
Andreas Gampe41c911f2018-11-19 11:34:16 -0800391 first = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000392 previous_iteration = first.get();
393 } else {
394 CHECK(previous_iteration != nullptr);
Andreas Gampe41c911f2018-11-19 11:34:16 -0800395 previous_iteration->parent = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000396 previous_iteration = previous_iteration->parent.get();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700397 }
398 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000399 return first.release();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700400}
401
402// Opens requested class path files and appends them to opened_dex_files. If the dex files have
403// been stripped, this opens them from their oat files (which get added to opened_oat_files).
David Brazdil89821862019-03-19 13:57:43 +0000404bool ClassLoaderContext::OpenDexFiles(InstructionSet isa,
405 const std::string& classpath_dir,
406 const std::vector<int>& fds) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700407 if (dex_files_open_attempted_) {
408 // Do not attempt to re-open the files if we already tried.
409 return dex_files_open_result_;
410 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700411
412 dex_files_open_attempted_ = true;
413 // Assume we can open all dex files. If not, we will set this to false as we go.
414 dex_files_open_result_ = true;
415
416 if (special_shared_library_) {
417 // Nothing to open if the context is a special shared library.
418 return true;
419 }
420
421 // Note that we try to open all dex files even if some fail.
422 // We may get resource-only apks which we cannot load.
423 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
424 // no dex files. So that we can distinguish the real failures...
David Sehr013fd802018-01-11 22:55:24 -0800425 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000426 std::vector<ClassLoaderInfo*> work_list;
Nicolas Geoffray9893c472018-11-13 15:39:53 +0000427 CHECK(class_loader_chain_ != nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000428 work_list.push_back(class_loader_chain_.get());
David Brazdil89821862019-03-19 13:57:43 +0000429 size_t dex_file_index = 0;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000430 while (!work_list.empty()) {
431 ClassLoaderInfo* info = work_list.back();
432 work_list.pop_back();
David Brazdil93d339d2019-03-27 09:56:45 +0000433 DCHECK(info->type != kInMemoryDexClassLoader) << __FUNCTION__ << " not supported for IMC";
434
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000435 size_t opened_dex_files_index = info->opened_dex_files.size();
436 for (const std::string& cp_elem : info->classpath) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700437 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000438 std::string location = cp_elem;
439 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000440 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700441 }
442
David Brazdil89821862019-03-19 13:57:43 +0000443 // If file descriptors were provided for the class loader context dex paths,
444 // get the descriptor which correponds to this dex path. We assume the `fds`
445 // vector follows the same order as a flattened class loader context.
446 int fd = -1;
447 if (!fds.empty()) {
448 if (dex_file_index >= fds.size()) {
449 LOG(WARNING) << "Number of FDs is smaller than number of dex files in the context";
450 dex_files_open_result_ = false;
451 return false;
452 }
453
454 fd = fds[dex_file_index++];
455 DCHECK_GE(fd, 0);
456 }
457
Calin Juravle87e2cb62017-06-13 21:48:45 -0700458 std::string error_msg;
459 // When opening the dex files from the context we expect their checksum to match their
460 // contents. So pass true to verify_checksum.
Nicolas Geoffraybf7705502020-03-16 14:02:31 +0000461 // We don't need to do structural dex file verification, we only need to
462 // check the checksum, so pass false to verify.
David Brazdil89821862019-03-19 13:57:43 +0000463 if (fd < 0) {
464 if (!dex_file_loader.Open(location.c_str(),
465 location.c_str(),
Nicolas Geoffraybf7705502020-03-16 14:02:31 +0000466 /*verify=*/ false,
David Brazdil89821862019-03-19 13:57:43 +0000467 /*verify_checksum=*/ true,
468 &error_msg,
469 &info->opened_dex_files)) {
470 // If we fail to open the dex file because it's been stripped, try to
471 // open the dex file from its corresponding oat file.
472 // This could happen when we need to recompile a pre-build whose dex
473 // code has been stripped (for example, if the pre-build is only
474 // quicken and we want to re-compile it speed-profile).
475 // TODO(calin): Use the vdex directly instead of going through the oat file.
476 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
477 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
478 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
479 if (oat_file != nullptr &&
480 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
481 info->opened_oat_files.push_back(std::move(oat_file));
482 info->opened_dex_files.insert(info->opened_dex_files.end(),
483 std::make_move_iterator(oat_dex_files.begin()),
484 std::make_move_iterator(oat_dex_files.end()));
485 } else {
486 LOG(WARNING) << "Could not open dex files from location: " << location;
487 dex_files_open_result_ = false;
488 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700489 }
David Brazdil89821862019-03-19 13:57:43 +0000490 } else if (!dex_file_loader.Open(fd,
491 location.c_str(),
Nicolas Geoffraybf7705502020-03-16 14:02:31 +0000492 /*verify=*/ false,
David Brazdil89821862019-03-19 13:57:43 +0000493 /*verify_checksum=*/ true,
494 &error_msg,
495 &info->opened_dex_files)) {
496 LOG(WARNING) << "Could not open dex files from fd " << fd << " for location: " << location;
497 dex_files_open_result_ = false;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700498 }
499 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700500
501 // We finished opening the dex files from the classpath.
502 // Now update the classpath and the checksum with the locations of the dex files.
503 //
504 // We do this because initially the classpath contains the paths of the dex files; and
505 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
506 // file paths with the actual dex locations being loaded.
507 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
508 // location in the class paths.
509 // Note that this will also remove the paths that could not be opened.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000510 info->original_classpath = std::move(info->classpath);
511 info->classpath.clear();
512 info->checksums.clear();
513 for (size_t k = opened_dex_files_index; k < info->opened_dex_files.size(); k++) {
514 std::unique_ptr<const DexFile>& dex = info->opened_dex_files[k];
515 info->classpath.push_back(dex->GetLocation());
516 info->checksums.push_back(dex->GetLocationChecksum());
Calin Juravlec5b215f2017-09-12 14:49:37 -0700517 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000518 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700519 }
520
David Brazdil89821862019-03-19 13:57:43 +0000521 // Check that if file descriptors were provided, there were exactly as many
522 // as we have encountered while iterating over this class loader context.
523 if (dex_file_index != fds.size()) {
524 LOG(WARNING) << fds.size() << " FDs provided but only " << dex_file_index
525 << " dex files are in the class loader context";
526 dex_files_open_result_ = false;
527 }
528
Calin Juravle87e2cb62017-06-13 21:48:45 -0700529 return dex_files_open_result_;
530}
531
532bool ClassLoaderContext::RemoveLocationsFromClassPaths(
533 const dchecked_vector<std::string>& locations) {
534 CHECK(!dex_files_open_attempted_)
535 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
536
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000537 if (class_loader_chain_ == nullptr) {
538 return false;
539 }
540
Calin Juravle87e2cb62017-06-13 21:48:45 -0700541 std::set<std::string> canonical_locations;
542 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700543 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700544 }
545 bool removed_locations = false;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000546 std::vector<ClassLoaderInfo*> work_list;
547 work_list.push_back(class_loader_chain_.get());
548 while (!work_list.empty()) {
549 ClassLoaderInfo* info = work_list.back();
550 work_list.pop_back();
551 size_t initial_size = info->classpath.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700552 auto kept_it = std::remove_if(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000553 info->classpath.begin(),
554 info->classpath.end(),
Calin Juravle87e2cb62017-06-13 21:48:45 -0700555 [canonical_locations](const std::string& location) {
556 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700557 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700558 });
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000559 info->classpath.erase(kept_it, info->classpath.end());
560 if (initial_size != info->classpath.size()) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700561 removed_locations = true;
562 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000563 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700564 }
565 return removed_locations;
566}
567
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700568std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700569 return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700570}
571
Mathieu Chartierc4440772018-04-16 14:40:56 -0700572std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
573 ClassLoaderContext* stored_context) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700574 return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700575}
576
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800577std::map<std::string, std::string>
578ClassLoaderContext::EncodeClassPathContexts(const std::string& base_dir) const {
579 CheckDexFilesOpened("EncodeClassPathContexts");
580 if (class_loader_chain_ == nullptr) {
581 return std::map<std::string, std::string>{};
582 }
583
584 std::map<std::string, std::string> results;
585 std::vector<std::string> dex_locations;
586 std::vector<uint32_t> checksums;
587 dex_locations.reserve(class_loader_chain_->original_classpath.size());
588
589 std::ostringstream encoded_libs_and_parent_stream;
590 EncodeSharedLibAndParent(*class_loader_chain_,
591 base_dir,
592 /*for_dex2oat=*/true,
593 /*stored_info=*/nullptr,
594 encoded_libs_and_parent_stream);
595 std::string encoded_libs_and_parent(encoded_libs_and_parent_stream.str());
596
597 std::set<std::string> seen_locations;
598 for (const std::string& path : class_loader_chain_->classpath) {
599 // The classpath will contain multiple entries for multidex files, so make sure this is the
600 // first time we're seeing this file.
601 const std::string base_location(DexFileLoader::GetBaseLocation(path));
602 if (!seen_locations.insert(base_location).second) {
603 continue;
604 }
605
606 std::ostringstream out;
607 EncodeClassPath(base_dir, dex_locations, checksums, class_loader_chain_->type, out);
608 out << encoded_libs_and_parent;
609 results.emplace(base_location, out.str());
610
611 dex_locations.push_back(base_location);
612 }
613
614 return results;
615}
616
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700617std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700618 bool for_dex2oat,
619 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700620 CheckDexFilesOpened("EncodeContextForOatFile");
621 if (special_shared_library_) {
622 return OatFile::kSpecialSharedLibrary;
623 }
624
Mathieu Chartierc4440772018-04-16 14:40:56 -0700625 if (stored_context != nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000626 DCHECK_EQ(GetParentChainSize(), stored_context->GetParentChainSize());
Mathieu Chartierc4440772018-04-16 14:40:56 -0700627 }
628
Calin Juravle7b0648a2017-07-07 18:40:50 -0700629 std::ostringstream out;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000630 if (class_loader_chain_ == nullptr) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700631 // We can get in this situation if the context was created with a class path containing the
632 // source dex files which were later removed (happens during run-tests).
633 out << GetClassLoaderTypeName(kPathClassLoader)
634 << kClassLoaderOpeningMark
635 << kClassLoaderClosingMark;
636 return out.str();
637 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700638
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000639 EncodeContextInternal(
640 *class_loader_chain_,
641 base_dir,
642 for_dex2oat,
643 (stored_context == nullptr ? nullptr : stored_context->class_loader_chain_.get()),
644 out);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700645 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700646}
647
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800648void ClassLoaderContext::EncodeClassPath(const std::string& base_dir,
649 const std::vector<std::string>& dex_locations,
650 const std::vector<uint32_t>& checksums,
651 ClassLoaderType type,
652 std::ostringstream& out) const {
653 CHECK(checksums.empty() || dex_locations.size() == checksums.size());
654 out << GetClassLoaderTypeName(type);
655 out << kClassLoaderOpeningMark;
656 const size_t len = dex_locations.size();
657 for (size_t k = 0; k < len; k++) {
658 std::string location = dex_locations[k];
659 if (k > 0) {
660 out << kClasspathSeparator;
661 }
662 if (type == kInMemoryDexClassLoader) {
663 out << kInMemoryDexClassLoaderDexLocationMagic;
664 } else if (!base_dir.empty()
665 && location.substr(0, base_dir.length()) == base_dir) {
666 // Find paths that were relative and convert them back from absolute.
667 out << location.substr(base_dir.length() + 1).c_str();
668 } else {
669 out << location.c_str();
670 }
671 if (!checksums.empty()) {
672 out << kDexFileChecksumSeparator;
673 out << checksums[k];
674 }
675 }
676 out << kClassLoaderClosingMark;
677}
678
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000679void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info,
680 const std::string& base_dir,
681 bool for_dex2oat,
682 ClassLoaderInfo* stored_info,
683 std::ostringstream& out) const {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800684 std::vector<std::string> locations;
685 std::vector<uint32_t> checksums;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000686 std::set<std::string> seen_locations;
687 SafeMap<std::string, std::string> remap;
688 if (stored_info != nullptr) {
689 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
690 // Note that we don't care if the same name appears twice.
691 remap.Put(info.original_classpath[k], stored_info->classpath[k]);
692 }
693 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800694
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000695 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
696 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
697 if (for_dex2oat) {
698 // dex2oat only needs the base location. It cannot accept multidex locations.
699 // So ensure we only add each file once.
700 bool new_insert = seen_locations.insert(
701 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
702 if (!new_insert) {
703 continue;
704 }
705 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800706
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000707 std::string location = dex_file->GetLocation();
708 // If there is a stored class loader remap, fix up the multidex strings.
709 if (!remap.empty()) {
710 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
711 auto it = remap.find(base_dex_location);
712 CHECK(it != remap.end()) << base_dex_location;
713 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
714 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800715 locations.emplace_back(std::move(location));
716
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000717 // dex2oat does not need the checksums.
718 if (!for_dex2oat) {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800719 checksums.push_back(dex_file->GetLocationChecksum());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000720 }
721 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800722 EncodeClassPath(base_dir, locations, checksums, info.type, out);
723 EncodeSharedLibAndParent(info, base_dir, for_dex2oat, stored_info, out);
724}
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000725
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800726void ClassLoaderContext::EncodeSharedLibAndParent(const ClassLoaderInfo& info,
727 const std::string& base_dir,
728 bool for_dex2oat,
729 ClassLoaderInfo* stored_info,
730 std::ostringstream& out) const {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000731 if (!info.shared_libraries.empty()) {
732 out << kClassLoaderSharedLibraryOpeningMark;
733 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
734 if (i > 0) {
735 out << kClassLoaderSharedLibrarySeparator;
736 }
737 EncodeContextInternal(
738 *info.shared_libraries[i].get(),
739 base_dir,
740 for_dex2oat,
741 (stored_info == nullptr ? nullptr : stored_info->shared_libraries[i].get()),
742 out);
743 }
744 out << kClassLoaderSharedLibraryClosingMark;
745 }
746 if (info.parent != nullptr) {
747 out << kClassLoaderSeparator;
748 EncodeContextInternal(
749 *info.parent.get(),
750 base_dir,
751 for_dex2oat,
752 (stored_info == nullptr ? nullptr : stored_info->parent.get()),
753 out);
754 }
755}
756
757// Returns the WellKnownClass for the given class loader type.
758static jclass GetClassLoaderClass(ClassLoaderContext::ClassLoaderType type) {
759 switch (type) {
760 case ClassLoaderContext::kPathClassLoader:
761 return WellKnownClasses::dalvik_system_PathClassLoader;
762 case ClassLoaderContext::kDelegateLastClassLoader:
763 return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +0000764 case ClassLoaderContext::kInMemoryDexClassLoader:
765 return WellKnownClasses::dalvik_system_InMemoryDexClassLoader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000766 case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch.
767 }
768 LOG(FATAL) << "Invalid class loader type " << type;
769 UNREACHABLE();
770}
771
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000772static std::string FlattenClasspath(const std::vector<std::string>& classpath) {
773 return android::base::Join(classpath, ':');
774}
775
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000776static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal(
777 Thread* self,
778 ScopedObjectAccess& soa,
779 const ClassLoaderContext::ClassLoaderInfo& info,
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000780 bool for_shared_library,
781 VariableSizedHandleScope& map_scope,
782 std::map<std::string, Handle<mirror::ClassLoader>>& canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000783 bool add_compilation_sources,
784 const std::vector<const DexFile*>& compilation_sources)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000785 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000786 if (for_shared_library) {
787 // Check if the shared library has already been created.
788 auto search = canonicalized_libraries.find(FlattenClasspath(info.classpath));
789 if (search != canonicalized_libraries.end()) {
790 return search->second.Get();
791 }
792 }
793
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000794 StackHandleScope<3> hs(self);
795 MutableHandle<mirror::ObjectArray<mirror::ClassLoader>> libraries(
796 hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr));
797
798 if (!info.shared_libraries.empty()) {
799 libraries.Assign(mirror::ObjectArray<mirror::ClassLoader>::Alloc(
800 self,
801 GetClassRoot<mirror::ObjectArray<mirror::ClassLoader>>(),
802 info.shared_libraries.size()));
803 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
804 // We should only add the compilation sources to the first class loader.
805 libraries->Set(i,
806 CreateClassLoaderInternal(
807 self,
808 soa,
809 *info.shared_libraries[i].get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000810 /* for_shared_library= */ true,
811 map_scope,
812 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000813 /* add_compilation_sources= */ false,
814 compilation_sources));
815 }
816 }
817
818 MutableHandle<mirror::ClassLoader> parent = hs.NewHandle<mirror::ClassLoader>(nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000819 if (info.parent != nullptr) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000820 // We should only add the compilation sources to the first class loader.
821 parent.Assign(CreateClassLoaderInternal(
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000822 self,
823 soa,
824 *info.parent.get(),
825 /* for_shared_library= */ false,
826 map_scope,
827 canonicalized_libraries,
828 /* add_compilation_sources= */ false,
829 compilation_sources));
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000830 }
831 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
832 info.opened_dex_files);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000833 if (add_compilation_sources) {
834 // For the first class loader, its classpath comes first, followed by compilation sources.
835 // This ensures that whenever we need to resolve classes from it the classpath elements
836 // come first.
837 class_path_files.insert(class_path_files.end(),
838 compilation_sources.begin(),
839 compilation_sources.end());
840 }
841 Handle<mirror::Class> loader_class = hs.NewHandle<mirror::Class>(
842 soa.Decode<mirror::Class>(GetClassLoaderClass(info.type)));
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000843 ObjPtr<mirror::ClassLoader> loader =
844 Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
845 self,
846 class_path_files,
847 loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +0000848 parent,
849 libraries);
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000850 if (for_shared_library) {
851 canonicalized_libraries[FlattenClasspath(info.classpath)] =
852 map_scope.NewHandle<mirror::ClassLoader>(loader);
853 }
854 return loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000855}
856
Calin Juravle87e2cb62017-06-13 21:48:45 -0700857jobject ClassLoaderContext::CreateClassLoader(
858 const std::vector<const DexFile*>& compilation_sources) const {
859 CheckDexFilesOpened("CreateClassLoader");
860
861 Thread* self = Thread::Current();
862 ScopedObjectAccess soa(self);
863
Calin Juravlec79470d2017-07-12 17:37:42 -0700864 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700865
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000866 if (class_loader_chain_ == nullptr) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000867 CHECK(special_shared_library_);
Calin Juravlec79470d2017-07-12 17:37:42 -0700868 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700869 }
870
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000871 // Create a map of canonicalized shared libraries. As we're holding objects,
872 // we're creating a variable size handle scope to put handles in the map.
873 VariableSizedHandleScope map_scope(self);
874 std::map<std::string, Handle<mirror::ClassLoader>> canonicalized_libraries;
875
876 // Create the class loader.
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000877 ObjPtr<mirror::ClassLoader> loader =
878 CreateClassLoaderInternal(self,
879 soa,
880 *class_loader_chain_.get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000881 /* for_shared_library= */ false,
882 map_scope,
883 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000884 /* add_compilation_sources= */ true,
885 compilation_sources);
886 // Make it a global ref and return.
887 ScopedLocalRef<jobject> local_ref(
888 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
889 return soa.Env()->NewGlobalRef(local_ref.get());
Calin Juravle87e2cb62017-06-13 21:48:45 -0700890}
891
892std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
893 CheckDexFilesOpened("FlattenOpenedDexFiles");
894
895 std::vector<const DexFile*> result;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000896 if (class_loader_chain_ == nullptr) {
897 return result;
898 }
899 std::vector<ClassLoaderInfo*> work_list;
900 work_list.push_back(class_loader_chain_.get());
901 while (!work_list.empty()) {
902 ClassLoaderInfo* info = work_list.back();
903 work_list.pop_back();
904 for (const std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700905 result.push_back(dex_file.get());
906 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000907 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700908 }
909 return result;
910}
911
David Brazdil89821862019-03-19 13:57:43 +0000912std::string ClassLoaderContext::FlattenDexPaths() const {
913 if (class_loader_chain_ == nullptr) {
914 return "";
915 }
916
917 std::vector<std::string> result;
918 std::vector<ClassLoaderInfo*> work_list;
919 work_list.push_back(class_loader_chain_.get());
920 while (!work_list.empty()) {
921 ClassLoaderInfo* info = work_list.back();
922 work_list.pop_back();
923 for (const std::string& dex_path : info->classpath) {
924 result.push_back(dex_path);
925 }
926 AddToWorkList(info, work_list);
927 }
928 return FlattenClasspath(result);
929}
930
Calin Juravle87e2cb62017-06-13 21:48:45 -0700931const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
932 switch (type) {
933 case kPathClassLoader: return kPathClassLoaderString;
934 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
David Brazdil1a9ac532019-03-05 11:57:13 +0000935 case kInMemoryDexClassLoader: return kInMemoryDexClassLoaderString;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700936 default:
937 LOG(FATAL) << "Invalid class loader type " << type;
938 UNREACHABLE();
939 }
940}
941
942void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
943 CHECK(dex_files_open_attempted_)
944 << "Dex files were not successfully opened before the call to " << calling_method
945 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
946}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700947
Calin Juravle57d0acc2017-07-11 17:41:30 -0700948// Collects the dex files from the give Java dex_file object. Only the dex files with
949// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
950static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
951 ArtField* const cookie_field,
952 std::vector<const DexFile*>* out_dex_files)
953 REQUIRES_SHARED(Locks::mutator_lock_) {
954 if (java_dex_file == nullptr) {
955 return true;
956 }
957 // On the Java side, the dex files are stored in the cookie field.
Vladimir Marko4617d582019-03-28 13:48:31 +0000958 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
Calin Juravle57d0acc2017-07-11 17:41:30 -0700959 if (long_array == nullptr) {
960 // This should never happen so log a warning.
961 LOG(ERROR) << "Unexpected null cookie";
962 return false;
963 }
964 int32_t long_array_size = long_array->GetLength();
965 // Index 0 from the long array stores the oat file. The dex files start at index 1.
966 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +0100967 const DexFile* cp_dex_file =
968 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700969 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
970 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
971 // cp_dex_file can be null.
972 out_dex_files->push_back(cp_dex_file);
973 }
974 }
975 return true;
976}
977
978// Collects all the dex files loaded by the given class loader.
979// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
980// a null list of dex elements or a null dex element).
981static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
982 Handle<mirror::ClassLoader> class_loader,
983 std::vector<const DexFile*>* out_dex_files)
984 REQUIRES_SHARED(Locks::mutator_lock_) {
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800985 CHECK(IsInstanceOfBaseDexClassLoader(soa, class_loader));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700986
987 // All supported class loaders inherit from BaseDexClassLoader.
988 // We need to get the DexPathList and loop through it.
989 ArtField* const cookie_field =
990 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
991 ArtField* const dex_file_field =
992 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
993 ObjPtr<mirror::Object> dex_path_list =
994 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
995 GetObject(class_loader.Get());
996 CHECK(cookie_field != nullptr);
997 CHECK(dex_file_field != nullptr);
998 if (dex_path_list == nullptr) {
999 // This may be null if the current class loader is under construction and it does not
1000 // have its fields setup yet.
1001 return true;
1002 }
1003 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1004 ObjPtr<mirror::Object> dex_elements_obj =
1005 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1006 GetObject(dex_path_list);
1007 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1008 // at the mCookie which is a DexFile vector.
1009 if (dex_elements_obj == nullptr) {
1010 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
1011 // and assume we have no elements.
1012 return true;
1013 } else {
1014 StackHandleScope<1> hs(soa.Self());
1015 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
1016 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
Alex Lighta9bbc082019-11-14 14:51:41 -08001017 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001018 if (element == nullptr) {
1019 // Should never happen, log an error and break.
1020 // TODO(calin): It's unclear if we should just assert here.
1021 // This code was propagated to oat_file_manager from the class linker where it would
1022 // throw a NPE. For now, return false which will mark this class loader as unsupported.
1023 LOG(ERROR) << "Unexpected null in the dex element list";
1024 return false;
1025 }
1026 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
1027 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1028 return false;
1029 }
1030 }
1031 }
1032
1033 return true;
1034}
1035
1036static bool GetDexFilesFromDexElementsArray(
1037 ScopedObjectAccessAlreadyRunnable& soa,
1038 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1039 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
1040 DCHECK(dex_elements != nullptr);
1041
1042 ArtField* const cookie_field =
1043 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
1044 ArtField* const dex_file_field =
1045 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Vladimir Marko0984e482019-03-27 16:41:41 +00001046 const ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001047 WellKnownClasses::dalvik_system_DexPathList__Element);
Vladimir Marko0984e482019-03-27 16:41:41 +00001048 const ObjPtr<mirror::Class> dexfile_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001049 WellKnownClasses::dalvik_system_DexFile);
1050
Alex Lighta9bbc082019-11-14 14:51:41 -08001051 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001052 // We can hit a null element here because this is invoked with a partially filled dex_elements
1053 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
1054 // list of dex files which were opened before.
1055 if (element == nullptr) {
1056 continue;
1057 }
1058
1059 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
1060 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
1061 // a historical glitch. All the java code opens dex files using an array of Elements.
1062 ObjPtr<mirror::Object> dex_file;
1063 if (element_class == element->GetClass()) {
1064 dex_file = dex_file_field->GetObject(element);
1065 } else if (dexfile_class == element->GetClass()) {
1066 dex_file = element;
1067 } else {
1068 LOG(ERROR) << "Unsupported element in dex_elements: "
1069 << mirror::Class::PrettyClass(element->GetClass());
1070 return false;
1071 }
1072
1073 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1074 return false;
1075 }
1076 }
1077 return true;
1078}
1079
1080// Adds the `class_loader` info to the `context`.
1081// The dex file present in `dex_elements` array (if not null) will be added at the end of
1082// the classpath.
1083// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
1084// BootClassLoader. Note that the class loader chain is expected to be short.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001085bool ClassLoaderContext::CreateInfoFromClassLoader(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001086 ScopedObjectAccessAlreadyRunnable& soa,
1087 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001088 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1089 ClassLoaderInfo* child_info,
1090 bool is_shared_library)
Calin Juravle57d0acc2017-07-11 17:41:30 -07001091 REQUIRES_SHARED(Locks::mutator_lock_) {
1092 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
1093 // Nothing to do for the boot class loader as we don't add its dex files to the context.
1094 return true;
1095 }
1096
1097 ClassLoaderContext::ClassLoaderType type;
1098 if (IsPathOrDexClassLoader(soa, class_loader)) {
1099 type = kPathClassLoader;
1100 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
1101 type = kDelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +00001102 } else if (IsInMemoryDexClassLoader(soa, class_loader)) {
1103 type = kInMemoryDexClassLoader;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001104 } else {
1105 LOG(WARNING) << "Unsupported class loader";
1106 return false;
1107 }
1108
1109 // Inspect the class loader for its dex files.
1110 std::vector<const DexFile*> dex_files_loaded;
1111 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
1112
1113 // If we have a dex_elements array extract its dex elements now.
1114 // This is used in two situations:
1115 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
1116 // passing the list of already open dex files each time. This ensures that we see the
1117 // correct context even if the ClassLoader under construction is not fully build.
1118 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
1119 // appending them to the current class loader. When the new code paths are loaded in
1120 // BaseDexClassLoader, the paths already present in the class loader will be passed
1121 // in the dex_elements array.
1122 if (dex_elements != nullptr) {
1123 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
1124 }
1125
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001126 ClassLoaderInfo* info = new ClassLoaderContext::ClassLoaderInfo(type);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001127 // Attach the `ClassLoaderInfo` now, before populating dex files, as only the
1128 // `ClassLoaderContext` knows whether these dex files should be deleted or not.
1129 if (child_info == nullptr) {
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001130 class_loader_chain_.reset(info);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001131 } else if (is_shared_library) {
1132 child_info->shared_libraries.push_back(std::unique_ptr<ClassLoaderInfo>(info));
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001133 } else {
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001134 child_info->parent.reset(info);
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001135 }
1136
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001137 // Now that `info` is in the chain, populate dex files.
Calin Juravle57d0acc2017-07-11 17:41:30 -07001138 for (const DexFile* dex_file : dex_files_loaded) {
David Brazdil93d339d2019-03-27 09:56:45 +00001139 // Dex location of dex files loaded with InMemoryDexClassLoader is always bogus.
1140 // Use a magic value for the classpath instead.
1141 info->classpath.push_back((type == kInMemoryDexClassLoader)
1142 ? kInMemoryDexClassLoaderDexLocationMagic
1143 : dex_file->GetLocation());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001144 info->checksums.push_back(dex_file->GetLocationChecksum());
1145 info->opened_dex_files.emplace_back(dex_file);
Calin Juravle57d0acc2017-07-11 17:41:30 -07001146 }
1147
Calin Juravle57d0acc2017-07-11 17:41:30 -07001148 // Note that dex_elements array is null here. The elements are considered to be part of the
1149 // current class loader and are not passed to the parents.
1150 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001151
1152 // Add the shared libraries.
1153 StackHandleScope<3> hs(Thread::Current());
1154 ArtField* field =
1155 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1156 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
1157 if (raw_shared_libraries != nullptr) {
1158 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries =
1159 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>());
1160 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08001161 for (auto library : shared_libraries.Iterate<mirror::ClassLoader>()) {
1162 temp_loader.Assign(library);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001163 if (!CreateInfoFromClassLoader(
1164 soa, temp_loader, null_dex_elements, info, /*is_shared_library=*/ true)) {
1165 return false;
1166 }
1167 }
1168 }
1169
1170 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
1171 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
1172 if (!CreateInfoFromClassLoader(
1173 soa, parent, null_dex_elements, info, /*is_shared_library=*/ false)) {
1174 return false;
1175 }
1176 return true;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001177}
1178
1179std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
1180 jobject class_loader,
1181 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -07001182 CHECK(class_loader != nullptr);
1183
Calin Juravle57d0acc2017-07-11 17:41:30 -07001184 ScopedObjectAccess soa(Thread::Current());
1185 StackHandleScope<2> hs(soa.Self());
1186 Handle<mirror::ClassLoader> h_class_loader =
1187 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1188 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
1189 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001190 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/ false));
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001191 if (!result->CreateInfoFromClassLoader(
1192 soa, h_class_loader, h_dex_elements, nullptr, /*is_shared_library=*/ false)) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001193 return nullptr;
1194 }
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001195 return result;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001196}
1197
Dan Zimmermanb682ea42019-12-23 06:59:06 -08001198std::map<std::string, std::string>
1199ClassLoaderContext::EncodeClassPathContextsForClassLoader(jobject class_loader) {
1200 std::unique_ptr<ClassLoaderContext> clc =
1201 ClassLoaderContext::CreateContextForClassLoader(class_loader, nullptr);
1202 if (clc != nullptr) {
1203 return clc->EncodeClassPathContexts("");
1204 }
1205
1206 ScopedObjectAccess soa(Thread::Current());
1207 StackHandleScope<1> hs(soa.Self());
1208 Handle<mirror::ClassLoader> h_class_loader =
1209 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1210 if (!IsInstanceOfBaseDexClassLoader(soa, h_class_loader)) {
1211 return std::map<std::string, std::string>{};
1212 }
1213
1214 std::vector<const DexFile*> dex_files_loaded;
1215 CollectDexFilesFromSupportedClassLoader(soa, h_class_loader, &dex_files_loaded);
1216
1217 std::map<std::string, std::string> results;
1218 for (const DexFile* dex_file : dex_files_loaded) {
1219 results.emplace(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1220 ClassLoaderContext::kUnsupportedClassLoaderContextEncoding);
1221 }
1222 return results;
1223}
1224
Dan Zimmermanc9fa7702020-01-31 13:35:12 -08001225bool ClassLoaderContext::IsValidEncoding(const std::string& possible_encoded_class_loader_context) {
1226 return ClassLoaderContext::Create(possible_encoded_class_loader_context.c_str()) != nullptr
1227 || possible_encoded_class_loader_context == kUnsupportedClassLoaderContextEncoding;
1228}
1229
Mathieu Chartieradc90862018-05-11 13:03:06 -07001230ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
1231 const std::string& context_spec,
1232 bool verify_names,
1233 bool verify_checksums) const {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001234 if (verify_names || verify_checksums) {
1235 DCHECK(dex_files_open_attempted_);
1236 DCHECK(dex_files_open_result_);
1237 }
Calin Juravlec5b215f2017-09-12 14:49:37 -07001238
Calin Juravle3f918642017-07-11 19:04:20 -07001239 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001240 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -07001241 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -07001242 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001243 }
1244
Calin Juravlec5b215f2017-09-12 14:49:37 -07001245 // Special shared library contexts always match. They essentially instruct the runtime
1246 // to ignore the class path check because the oat file is known to be loaded in different
1247 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
1248 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -07001249 if (expected_context.special_shared_library_) {
1250 // Special case where we are the only entry in the class path.
Nicolas Geoffray9893c472018-11-13 15:39:53 +00001251 if (class_loader_chain_ != nullptr &&
1252 class_loader_chain_->parent == nullptr &&
1253 class_loader_chain_->classpath.size() == 0) {
Mathieu Chartieradc90862018-05-11 13:03:06 -07001254 return VerificationResult::kVerifies;
1255 }
1256 return VerificationResult::kForcedToSkipChecks;
1257 } else if (special_shared_library_) {
1258 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -07001259 }
1260
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001261 ClassLoaderInfo* info = class_loader_chain_.get();
1262 ClassLoaderInfo* expected = expected_context.class_loader_chain_.get();
1263 CHECK(info != nullptr);
1264 CHECK(expected != nullptr);
1265 if (!ClassLoaderInfoMatch(*info, *expected, context_spec, verify_names, verify_checksums)) {
Mathieu Chartieradc90862018-05-11 13:03:06 -07001266 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001267 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001268 return VerificationResult::kVerifies;
1269}
Calin Juravle3f918642017-07-11 19:04:20 -07001270
Vladimir Marko36ec5982019-11-28 10:55:16 +00001271// Returns true if absolute `path` ends with relative `suffix` starting at
1272// a directory name boundary, i.e. after a '/'. For example, "foo/bar"
1273// is a valid suffix of "/data/foo/bar" but not "/data-foo/bar".
1274static inline bool AbsolutePathHasRelativeSuffix(const std::string& path,
1275 const std::string& suffix) {
1276 DCHECK(IsAbsoluteLocation(path));
1277 DCHECK(!IsAbsoluteLocation(suffix));
1278 return (path.size() > suffix.size()) &&
1279 (path[path.size() - suffix.size() - 1u] == '/') &&
1280 (std::string_view(path).substr(/*pos*/ path.size() - suffix.size()) == suffix);
1281}
1282
Calin Juravleb495e7f2020-04-06 19:29:45 -07001283// Returns true if the given dex names are mathing, false otherwise.
1284static bool AreDexNameMatching(const std::string& actual_dex_name,
1285 const std::string& expected_dex_name) {
1286 // Compute the dex location that must be compared.
1287 // We shouldn't do a naive comparison `actual_dex_name == expected_dex_name`
1288 // because even if they refer to the same file, one could be encoded as a relative location
1289 // and the other as an absolute one.
1290 bool is_dex_name_absolute = IsAbsoluteLocation(actual_dex_name);
1291 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_dex_name);
1292 bool dex_names_match = false;
1293
1294 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
1295 // If both locations are absolute or relative then compare them as they are.
1296 // This is usually the case for: shared libraries and secondary dex files.
1297 dex_names_match = (actual_dex_name == expected_dex_name);
1298 } else if (is_dex_name_absolute) {
1299 // The runtime name is absolute but the compiled name (the expected one) is relative.
1300 // This is the case for split apks which depend on base or on other splits.
1301 dex_names_match =
1302 AbsolutePathHasRelativeSuffix(actual_dex_name, expected_dex_name);
1303 } else if (is_expected_dex_name_absolute) {
1304 // The runtime name is relative but the compiled name is absolute.
1305 // There is no expected use case that would end up here as dex files are always loaded
1306 // with their absolute location. However, be tolerant and do the best effort (in case
1307 // there are unexpected new use case...).
1308 dex_names_match =
1309 AbsolutePathHasRelativeSuffix(expected_dex_name, actual_dex_name);
1310 } else {
1311 // Both locations are relative. In this case there's not much we can be sure about
1312 // except that the names are the same. The checksum will ensure that the files are
1313 // are same. This should not happen outside testing and manual invocations.
1314 dex_names_match = (actual_dex_name == expected_dex_name);
1315 }
1316
1317 return dex_names_match;
1318}
1319
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001320bool ClassLoaderContext::ClassLoaderInfoMatch(
1321 const ClassLoaderInfo& info,
1322 const ClassLoaderInfo& expected_info,
1323 const std::string& context_spec,
1324 bool verify_names,
1325 bool verify_checksums) const {
1326 if (info.type != expected_info.type) {
1327 LOG(WARNING) << "ClassLoaderContext type mismatch"
1328 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
1329 << ", found=" << GetClassLoaderTypeName(info.type)
1330 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1331 return false;
1332 }
1333 if (info.classpath.size() != expected_info.classpath.size()) {
1334 LOG(WARNING) << "ClassLoaderContext classpath size mismatch"
1335 << ". expected=" << expected_info.classpath.size()
1336 << ", found=" << info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001337 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001338 return false;
1339 }
Calin Juravle3f918642017-07-11 19:04:20 -07001340
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001341 if (verify_checksums) {
1342 DCHECK_EQ(info.classpath.size(), info.checksums.size());
1343 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
1344 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001345
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001346 if (verify_names) {
Calin Juravle3f918642017-07-11 19:04:20 -07001347 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravleb495e7f2020-04-06 19:29:45 -07001348 bool dex_names_match = AreDexNameMatching(info.classpath[k], expected_info.classpath[k]);
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001349
1350 // Compare the locations.
Vladimir Marko36ec5982019-11-28 10:55:16 +00001351 if (!dex_names_match) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001352 LOG(WARNING) << "ClassLoaderContext classpath element mismatch"
Calin Juravle3f918642017-07-11 19:04:20 -07001353 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001354 << ", found=" << info.classpath[k]
1355 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001356 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001357 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001358
1359 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -07001360 if (info.checksums[k] != expected_info.checksums[k]) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001361 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch"
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001362 << ". expected=" << expected_info.checksums[k]
1363 << ", found=" << info.checksums[k]
1364 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001365 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001366 }
1367 }
1368 }
Calin Juravle3f918642017-07-11 19:04:20 -07001369
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001370 if (info.shared_libraries.size() != expected_info.shared_libraries.size()) {
1371 LOG(WARNING) << "ClassLoaderContext shared library size mismatch. "
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001372 << "Expected=" << expected_info.shared_libraries.size()
1373 << ", found=" << info.shared_libraries.size()
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001374 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1375 return false;
Calin Juravlec79470d2017-07-12 17:37:42 -07001376 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001377 for (size_t i = 0; i < info.shared_libraries.size(); ++i) {
1378 if (!ClassLoaderInfoMatch(*info.shared_libraries[i].get(),
1379 *expected_info.shared_libraries[i].get(),
1380 context_spec,
1381 verify_names,
1382 verify_checksums)) {
1383 return false;
1384 }
1385 }
1386 if (info.parent.get() == nullptr) {
1387 if (expected_info.parent.get() != nullptr) {
1388 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1389 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1390 return false;
1391 }
1392 return true;
1393 } else if (expected_info.parent.get() == nullptr) {
1394 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1395 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1396 return false;
1397 } else {
1398 return ClassLoaderInfoMatch(*info.parent.get(),
1399 *expected_info.parent.get(),
1400 context_spec,
1401 verify_names,
1402 verify_checksums);
1403 }
Calin Juravlec79470d2017-07-12 17:37:42 -07001404}
1405
Calin Juravlea63a2e92020-04-15 20:02:00 -07001406std::set<const DexFile*> ClassLoaderContext::CheckForDuplicateDexFiles(
Calin Juravleb495e7f2020-04-06 19:29:45 -07001407 const std::vector<const DexFile*>& dex_files_to_check) {
1408 DCHECK(dex_files_open_attempted_);
1409 DCHECK(dex_files_open_result_);
1410
Calin Juravlea63a2e92020-04-15 20:02:00 -07001411 std::set<const DexFile*> result;
Calin Juravleb495e7f2020-04-06 19:29:45 -07001412
Calin Juravlea63a2e92020-04-15 20:02:00 -07001413 // If we are the special shared library or the chain is null there's nothing
1414 // we can check, return an empty list;
1415 // The class loader chain can be null if there were issues when creating the
1416 // class loader context (e.g. tests).
1417 if (special_shared_library_ || class_loader_chain_ == nullptr) {
Calin Juravleb495e7f2020-04-06 19:29:45 -07001418 return result;
1419 }
1420
Calin Juravlea63a2e92020-04-15 20:02:00 -07001421 // We only check the current Class Loader which the first one in the chain.
1422 // Cross class-loader duplicates may be a valid scenario (though unlikely
1423 // in the Android world) - and as such we decide not to warn on them.
1424 ClassLoaderInfo* info = class_loader_chain_.get();
1425 for (size_t k = 0; k < info->classpath.size(); k++) {
1426 for (const DexFile* dex_file : dex_files_to_check) {
1427 if (info->checksums[k] == dex_file->GetLocationChecksum()
1428 && AreDexNameMatching(info->classpath[k], dex_file->GetLocation())) {
1429 result.insert(dex_file);
Calin Juravleb495e7f2020-04-06 19:29:45 -07001430 }
1431 }
Calin Juravleb495e7f2020-04-06 19:29:45 -07001432 }
1433
1434 return result;
1435}
1436
Calin Juravle87e2cb62017-06-13 21:48:45 -07001437} // namespace art