blob: 929cf8c31d8f5d3cf1d3431ea8bac85c3d1176ee [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"
Calin Juravle98071152021-01-27 18:41:58 -080029#include "base/systrace.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070030#include "class_linker.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070031#include "class_loader_utils.h"
Vladimir Marko5868ada2020-05-12 11:50:34 +010032#include "class_root-inl.h"
David Sehr013fd802018-01-11 22:55:24 -080033#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080034#include "dex/dex_file.h"
35#include "dex/dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070036#include "handle_scope-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010037#include "jni/jni_internal.h"
Vladimir Markobdc93b42019-03-29 16:12:04 +000038#include "mirror/class_loader-inl.h"
Alex Lighta9bbc082019-11-14 14:51:41 -080039#include "mirror/object.h"
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +000040#include "mirror/object_array-alloc-inl.h"
41#include "nativehelper/scoped_local_ref.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070042#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070043#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070044#include "runtime.h"
45#include "scoped_thread_state_change-inl.h"
46#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070047#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070048
49namespace art {
50
51static constexpr char kPathClassLoaderString[] = "PCL";
52static constexpr char kDelegateLastClassLoaderString[] = "DLC";
David Brazdil1a9ac532019-03-05 11:57:13 +000053static constexpr char kInMemoryDexClassLoaderString[] = "IMC";
Calin Juravle87e2cb62017-06-13 21:48:45 -070054static constexpr char kClassLoaderOpeningMark = '[';
55static constexpr char kClassLoaderClosingMark = ']';
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000056static constexpr char kClassLoaderSharedLibraryOpeningMark = '{';
57static constexpr char kClassLoaderSharedLibraryClosingMark = '}';
58static constexpr char kClassLoaderSharedLibrarySeparator = '#';
Calin Juravle7b0648a2017-07-07 18:40:50 -070059static constexpr char kClassLoaderSeparator = ';';
60static constexpr char kClasspathSeparator = ':';
61static constexpr char kDexFileChecksumSeparator = '*';
David Brazdil93d339d2019-03-27 09:56:45 +000062static constexpr char kInMemoryDexClassLoaderDexLocationMagic[] = "<unknown>";
Calin Juravle87e2cb62017-06-13 21:48:45 -070063
64ClassLoaderContext::ClassLoaderContext()
65 : special_shared_library_(false),
Calin Juravle6e6f1b22020-12-15 19:13:19 -080066 dex_files_state_(ContextDexFilesState::kDexFilesNotOpened),
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),
Calin Juravle6e6f1b22020-12-15 19:13:19 -080071 dex_files_state_(ContextDexFilesState::kDexFilesOpened),
Calin Juravle57d0acc2017-07-11 17:41:30 -070072 owns_the_dex_files_(owns_the_dex_files) {}
73
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000074// Utility method to add parent and shared libraries of `info` into
75// the `work_list`.
76static void AddToWorkList(
77 ClassLoaderContext::ClassLoaderInfo* info,
78 std::vector<ClassLoaderContext::ClassLoaderInfo*>& work_list) {
79 if (info->parent != nullptr) {
80 work_list.push_back(info->parent.get());
81 }
82 for (size_t i = 0; i < info->shared_libraries.size(); ++i) {
83 work_list.push_back(info->shared_libraries[i].get());
84 }
85}
86
Calin Juravle57d0acc2017-07-11 17:41:30 -070087ClassLoaderContext::~ClassLoaderContext() {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000088 if (!owns_the_dex_files_ && class_loader_chain_ != nullptr) {
Calin Juravle57d0acc2017-07-11 17:41:30 -070089 // If the context does not own the dex/oat files release the unique pointers to
90 // make sure we do not de-allocate them.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000091 std::vector<ClassLoaderInfo*> work_list;
92 work_list.push_back(class_loader_chain_.get());
93 while (!work_list.empty()) {
94 ClassLoaderInfo* info = work_list.back();
95 work_list.pop_back();
96 for (std::unique_ptr<OatFile>& oat_file : info->opened_oat_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -070097 oat_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -070098 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000099 for (std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700100 dex_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -0700101 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000102 AddToWorkList(info, work_list);
Calin Juravle57d0acc2017-07-11 17:41:30 -0700103 }
104 }
105}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700106
Calin Juravle19915892017-08-03 17:10:36 +0000107std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
108 return Create("");
109}
110
Calin Juravle87e2cb62017-06-13 21:48:45 -0700111std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
112 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
113 if (result->Parse(spec)) {
114 return result;
115 } else {
116 return nullptr;
117 }
118}
119
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000120static size_t FindMatchingSharedLibraryCloseMarker(const std::string& spec,
121 size_t shared_library_open_index) {
122 // Counter of opened shared library marker we've encountered so far.
123 uint32_t counter = 1;
124 // The index at which we're operating in the loop.
125 uint32_t string_index = shared_library_open_index + 1;
126 size_t shared_library_close = std::string::npos;
127 while (counter != 0) {
128 shared_library_close =
129 spec.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index);
130 size_t shared_library_open =
131 spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, string_index);
132 if (shared_library_close == std::string::npos) {
133 // No matching closing marker. Return an error.
134 break;
135 }
136
137 if ((shared_library_open == std::string::npos) ||
138 (shared_library_close < shared_library_open)) {
139 // We have seen a closing marker. Decrement the counter.
140 --counter;
141 // Move the search index forward.
142 string_index = shared_library_close + 1;
143 } else {
144 // New nested opening marker. Increment the counter and move the search
145 // index after the marker.
146 ++counter;
147 string_index = shared_library_open + 1;
148 }
149 }
150 return shared_library_close;
151}
152
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000153// The expected format is:
154// "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]{ClassLoaderType2[...]}".
Calin Juravle7b0648a2017-07-07 18:40:50 -0700155// The checksum part of the format is expected only if parse_cheksums is true.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000156std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseClassLoaderSpec(
157 const std::string& class_loader_spec,
158 bool parse_checksums) {
159 ClassLoaderType class_loader_type = ExtractClassLoaderType(class_loader_spec);
160 if (class_loader_type == kInvalidClassLoader) {
161 return nullptr;
162 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000163
164 // InMemoryDexClassLoader's dex location is always bogus. Special-case it.
165 if (class_loader_type == kInMemoryDexClassLoader) {
166 if (parse_checksums) {
167 // Make sure that OpenDexFiles() will never be attempted on this context
168 // because the dex locations of IMC do not correspond to real files.
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800169 CHECK(dex_files_state_ == kDexFilesNotOpened || dex_files_state_ == kDexFilesOpenFailed)
170 << "Parsing spec not supported when context created from a ClassLoader object: "
171 << "dex_files_state_=" << dex_files_state_;
172 dex_files_state_ = kDexFilesOpenFailed;
David Brazdil1a9ac532019-03-05 11:57:13 +0000173 } else {
174 // Checksums are not provided and dex locations themselves have no meaning
175 // (although we keep them in the spec to simplify parsing). Treat this as
176 // an unknown class loader.
David Brazdil93d339d2019-03-27 09:56:45 +0000177 // We can hit this case if dex2oat is invoked with a spec containing IMC.
178 // Because the dex file data is only available at runtime, we cannot proceed.
David Brazdil1a9ac532019-03-05 11:57:13 +0000179 return nullptr;
180 }
181 }
182
Calin Juravle87e2cb62017-06-13 21:48:45 -0700183 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
184 size_t type_str_size = strlen(class_loader_type_str);
185
186 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
187
188 // Check the opening and closing markers.
189 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000190 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700191 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000192 if ((class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) &&
193 (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderSharedLibraryClosingMark)) {
194 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700195 }
196
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000197 size_t closing_index = class_loader_spec.find_first_of(kClassLoaderClosingMark);
198
Calin Juravle87e2cb62017-06-13 21:48:45 -0700199 // At this point we know the format is ok; continue and extract the classpath.
200 // Note that class loaders with an empty class path are allowed.
201 std::string classpath = class_loader_spec.substr(type_str_size + 1,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000202 closing_index - type_str_size - 1);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700203
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000204 std::unique_ptr<ClassLoaderInfo> info(new ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700205
206 if (!parse_checksums) {
David Brazdil93d339d2019-03-27 09:56:45 +0000207 DCHECK(class_loader_type != kInMemoryDexClassLoader);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000208 Split(classpath, kClasspathSeparator, &info->classpath);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700209 } else {
210 std::vector<std::string> classpath_elements;
211 Split(classpath, kClasspathSeparator, &classpath_elements);
212 for (const std::string& element : classpath_elements) {
213 std::vector<std::string> dex_file_with_checksum;
214 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
215 if (dex_file_with_checksum.size() != 2) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000216 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700217 }
218 uint32_t checksum = 0;
Tom Cherry7bc8e8f2018-10-05 14:34:13 -0700219 if (!android::base::ParseUint(dex_file_with_checksum[1].c_str(), &checksum)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000220 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700221 }
David Brazdil93d339d2019-03-27 09:56:45 +0000222 if ((class_loader_type == kInMemoryDexClassLoader) &&
223 (dex_file_with_checksum[0] != kInMemoryDexClassLoaderDexLocationMagic)) {
224 return nullptr;
225 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000226
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000227 info->classpath.push_back(dex_file_with_checksum[0]);
228 info->checksums.push_back(checksum);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700229 }
230 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700231
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000232 if ((class_loader_spec[class_loader_spec.length() - 1] == kClassLoaderSharedLibraryClosingMark) &&
233 (class_loader_spec[class_loader_spec.length() - 2] != kClassLoaderSharedLibraryOpeningMark)) {
234 // Non-empty list of shared libraries.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000235 size_t start_index = class_loader_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark);
236 if (start_index == std::string::npos) {
237 return nullptr;
238 }
239 std::string shared_libraries_spec =
240 class_loader_spec.substr(start_index + 1, class_loader_spec.length() - start_index - 2);
241 std::vector<std::string> shared_libraries;
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000242 size_t cursor = 0;
243 while (cursor != shared_libraries_spec.length()) {
244 size_t shared_library_separator =
245 shared_libraries_spec.find_first_of(kClassLoaderSharedLibrarySeparator, cursor);
246 size_t shared_library_open =
247 shared_libraries_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, cursor);
248 std::string shared_library_spec;
249 if (shared_library_separator == std::string::npos) {
250 // Only one shared library, for example:
251 // PCL[...]
252 shared_library_spec =
253 shared_libraries_spec.substr(cursor, shared_libraries_spec.length() - cursor);
254 cursor = shared_libraries_spec.length();
255 } else if ((shared_library_open == std::string::npos) ||
256 (shared_library_open > shared_library_separator)) {
257 // We found a shared library without nested shared libraries, for example:
258 // PCL[...]#PCL[...]{...}
259 shared_library_spec =
260 shared_libraries_spec.substr(cursor, shared_library_separator - cursor);
261 cursor = shared_library_separator + 1;
262 } else {
263 // The shared library contains nested shared libraries. Find the matching closing shared
264 // marker for it.
265 size_t closing_marker =
266 FindMatchingSharedLibraryCloseMarker(shared_libraries_spec, shared_library_open);
267 if (closing_marker == std::string::npos) {
268 // No matching closing marker, return an error.
269 return nullptr;
270 }
271 shared_library_spec = shared_libraries_spec.substr(cursor, closing_marker + 1 - cursor);
272 cursor = closing_marker + 1;
273 if (cursor != shared_libraries_spec.length() &&
274 shared_libraries_spec[cursor] == kClassLoaderSharedLibrarySeparator) {
275 // Pass the shared library separator marker.
276 ++cursor;
277 }
278 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000279 std::unique_ptr<ClassLoaderInfo> shared_library(
280 ParseInternal(shared_library_spec, parse_checksums));
281 if (shared_library == nullptr) {
282 return nullptr;
283 }
284 info->shared_libraries.push_back(std::move(shared_library));
285 }
286 }
287
288 return info;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700289}
290
291// Extracts the class loader type from the given spec.
292// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
293// recognized.
294ClassLoaderContext::ClassLoaderType
295ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
David Brazdil1a9ac532019-03-05 11:57:13 +0000296 const ClassLoaderType kValidTypes[] = { kPathClassLoader,
297 kDelegateLastClassLoader,
298 kInMemoryDexClassLoader };
Calin Juravle87e2cb62017-06-13 21:48:45 -0700299 for (const ClassLoaderType& type : kValidTypes) {
300 const char* type_str = GetClassLoaderTypeName(type);
301 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
302 return type;
303 }
304 }
305 return kInvalidClassLoader;
306}
307
308// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
309// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
310// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700311bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700312 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700313 // By default we load the dex files in a PathClassLoader.
314 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
315 // tests)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000316 class_loader_chain_.reset(new ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700317 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700318 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700319
Calin Juravle87e2cb62017-06-13 21:48:45 -0700320 // Stop early if we detect the special shared library, which may be passed as the classpath
321 // for dex2oat when we want to skip the shared libraries check.
322 if (spec == OatFile::kSpecialSharedLibrary) {
Tom Cherry556ace12020-07-24 15:09:55 -0700323 // TODO(calin): move this out from parsing to the oat manager to prevent log spam.
324 VLOG(oat) << "The ClassLoaderContext is a special shared library.";
Calin Juravle87e2cb62017-06-13 21:48:45 -0700325 special_shared_library_ = true;
326 return true;
327 }
328
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000329 CHECK(class_loader_chain_ == nullptr);
330 class_loader_chain_.reset(ParseInternal(spec, parse_checksums));
331 return class_loader_chain_ != nullptr;
332}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700333
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000334ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal(
335 const std::string& spec, bool parse_checksums) {
336 CHECK(!spec.empty());
337 CHECK_NE(spec, OatFile::kSpecialSharedLibrary);
338 std::string remaining = spec;
339 std::unique_ptr<ClassLoaderInfo> first(nullptr);
340 ClassLoaderInfo* previous_iteration = nullptr;
341 while (!remaining.empty()) {
342 std::string class_loader_spec;
343 size_t first_class_loader_separator = remaining.find_first_of(kClassLoaderSeparator);
344 size_t first_shared_library_open =
345 remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark);
346 if (first_class_loader_separator == std::string::npos) {
347 // Only one class loader, for example:
348 // PCL[...]
349 class_loader_spec = remaining;
350 remaining = "";
351 } else if ((first_shared_library_open == std::string::npos) ||
352 (first_shared_library_open > first_class_loader_separator)) {
353 // We found a class loader spec without shared libraries, for example:
354 // PCL[...];PCL[...]{...}
355 class_loader_spec = remaining.substr(0, first_class_loader_separator);
356 remaining = remaining.substr(first_class_loader_separator + 1,
357 remaining.size() - first_class_loader_separator - 1);
358 } else {
359 // The class loader spec contains shared libraries. Find the matching closing
360 // shared library marker for it.
361
Yi Kongd5fe17e2019-10-01 16:18:47 -0700362 size_t shared_library_close =
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000363 FindMatchingSharedLibraryCloseMarker(remaining, first_shared_library_open);
364 if (shared_library_close == std::string::npos) {
365 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
366 return nullptr;
367 }
368 class_loader_spec = remaining.substr(0, shared_library_close + 1);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000369
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000370 // Compute the remaining string to analyze.
371 if (remaining.size() == shared_library_close + 1) {
372 remaining = "";
373 } else if ((remaining.size() == shared_library_close + 2) ||
374 (remaining.at(shared_library_close + 1) != kClassLoaderSeparator)) {
375 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
376 return nullptr;
377 } else {
378 remaining = remaining.substr(shared_library_close + 2,
379 remaining.size() - shared_library_close - 2);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000380 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700381 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000382
383 std::unique_ptr<ClassLoaderInfo> info =
384 ParseClassLoaderSpec(class_loader_spec, parse_checksums);
385 if (info == nullptr) {
386 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
387 return nullptr;
388 }
389 if (first == nullptr) {
Andreas Gampe41c911f2018-11-19 11:34:16 -0800390 first = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000391 previous_iteration = first.get();
392 } else {
393 CHECK(previous_iteration != nullptr);
Andreas Gampe41c911f2018-11-19 11:34:16 -0800394 previous_iteration->parent = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000395 previous_iteration = previous_iteration->parent.get();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700396 }
397 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000398 return first.release();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700399}
400
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800401// Opens requested class path files and appends them to opened_dex_files. If the dex files have
402// been stripped, this opens them from their oat files (which get added to opened_oat_files).
Calin Juravle5ff23932020-12-11 18:26:14 -0800403bool ClassLoaderContext::OpenDexFiles(const std::string& classpath_dir,
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800404 const std::vector<int>& fds,
405 bool only_read_checksums) {
406 switch (dex_files_state_) {
407 case kDexFilesNotOpened: break; // files not opened, continue.
408 case kDexFilesOpenFailed: return false; // previous attempt failed.
409 case kDexFilesOpened: return true; // previous attempt succeed.
410 case kDexFilesChecksumsRead:
411 if (only_read_checksums) {
412 return true; // we already read the checksums.
413 } else {
414 break; // we already read the checksums but have to open the dex files; continue.
415 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700416 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700417
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800418 // Assume we can open the files. If not, we will adjust as we go.
419 dex_files_state_ = only_read_checksums ? kDexFilesChecksumsRead : kDexFilesOpened;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700420
421 if (special_shared_library_) {
422 // Nothing to open if the context is a special shared library.
423 return true;
424 }
425
426 // Note that we try to open all dex files even if some fail.
427 // We may get resource-only apks which we cannot load.
428 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
429 // no dex files. So that we can distinguish the real failures...
David Sehr013fd802018-01-11 22:55:24 -0800430 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000431 std::vector<ClassLoaderInfo*> work_list;
Nicolas Geoffray9893c472018-11-13 15:39:53 +0000432 CHECK(class_loader_chain_ != nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000433 work_list.push_back(class_loader_chain_.get());
David Brazdil89821862019-03-19 13:57:43 +0000434 size_t dex_file_index = 0;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000435 while (!work_list.empty()) {
436 ClassLoaderInfo* info = work_list.back();
437 work_list.pop_back();
David Brazdil93d339d2019-03-27 09:56:45 +0000438 DCHECK(info->type != kInMemoryDexClassLoader) << __FUNCTION__ << " not supported for IMC";
439
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800440 // Holds the dex locations for the classpath files we've opened.
441 std::vector<std::string> dex_locations;
442 // Holds the checksums for the classpath files we've opened.
443 std::vector<uint32_t> dex_checksums;
444
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000445 for (const std::string& cp_elem : info->classpath) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700446 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000447 std::string location = cp_elem;
448 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000449 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700450 }
451
David Brazdil89821862019-03-19 13:57:43 +0000452 // If file descriptors were provided for the class loader context dex paths,
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800453 // get the descriptor which corresponds to this dex path. We assume the `fds`
David Brazdil89821862019-03-19 13:57:43 +0000454 // vector follows the same order as a flattened class loader context.
455 int fd = -1;
456 if (!fds.empty()) {
457 if (dex_file_index >= fds.size()) {
458 LOG(WARNING) << "Number of FDs is smaller than number of dex files in the context";
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800459 dex_files_state_ = kDexFilesOpenFailed;
David Brazdil89821862019-03-19 13:57:43 +0000460 return false;
461 }
462
463 fd = fds[dex_file_index++];
464 DCHECK_GE(fd, 0);
465 }
466
Calin Juravle87e2cb62017-06-13 21:48:45 -0700467 std::string error_msg;
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800468 if (only_read_checksums) {
469 bool zip_file_only_contains_uncompress_dex;
470 if (!dex_file_loader.GetMultiDexChecksums(location.c_str(),
471 &dex_checksums,
472 &dex_locations,
473 &error_msg,
474 fd,
475 &zip_file_only_contains_uncompress_dex)) {
476 LOG(WARNING) << "Could not get dex checksums for location " << location << ", fd=" << fd;
477 dex_files_state_ = kDexFilesOpenFailed;
478 }
479 } else {
480 // When opening the dex files from the context we expect their checksum to match their
481 // contents. So pass true to verify_checksum.
482 // We don't need to do structural dex file verification, we only need to
483 // check the checksum, so pass false to verify.
484 size_t opened_dex_files_index = info->opened_dex_files.size();
485 if (!dex_file_loader.Open(location.c_str(),
486 fd,
487 location.c_str(),
488 /*verify=*/ false,
489 /*verify_checksum=*/ true,
490 &error_msg,
491 &info->opened_dex_files)) {
492 LOG(WARNING) << "Could not open dex files for location " << location << ", fd=" << fd;
493 dex_files_state_ = kDexFilesOpenFailed;
494 } else {
495 for (size_t k = opened_dex_files_index; k < info->opened_dex_files.size(); k++) {
496 std::unique_ptr<const DexFile>& dex = info->opened_dex_files[k];
497 dex_locations.push_back(dex->GetLocation());
498 dex_checksums.push_back(dex->GetLocationChecksum());
499 }
500 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700501 }
502 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700503
504 // We finished opening the dex files from the classpath.
505 // Now update the classpath and the checksum with the locations of the dex files.
506 //
507 // We do this because initially the classpath contains the paths of the dex files; and
508 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
509 // file paths with the actual dex locations being loaded.
510 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
511 // location in the class paths.
512 // Note that this will also remove the paths that could not be opened.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000513 info->original_classpath = std::move(info->classpath);
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800514 DCHECK(dex_locations.size() == dex_checksums.size());
515 info->classpath = dex_locations;
516 info->checksums = dex_checksums;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000517 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700518 }
519
David Brazdil89821862019-03-19 13:57:43 +0000520 // Check that if file descriptors were provided, there were exactly as many
521 // as we have encountered while iterating over this class loader context.
522 if (dex_file_index != fds.size()) {
523 LOG(WARNING) << fds.size() << " FDs provided but only " << dex_file_index
524 << " dex files are in the class loader context";
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800525 dex_files_state_ = kDexFilesOpenFailed;
David Brazdil89821862019-03-19 13:57:43 +0000526 }
527
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800528 return dex_files_state_ != kDexFilesOpenFailed;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700529}
530
531bool ClassLoaderContext::RemoveLocationsFromClassPaths(
532 const dchecked_vector<std::string>& locations) {
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800533 CHECK_EQ(dex_files_state_, kDexFilesNotOpened)
Calin Juravle87e2cb62017-06-13 21:48:45 -0700534 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
535
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000536 if (class_loader_chain_ == nullptr) {
537 return false;
538 }
539
Calin Juravle87e2cb62017-06-13 21:48:45 -0700540 std::set<std::string> canonical_locations;
541 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700542 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700543 }
544 bool removed_locations = false;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000545 std::vector<ClassLoaderInfo*> work_list;
546 work_list.push_back(class_loader_chain_.get());
547 while (!work_list.empty()) {
548 ClassLoaderInfo* info = work_list.back();
549 work_list.pop_back();
550 size_t initial_size = info->classpath.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700551 auto kept_it = std::remove_if(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000552 info->classpath.begin(),
553 info->classpath.end(),
Calin Juravle87e2cb62017-06-13 21:48:45 -0700554 [canonical_locations](const std::string& location) {
555 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700556 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700557 });
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000558 info->classpath.erase(kept_it, info->classpath.end());
559 if (initial_size != info->classpath.size()) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700560 removed_locations = true;
561 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000562 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700563 }
564 return removed_locations;
565}
566
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700567std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700568 return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700569}
570
Mathieu Chartierc4440772018-04-16 14:40:56 -0700571std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
572 ClassLoaderContext* stored_context) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700573 return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700574}
575
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800576std::map<std::string, std::string>
577ClassLoaderContext::EncodeClassPathContexts(const std::string& base_dir) const {
578 CheckDexFilesOpened("EncodeClassPathContexts");
579 if (class_loader_chain_ == nullptr) {
580 return std::map<std::string, std::string>{};
581 }
582
583 std::map<std::string, std::string> results;
584 std::vector<std::string> dex_locations;
585 std::vector<uint32_t> checksums;
586 dex_locations.reserve(class_loader_chain_->original_classpath.size());
587
588 std::ostringstream encoded_libs_and_parent_stream;
589 EncodeSharedLibAndParent(*class_loader_chain_,
590 base_dir,
591 /*for_dex2oat=*/true,
592 /*stored_info=*/nullptr,
593 encoded_libs_and_parent_stream);
594 std::string encoded_libs_and_parent(encoded_libs_and_parent_stream.str());
595
596 std::set<std::string> seen_locations;
597 for (const std::string& path : class_loader_chain_->classpath) {
598 // The classpath will contain multiple entries for multidex files, so make sure this is the
599 // first time we're seeing this file.
600 const std::string base_location(DexFileLoader::GetBaseLocation(path));
601 if (!seen_locations.insert(base_location).second) {
602 continue;
603 }
604
605 std::ostringstream out;
606 EncodeClassPath(base_dir, dex_locations, checksums, class_loader_chain_->type, out);
607 out << encoded_libs_and_parent;
608 results.emplace(base_location, out.str());
609
610 dex_locations.push_back(base_location);
611 }
612
613 return results;
614}
615
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700616std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700617 bool for_dex2oat,
618 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700619 CheckDexFilesOpened("EncodeContextForOatFile");
620 if (special_shared_library_) {
621 return OatFile::kSpecialSharedLibrary;
622 }
623
Mathieu Chartierc4440772018-04-16 14:40:56 -0700624 if (stored_context != nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000625 DCHECK_EQ(GetParentChainSize(), stored_context->GetParentChainSize());
Mathieu Chartierc4440772018-04-16 14:40:56 -0700626 }
627
Calin Juravle7b0648a2017-07-07 18:40:50 -0700628 std::ostringstream out;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000629 if (class_loader_chain_ == nullptr) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700630 // We can get in this situation if the context was created with a class path containing the
631 // source dex files which were later removed (happens during run-tests).
632 out << GetClassLoaderTypeName(kPathClassLoader)
633 << kClassLoaderOpeningMark
634 << kClassLoaderClosingMark;
635 return out.str();
636 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700637
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000638 EncodeContextInternal(
639 *class_loader_chain_,
640 base_dir,
641 for_dex2oat,
642 (stored_context == nullptr ? nullptr : stored_context->class_loader_chain_.get()),
643 out);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700644 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700645}
646
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800647void ClassLoaderContext::EncodeClassPath(const std::string& base_dir,
648 const std::vector<std::string>& dex_locations,
649 const std::vector<uint32_t>& checksums,
650 ClassLoaderType type,
651 std::ostringstream& out) const {
652 CHECK(checksums.empty() || dex_locations.size() == checksums.size());
653 out << GetClassLoaderTypeName(type);
654 out << kClassLoaderOpeningMark;
655 const size_t len = dex_locations.size();
656 for (size_t k = 0; k < len; k++) {
657 std::string location = dex_locations[k];
658 if (k > 0) {
659 out << kClasspathSeparator;
660 }
661 if (type == kInMemoryDexClassLoader) {
662 out << kInMemoryDexClassLoaderDexLocationMagic;
663 } else if (!base_dir.empty()
664 && location.substr(0, base_dir.length()) == base_dir) {
665 // Find paths that were relative and convert them back from absolute.
666 out << location.substr(base_dir.length() + 1).c_str();
667 } else {
668 out << location.c_str();
669 }
670 if (!checksums.empty()) {
671 out << kDexFileChecksumSeparator;
672 out << checksums[k];
673 }
674 }
675 out << kClassLoaderClosingMark;
676}
677
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000678void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info,
679 const std::string& base_dir,
680 bool for_dex2oat,
681 ClassLoaderInfo* stored_info,
682 std::ostringstream& out) const {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800683 std::vector<std::string> locations;
684 std::vector<uint32_t> checksums;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000685 std::set<std::string> seen_locations;
686 SafeMap<std::string, std::string> remap;
687 if (stored_info != nullptr) {
688 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
689 // Note that we don't care if the same name appears twice.
690 remap.Put(info.original_classpath[k], stored_info->classpath[k]);
691 }
692 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800693
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000694 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
695 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
696 if (for_dex2oat) {
697 // dex2oat only needs the base location. It cannot accept multidex locations.
698 // So ensure we only add each file once.
699 bool new_insert = seen_locations.insert(
700 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
701 if (!new_insert) {
702 continue;
703 }
704 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800705
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000706 std::string location = dex_file->GetLocation();
707 // If there is a stored class loader remap, fix up the multidex strings.
708 if (!remap.empty()) {
709 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
710 auto it = remap.find(base_dex_location);
711 CHECK(it != remap.end()) << base_dex_location;
712 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
713 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800714 locations.emplace_back(std::move(location));
715
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000716 // dex2oat does not need the checksums.
717 if (!for_dex2oat) {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800718 checksums.push_back(dex_file->GetLocationChecksum());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000719 }
720 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800721 EncodeClassPath(base_dir, locations, checksums, info.type, out);
722 EncodeSharedLibAndParent(info, base_dir, for_dex2oat, stored_info, out);
723}
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000724
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800725void ClassLoaderContext::EncodeSharedLibAndParent(const ClassLoaderInfo& info,
726 const std::string& base_dir,
727 bool for_dex2oat,
728 ClassLoaderInfo* stored_info,
729 std::ostringstream& out) const {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000730 if (!info.shared_libraries.empty()) {
731 out << kClassLoaderSharedLibraryOpeningMark;
732 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
733 if (i > 0) {
734 out << kClassLoaderSharedLibrarySeparator;
735 }
736 EncodeContextInternal(
737 *info.shared_libraries[i].get(),
738 base_dir,
739 for_dex2oat,
740 (stored_info == nullptr ? nullptr : stored_info->shared_libraries[i].get()),
741 out);
742 }
743 out << kClassLoaderSharedLibraryClosingMark;
744 }
745 if (info.parent != nullptr) {
746 out << kClassLoaderSeparator;
747 EncodeContextInternal(
748 *info.parent.get(),
749 base_dir,
750 for_dex2oat,
751 (stored_info == nullptr ? nullptr : stored_info->parent.get()),
752 out);
753 }
754}
755
756// Returns the WellKnownClass for the given class loader type.
757static jclass GetClassLoaderClass(ClassLoaderContext::ClassLoaderType type) {
758 switch (type) {
759 case ClassLoaderContext::kPathClassLoader:
760 return WellKnownClasses::dalvik_system_PathClassLoader;
761 case ClassLoaderContext::kDelegateLastClassLoader:
762 return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +0000763 case ClassLoaderContext::kInMemoryDexClassLoader:
764 return WellKnownClasses::dalvik_system_InMemoryDexClassLoader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000765 case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch.
766 }
767 LOG(FATAL) << "Invalid class loader type " << type;
768 UNREACHABLE();
769}
770
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000771static std::string FlattenClasspath(const std::vector<std::string>& classpath) {
772 return android::base::Join(classpath, ':');
773}
774
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000775static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal(
776 Thread* self,
777 ScopedObjectAccess& soa,
778 const ClassLoaderContext::ClassLoaderInfo& info,
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000779 bool for_shared_library,
780 VariableSizedHandleScope& map_scope,
781 std::map<std::string, Handle<mirror::ClassLoader>>& canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000782 bool add_compilation_sources,
783 const std::vector<const DexFile*>& compilation_sources)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000784 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000785 if (for_shared_library) {
786 // Check if the shared library has already been created.
787 auto search = canonicalized_libraries.find(FlattenClasspath(info.classpath));
788 if (search != canonicalized_libraries.end()) {
789 return search->second.Get();
790 }
791 }
792
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000793 StackHandleScope<3> hs(self);
794 MutableHandle<mirror::ObjectArray<mirror::ClassLoader>> libraries(
795 hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr));
796
797 if (!info.shared_libraries.empty()) {
798 libraries.Assign(mirror::ObjectArray<mirror::ClassLoader>::Alloc(
799 self,
800 GetClassRoot<mirror::ObjectArray<mirror::ClassLoader>>(),
801 info.shared_libraries.size()));
802 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
803 // We should only add the compilation sources to the first class loader.
804 libraries->Set(i,
805 CreateClassLoaderInternal(
806 self,
807 soa,
808 *info.shared_libraries[i].get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000809 /* for_shared_library= */ true,
810 map_scope,
811 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000812 /* add_compilation_sources= */ false,
813 compilation_sources));
814 }
815 }
816
817 MutableHandle<mirror::ClassLoader> parent = hs.NewHandle<mirror::ClassLoader>(nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000818 if (info.parent != nullptr) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000819 // We should only add the compilation sources to the first class loader.
820 parent.Assign(CreateClassLoaderInternal(
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000821 self,
822 soa,
823 *info.parent.get(),
824 /* for_shared_library= */ false,
825 map_scope,
826 canonicalized_libraries,
827 /* add_compilation_sources= */ false,
828 compilation_sources));
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000829 }
830 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
831 info.opened_dex_files);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000832 if (add_compilation_sources) {
833 // For the first class loader, its classpath comes first, followed by compilation sources.
834 // This ensures that whenever we need to resolve classes from it the classpath elements
835 // come first.
836 class_path_files.insert(class_path_files.end(),
837 compilation_sources.begin(),
838 compilation_sources.end());
839 }
840 Handle<mirror::Class> loader_class = hs.NewHandle<mirror::Class>(
841 soa.Decode<mirror::Class>(GetClassLoaderClass(info.type)));
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000842 ObjPtr<mirror::ClassLoader> loader =
843 Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
844 self,
845 class_path_files,
846 loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +0000847 parent,
848 libraries);
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000849 if (for_shared_library) {
850 canonicalized_libraries[FlattenClasspath(info.classpath)] =
851 map_scope.NewHandle<mirror::ClassLoader>(loader);
852 }
853 return loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000854}
855
Calin Juravle87e2cb62017-06-13 21:48:45 -0700856jobject ClassLoaderContext::CreateClassLoader(
857 const std::vector<const DexFile*>& compilation_sources) const {
858 CheckDexFilesOpened("CreateClassLoader");
859
860 Thread* self = Thread::Current();
861 ScopedObjectAccess soa(self);
862
Calin Juravlec79470d2017-07-12 17:37:42 -0700863 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700864
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000865 if (class_loader_chain_ == nullptr) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000866 CHECK(special_shared_library_);
Calin Juravlec79470d2017-07-12 17:37:42 -0700867 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700868 }
869
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000870 // Create a map of canonicalized shared libraries. As we're holding objects,
871 // we're creating a variable size handle scope to put handles in the map.
872 VariableSizedHandleScope map_scope(self);
873 std::map<std::string, Handle<mirror::ClassLoader>> canonicalized_libraries;
874
875 // Create the class loader.
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000876 ObjPtr<mirror::ClassLoader> loader =
877 CreateClassLoaderInternal(self,
878 soa,
879 *class_loader_chain_.get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000880 /* for_shared_library= */ false,
881 map_scope,
882 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000883 /* add_compilation_sources= */ true,
884 compilation_sources);
885 // Make it a global ref and return.
886 ScopedLocalRef<jobject> local_ref(
887 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
888 return soa.Env()->NewGlobalRef(local_ref.get());
Calin Juravle87e2cb62017-06-13 21:48:45 -0700889}
890
891std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
892 CheckDexFilesOpened("FlattenOpenedDexFiles");
893
894 std::vector<const DexFile*> result;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000895 if (class_loader_chain_ == nullptr) {
896 return result;
897 }
898 std::vector<ClassLoaderInfo*> work_list;
899 work_list.push_back(class_loader_chain_.get());
900 while (!work_list.empty()) {
901 ClassLoaderInfo* info = work_list.back();
902 work_list.pop_back();
903 for (const std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700904 result.push_back(dex_file.get());
905 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000906 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700907 }
908 return result;
909}
910
David Brazdil89821862019-03-19 13:57:43 +0000911std::string ClassLoaderContext::FlattenDexPaths() const {
912 if (class_loader_chain_ == nullptr) {
913 return "";
914 }
915
916 std::vector<std::string> result;
917 std::vector<ClassLoaderInfo*> work_list;
918 work_list.push_back(class_loader_chain_.get());
919 while (!work_list.empty()) {
920 ClassLoaderInfo* info = work_list.back();
921 work_list.pop_back();
922 for (const std::string& dex_path : info->classpath) {
923 result.push_back(dex_path);
924 }
925 AddToWorkList(info, work_list);
926 }
927 return FlattenClasspath(result);
928}
929
Calin Juravle87e2cb62017-06-13 21:48:45 -0700930const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
931 switch (type) {
932 case kPathClassLoader: return kPathClassLoaderString;
933 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
David Brazdil1a9ac532019-03-05 11:57:13 +0000934 case kInMemoryDexClassLoader: return kInMemoryDexClassLoaderString;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700935 default:
936 LOG(FATAL) << "Invalid class loader type " << type;
937 UNREACHABLE();
938 }
939}
940
941void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800942 CHECK_NE(dex_files_state_, kDexFilesNotOpened)
Calin Juravle87e2cb62017-06-13 21:48:45 -0700943 << "Dex files were not successfully opened before the call to " << calling_method
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800944 << "status=" << dex_files_state_;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700945}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700946
Calin Juravle57d0acc2017-07-11 17:41:30 -0700947// Collects the dex files from the give Java dex_file object. Only the dex files with
948// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
949static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
950 ArtField* const cookie_field,
951 std::vector<const DexFile*>* out_dex_files)
952 REQUIRES_SHARED(Locks::mutator_lock_) {
953 if (java_dex_file == nullptr) {
954 return true;
955 }
956 // On the Java side, the dex files are stored in the cookie field.
Vladimir Marko4617d582019-03-28 13:48:31 +0000957 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
Calin Juravle57d0acc2017-07-11 17:41:30 -0700958 if (long_array == nullptr) {
959 // This should never happen so log a warning.
960 LOG(ERROR) << "Unexpected null cookie";
961 return false;
962 }
963 int32_t long_array_size = long_array->GetLength();
964 // Index 0 from the long array stores the oat file. The dex files start at index 1.
965 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +0100966 const DexFile* cp_dex_file =
967 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700968 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
969 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
970 // cp_dex_file can be null.
971 out_dex_files->push_back(cp_dex_file);
972 }
973 }
974 return true;
975}
976
977// Collects all the dex files loaded by the given class loader.
978// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
979// a null list of dex elements or a null dex element).
980static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
981 Handle<mirror::ClassLoader> class_loader,
982 std::vector<const DexFile*>* out_dex_files)
983 REQUIRES_SHARED(Locks::mutator_lock_) {
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800984 CHECK(IsInstanceOfBaseDexClassLoader(soa, class_loader));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700985
986 // All supported class loaders inherit from BaseDexClassLoader.
987 // We need to get the DexPathList and loop through it.
988 ArtField* const cookie_field =
989 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
990 ArtField* const dex_file_field =
991 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
992 ObjPtr<mirror::Object> dex_path_list =
993 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
994 GetObject(class_loader.Get());
995 CHECK(cookie_field != nullptr);
996 CHECK(dex_file_field != nullptr);
997 if (dex_path_list == nullptr) {
998 // This may be null if the current class loader is under construction and it does not
999 // have its fields setup yet.
1000 return true;
1001 }
1002 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1003 ObjPtr<mirror::Object> dex_elements_obj =
1004 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1005 GetObject(dex_path_list);
1006 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1007 // at the mCookie which is a DexFile vector.
1008 if (dex_elements_obj == nullptr) {
1009 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
1010 // and assume we have no elements.
1011 return true;
1012 } else {
1013 StackHandleScope<1> hs(soa.Self());
1014 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
1015 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
Alex Lighta9bbc082019-11-14 14:51:41 -08001016 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001017 if (element == nullptr) {
1018 // Should never happen, log an error and break.
1019 // TODO(calin): It's unclear if we should just assert here.
1020 // This code was propagated to oat_file_manager from the class linker where it would
1021 // throw a NPE. For now, return false which will mark this class loader as unsupported.
1022 LOG(ERROR) << "Unexpected null in the dex element list";
1023 return false;
1024 }
1025 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
1026 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1027 return false;
1028 }
1029 }
1030 }
1031
1032 return true;
1033}
1034
1035static bool GetDexFilesFromDexElementsArray(
1036 ScopedObjectAccessAlreadyRunnable& soa,
1037 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1038 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
1039 DCHECK(dex_elements != nullptr);
1040
1041 ArtField* const cookie_field =
1042 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
1043 ArtField* const dex_file_field =
1044 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Vladimir Marko0984e482019-03-27 16:41:41 +00001045 const ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001046 WellKnownClasses::dalvik_system_DexPathList__Element);
Vladimir Marko0984e482019-03-27 16:41:41 +00001047 const ObjPtr<mirror::Class> dexfile_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001048 WellKnownClasses::dalvik_system_DexFile);
1049
Alex Lighta9bbc082019-11-14 14:51:41 -08001050 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001051 // We can hit a null element here because this is invoked with a partially filled dex_elements
1052 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
1053 // list of dex files which were opened before.
1054 if (element == nullptr) {
1055 continue;
1056 }
1057
1058 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
1059 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
1060 // a historical glitch. All the java code opens dex files using an array of Elements.
1061 ObjPtr<mirror::Object> dex_file;
1062 if (element_class == element->GetClass()) {
1063 dex_file = dex_file_field->GetObject(element);
1064 } else if (dexfile_class == element->GetClass()) {
1065 dex_file = element;
1066 } else {
1067 LOG(ERROR) << "Unsupported element in dex_elements: "
1068 << mirror::Class::PrettyClass(element->GetClass());
1069 return false;
1070 }
1071
1072 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1073 return false;
1074 }
1075 }
1076 return true;
1077}
1078
1079// Adds the `class_loader` info to the `context`.
1080// The dex file present in `dex_elements` array (if not null) will be added at the end of
1081// the classpath.
1082// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
1083// BootClassLoader. Note that the class loader chain is expected to be short.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001084bool ClassLoaderContext::CreateInfoFromClassLoader(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001085 ScopedObjectAccessAlreadyRunnable& soa,
1086 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001087 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1088 ClassLoaderInfo* child_info,
1089 bool is_shared_library)
Calin Juravle57d0acc2017-07-11 17:41:30 -07001090 REQUIRES_SHARED(Locks::mutator_lock_) {
1091 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
1092 // Nothing to do for the boot class loader as we don't add its dex files to the context.
1093 return true;
1094 }
1095
1096 ClassLoaderContext::ClassLoaderType type;
1097 if (IsPathOrDexClassLoader(soa, class_loader)) {
1098 type = kPathClassLoader;
1099 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
1100 type = kDelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +00001101 } else if (IsInMemoryDexClassLoader(soa, class_loader)) {
1102 type = kInMemoryDexClassLoader;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001103 } else {
1104 LOG(WARNING) << "Unsupported class loader";
1105 return false;
1106 }
1107
1108 // Inspect the class loader for its dex files.
1109 std::vector<const DexFile*> dex_files_loaded;
1110 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
1111
1112 // If we have a dex_elements array extract its dex elements now.
1113 // This is used in two situations:
1114 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
1115 // passing the list of already open dex files each time. This ensures that we see the
1116 // correct context even if the ClassLoader under construction is not fully build.
1117 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
1118 // appending them to the current class loader. When the new code paths are loaded in
1119 // BaseDexClassLoader, the paths already present in the class loader will be passed
1120 // in the dex_elements array.
1121 if (dex_elements != nullptr) {
1122 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
1123 }
1124
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001125 ClassLoaderInfo* info = new ClassLoaderContext::ClassLoaderInfo(type);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001126 // Attach the `ClassLoaderInfo` now, before populating dex files, as only the
1127 // `ClassLoaderContext` knows whether these dex files should be deleted or not.
1128 if (child_info == nullptr) {
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001129 class_loader_chain_.reset(info);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001130 } else if (is_shared_library) {
1131 child_info->shared_libraries.push_back(std::unique_ptr<ClassLoaderInfo>(info));
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001132 } else {
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001133 child_info->parent.reset(info);
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001134 }
1135
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001136 // Now that `info` is in the chain, populate dex files.
Calin Juravle57d0acc2017-07-11 17:41:30 -07001137 for (const DexFile* dex_file : dex_files_loaded) {
David Brazdil93d339d2019-03-27 09:56:45 +00001138 // Dex location of dex files loaded with InMemoryDexClassLoader is always bogus.
1139 // Use a magic value for the classpath instead.
1140 info->classpath.push_back((type == kInMemoryDexClassLoader)
1141 ? kInMemoryDexClassLoaderDexLocationMagic
1142 : dex_file->GetLocation());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001143 info->checksums.push_back(dex_file->GetLocationChecksum());
1144 info->opened_dex_files.emplace_back(dex_file);
Calin Juravle57d0acc2017-07-11 17:41:30 -07001145 }
1146
Calin Juravle57d0acc2017-07-11 17:41:30 -07001147 // Note that dex_elements array is null here. The elements are considered to be part of the
1148 // current class loader and are not passed to the parents.
1149 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001150
1151 // Add the shared libraries.
1152 StackHandleScope<3> hs(Thread::Current());
1153 ArtField* field =
1154 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1155 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
1156 if (raw_shared_libraries != nullptr) {
1157 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries =
1158 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>());
1159 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08001160 for (auto library : shared_libraries.Iterate<mirror::ClassLoader>()) {
1161 temp_loader.Assign(library);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001162 if (!CreateInfoFromClassLoader(
1163 soa, temp_loader, null_dex_elements, info, /*is_shared_library=*/ true)) {
1164 return false;
1165 }
1166 }
1167 }
1168
1169 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
1170 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
1171 if (!CreateInfoFromClassLoader(
1172 soa, parent, null_dex_elements, info, /*is_shared_library=*/ false)) {
1173 return false;
1174 }
1175 return true;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001176}
1177
1178std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
1179 jobject class_loader,
1180 jobjectArray dex_elements) {
Calin Juravle98071152021-01-27 18:41:58 -08001181 ScopedTrace trace(__FUNCTION__);
Calin Juravle3f918642017-07-11 19:04:20 -07001182
Calin Juravle98071152021-01-27 18:41:58 -08001183 CHECK(class_loader != nullptr);
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 {
Calin Juravle98071152021-01-27 18:41:58 -08001234 ScopedTrace trace(__FUNCTION__);
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001235 if (verify_names || verify_checksums) {
Calin Juravle6e6f1b22020-12-15 19:13:19 -08001236 DCHECK(dex_files_state_ == kDexFilesChecksumsRead || dex_files_state_ == kDexFilesOpened)
1237 << "dex_files_state_=" << dex_files_state_;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001238 }
Calin Juravlec5b215f2017-09-12 14:49:37 -07001239
Calin Juravle3f918642017-07-11 19:04:20 -07001240 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001241 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -07001242 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -07001243 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001244 }
1245
Calin Juravlec5b215f2017-09-12 14:49:37 -07001246 // Special shared library contexts always match. They essentially instruct the runtime
1247 // to ignore the class path check because the oat file is known to be loaded in different
1248 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
1249 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -07001250 if (expected_context.special_shared_library_) {
1251 // Special case where we are the only entry in the class path.
Nicolas Geoffray9893c472018-11-13 15:39:53 +00001252 if (class_loader_chain_ != nullptr &&
1253 class_loader_chain_->parent == nullptr &&
1254 class_loader_chain_->classpath.size() == 0) {
Mathieu Chartieradc90862018-05-11 13:03:06 -07001255 return VerificationResult::kVerifies;
1256 }
1257 return VerificationResult::kForcedToSkipChecks;
1258 } else if (special_shared_library_) {
1259 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -07001260 }
1261
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001262 ClassLoaderInfo* info = class_loader_chain_.get();
1263 ClassLoaderInfo* expected = expected_context.class_loader_chain_.get();
1264 CHECK(info != nullptr);
1265 CHECK(expected != nullptr);
1266 if (!ClassLoaderInfoMatch(*info, *expected, context_spec, verify_names, verify_checksums)) {
Mathieu Chartieradc90862018-05-11 13:03:06 -07001267 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001268 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001269 return VerificationResult::kVerifies;
1270}
Calin Juravle3f918642017-07-11 19:04:20 -07001271
Vladimir Marko36ec5982019-11-28 10:55:16 +00001272// Returns true if absolute `path` ends with relative `suffix` starting at
1273// a directory name boundary, i.e. after a '/'. For example, "foo/bar"
1274// is a valid suffix of "/data/foo/bar" but not "/data-foo/bar".
1275static inline bool AbsolutePathHasRelativeSuffix(const std::string& path,
1276 const std::string& suffix) {
1277 DCHECK(IsAbsoluteLocation(path));
1278 DCHECK(!IsAbsoluteLocation(suffix));
1279 return (path.size() > suffix.size()) &&
1280 (path[path.size() - suffix.size() - 1u] == '/') &&
1281 (std::string_view(path).substr(/*pos*/ path.size() - suffix.size()) == suffix);
1282}
1283
Calin Juravleb495e7f2020-04-06 19:29:45 -07001284// Returns true if the given dex names are mathing, false otherwise.
1285static bool AreDexNameMatching(const std::string& actual_dex_name,
1286 const std::string& expected_dex_name) {
1287 // Compute the dex location that must be compared.
1288 // We shouldn't do a naive comparison `actual_dex_name == expected_dex_name`
1289 // because even if they refer to the same file, one could be encoded as a relative location
1290 // and the other as an absolute one.
1291 bool is_dex_name_absolute = IsAbsoluteLocation(actual_dex_name);
1292 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_dex_name);
1293 bool dex_names_match = false;
1294
1295 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
1296 // If both locations are absolute or relative then compare them as they are.
1297 // This is usually the case for: shared libraries and secondary dex files.
1298 dex_names_match = (actual_dex_name == expected_dex_name);
1299 } else if (is_dex_name_absolute) {
1300 // The runtime name is absolute but the compiled name (the expected one) is relative.
1301 // This is the case for split apks which depend on base or on other splits.
1302 dex_names_match =
1303 AbsolutePathHasRelativeSuffix(actual_dex_name, expected_dex_name);
1304 } else if (is_expected_dex_name_absolute) {
1305 // The runtime name is relative but the compiled name is absolute.
1306 // There is no expected use case that would end up here as dex files are always loaded
1307 // with their absolute location. However, be tolerant and do the best effort (in case
1308 // there are unexpected new use case...).
1309 dex_names_match =
1310 AbsolutePathHasRelativeSuffix(expected_dex_name, actual_dex_name);
1311 } else {
1312 // Both locations are relative. In this case there's not much we can be sure about
1313 // except that the names are the same. The checksum will ensure that the files are
1314 // are same. This should not happen outside testing and manual invocations.
1315 dex_names_match = (actual_dex_name == expected_dex_name);
1316 }
1317
1318 return dex_names_match;
1319}
1320
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001321bool ClassLoaderContext::ClassLoaderInfoMatch(
1322 const ClassLoaderInfo& info,
1323 const ClassLoaderInfo& expected_info,
1324 const std::string& context_spec,
1325 bool verify_names,
1326 bool verify_checksums) const {
1327 if (info.type != expected_info.type) {
1328 LOG(WARNING) << "ClassLoaderContext type mismatch"
1329 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
1330 << ", found=" << GetClassLoaderTypeName(info.type)
1331 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1332 return false;
1333 }
1334 if (info.classpath.size() != expected_info.classpath.size()) {
1335 LOG(WARNING) << "ClassLoaderContext classpath size mismatch"
1336 << ". expected=" << expected_info.classpath.size()
1337 << ", found=" << info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001338 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001339 return false;
1340 }
Calin Juravle3f918642017-07-11 19:04:20 -07001341
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001342 if (verify_checksums) {
1343 DCHECK_EQ(info.classpath.size(), info.checksums.size());
1344 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
1345 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001346
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001347 if (verify_names) {
Calin Juravle3f918642017-07-11 19:04:20 -07001348 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravleb495e7f2020-04-06 19:29:45 -07001349 bool dex_names_match = AreDexNameMatching(info.classpath[k], expected_info.classpath[k]);
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001350
1351 // Compare the locations.
Vladimir Marko36ec5982019-11-28 10:55:16 +00001352 if (!dex_names_match) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001353 LOG(WARNING) << "ClassLoaderContext classpath element mismatch"
Calin Juravle3f918642017-07-11 19:04:20 -07001354 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001355 << ", found=" << info.classpath[k]
1356 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001357 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001358 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001359
1360 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -07001361 if (info.checksums[k] != expected_info.checksums[k]) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001362 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch"
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001363 << ". expected=" << expected_info.checksums[k]
1364 << ", found=" << info.checksums[k]
1365 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001366 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001367 }
1368 }
1369 }
Calin Juravle3f918642017-07-11 19:04:20 -07001370
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001371 if (info.shared_libraries.size() != expected_info.shared_libraries.size()) {
1372 LOG(WARNING) << "ClassLoaderContext shared library size mismatch. "
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001373 << "Expected=" << expected_info.shared_libraries.size()
1374 << ", found=" << info.shared_libraries.size()
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001375 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1376 return false;
Calin Juravlec79470d2017-07-12 17:37:42 -07001377 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001378 for (size_t i = 0; i < info.shared_libraries.size(); ++i) {
1379 if (!ClassLoaderInfoMatch(*info.shared_libraries[i].get(),
1380 *expected_info.shared_libraries[i].get(),
1381 context_spec,
1382 verify_names,
1383 verify_checksums)) {
1384 return false;
1385 }
1386 }
1387 if (info.parent.get() == nullptr) {
1388 if (expected_info.parent.get() != nullptr) {
1389 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1390 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1391 return false;
1392 }
1393 return true;
1394 } else if (expected_info.parent.get() == nullptr) {
1395 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1396 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1397 return false;
1398 } else {
1399 return ClassLoaderInfoMatch(*info.parent.get(),
1400 *expected_info.parent.get(),
1401 context_spec,
1402 verify_names,
1403 verify_checksums);
1404 }
Calin Juravlec79470d2017-07-12 17:37:42 -07001405}
1406
Calin Juravlea63a2e92020-04-15 20:02:00 -07001407std::set<const DexFile*> ClassLoaderContext::CheckForDuplicateDexFiles(
Calin Juravleb495e7f2020-04-06 19:29:45 -07001408 const std::vector<const DexFile*>& dex_files_to_check) {
Calin Juravle6e6f1b22020-12-15 19:13:19 -08001409 DCHECK_EQ(dex_files_state_, kDexFilesOpened);
Calin Juravleb495e7f2020-04-06 19:29:45 -07001410
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