blob: 2419b7b72016f8ce8f3deb7ee8b364cce6c7ad4f [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 = '#';
Brad Stenning9c924e82021-10-11 19:09:00 -070059static constexpr char kClassLoaderSharedLibraryAfterSeparator = '~';
Calin Juravle7b0648a2017-07-07 18:40:50 -070060static constexpr char kClassLoaderSeparator = ';';
61static constexpr char kClasspathSeparator = ':';
62static constexpr char kDexFileChecksumSeparator = '*';
David Brazdil93d339d2019-03-27 09:56:45 +000063static constexpr char kInMemoryDexClassLoaderDexLocationMagic[] = "<unknown>";
Calin Juravle87e2cb62017-06-13 21:48:45 -070064
65ClassLoaderContext::ClassLoaderContext()
Nicolas Geoffray982eced2021-03-29 08:49:38 +010066 : 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)
Nicolas Geoffray982eced2021-03-29 08:49:38 +010070 : dex_files_state_(ContextDexFilesState::kDexFilesOpened),
Calin Juravle57d0acc2017-07-11 17:41:30 -070071 owns_the_dex_files_(owns_the_dex_files) {}
72
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000073// Utility method to add parent and shared libraries of `info` into
74// the `work_list`.
75static void AddToWorkList(
76 ClassLoaderContext::ClassLoaderInfo* info,
77 std::vector<ClassLoaderContext::ClassLoaderInfo*>& work_list) {
78 if (info->parent != nullptr) {
79 work_list.push_back(info->parent.get());
80 }
81 for (size_t i = 0; i < info->shared_libraries.size(); ++i) {
82 work_list.push_back(info->shared_libraries[i].get());
83 }
Brad Stenning9c924e82021-10-11 19:09:00 -070084 for (size_t i = 0; i < info->shared_libraries_after.size(); ++i) {
85 work_list.push_back(info->shared_libraries_after[i].get());
86 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000087}
88
Calin Juravle57d0acc2017-07-11 17:41:30 -070089ClassLoaderContext::~ClassLoaderContext() {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000090 if (!owns_the_dex_files_ && class_loader_chain_ != nullptr) {
Calin Juravle57d0acc2017-07-11 17:41:30 -070091 // If the context does not own the dex/oat files release the unique pointers to
92 // make sure we do not de-allocate them.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000093 std::vector<ClassLoaderInfo*> work_list;
94 work_list.push_back(class_loader_chain_.get());
95 while (!work_list.empty()) {
96 ClassLoaderInfo* info = work_list.back();
97 work_list.pop_back();
98 for (std::unique_ptr<OatFile>& oat_file : info->opened_oat_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -070099 oat_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -0700100 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000101 for (std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700102 dex_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -0700103 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000104 AddToWorkList(info, work_list);
Calin Juravle57d0acc2017-07-11 17:41:30 -0700105 }
106 }
107}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700108
Calin Juravle19915892017-08-03 17:10:36 +0000109std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
110 return Create("");
111}
112
Calin Juravle87e2cb62017-06-13 21:48:45 -0700113std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
114 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
115 if (result->Parse(spec)) {
116 return result;
117 } else {
118 return nullptr;
119 }
120}
121
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000122static size_t FindMatchingSharedLibraryCloseMarker(const std::string& spec,
123 size_t shared_library_open_index) {
124 // Counter of opened shared library marker we've encountered so far.
125 uint32_t counter = 1;
126 // The index at which we're operating in the loop.
127 uint32_t string_index = shared_library_open_index + 1;
128 size_t shared_library_close = std::string::npos;
129 while (counter != 0) {
130 shared_library_close =
131 spec.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index);
132 size_t shared_library_open =
133 spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, string_index);
134 if (shared_library_close == std::string::npos) {
135 // No matching closing marker. Return an error.
136 break;
137 }
138
139 if ((shared_library_open == std::string::npos) ||
140 (shared_library_close < shared_library_open)) {
141 // We have seen a closing marker. Decrement the counter.
142 --counter;
143 // Move the search index forward.
144 string_index = shared_library_close + 1;
145 } else {
146 // New nested opening marker. Increment the counter and move the search
147 // index after the marker.
148 ++counter;
149 string_index = shared_library_open + 1;
150 }
151 }
152 return shared_library_close;
153}
154
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000155// The expected format is:
156// "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]{ClassLoaderType2[...]}".
Calin Juravle7b0648a2017-07-07 18:40:50 -0700157// The checksum part of the format is expected only if parse_cheksums is true.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000158std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseClassLoaderSpec(
159 const std::string& class_loader_spec,
160 bool parse_checksums) {
161 ClassLoaderType class_loader_type = ExtractClassLoaderType(class_loader_spec);
162 if (class_loader_type == kInvalidClassLoader) {
163 return nullptr;
164 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000165
166 // InMemoryDexClassLoader's dex location is always bogus. Special-case it.
167 if (class_loader_type == kInMemoryDexClassLoader) {
168 if (parse_checksums) {
169 // Make sure that OpenDexFiles() will never be attempted on this context
170 // because the dex locations of IMC do not correspond to real files.
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800171 CHECK(dex_files_state_ == kDexFilesNotOpened || dex_files_state_ == kDexFilesOpenFailed)
172 << "Parsing spec not supported when context created from a ClassLoader object: "
173 << "dex_files_state_=" << dex_files_state_;
174 dex_files_state_ = kDexFilesOpenFailed;
David Brazdil1a9ac532019-03-05 11:57:13 +0000175 } else {
176 // Checksums are not provided and dex locations themselves have no meaning
177 // (although we keep them in the spec to simplify parsing). Treat this as
178 // an unknown class loader.
David Brazdil93d339d2019-03-27 09:56:45 +0000179 // We can hit this case if dex2oat is invoked with a spec containing IMC.
180 // Because the dex file data is only available at runtime, we cannot proceed.
David Brazdil1a9ac532019-03-05 11:57:13 +0000181 return nullptr;
182 }
183 }
184
Calin Juravle87e2cb62017-06-13 21:48:45 -0700185 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
186 size_t type_str_size = strlen(class_loader_type_str);
187
188 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
189
190 // Check the opening and closing markers.
191 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000192 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700193 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000194 if ((class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) &&
195 (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderSharedLibraryClosingMark)) {
196 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700197 }
198
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000199 size_t closing_index = class_loader_spec.find_first_of(kClassLoaderClosingMark);
200
Calin Juravle87e2cb62017-06-13 21:48:45 -0700201 // At this point we know the format is ok; continue and extract the classpath.
202 // Note that class loaders with an empty class path are allowed.
203 std::string classpath = class_loader_spec.substr(type_str_size + 1,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000204 closing_index - type_str_size - 1);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700205
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000206 std::unique_ptr<ClassLoaderInfo> info(new ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700207
208 if (!parse_checksums) {
David Brazdil93d339d2019-03-27 09:56:45 +0000209 DCHECK(class_loader_type != kInMemoryDexClassLoader);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000210 Split(classpath, kClasspathSeparator, &info->classpath);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700211 } else {
212 std::vector<std::string> classpath_elements;
213 Split(classpath, kClasspathSeparator, &classpath_elements);
214 for (const std::string& element : classpath_elements) {
215 std::vector<std::string> dex_file_with_checksum;
216 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
217 if (dex_file_with_checksum.size() != 2) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000218 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700219 }
220 uint32_t checksum = 0;
Tom Cherry7bc8e8f2018-10-05 14:34:13 -0700221 if (!android::base::ParseUint(dex_file_with_checksum[1].c_str(), &checksum)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000222 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700223 }
David Brazdil93d339d2019-03-27 09:56:45 +0000224 if ((class_loader_type == kInMemoryDexClassLoader) &&
225 (dex_file_with_checksum[0] != kInMemoryDexClassLoaderDexLocationMagic)) {
226 return nullptr;
227 }
David Brazdil1a9ac532019-03-05 11:57:13 +0000228
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000229 info->classpath.push_back(dex_file_with_checksum[0]);
230 info->checksums.push_back(checksum);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700231 }
232 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700233
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000234 if ((class_loader_spec[class_loader_spec.length() - 1] == kClassLoaderSharedLibraryClosingMark) &&
235 (class_loader_spec[class_loader_spec.length() - 2] != kClassLoaderSharedLibraryOpeningMark)) {
236 // Non-empty list of shared libraries.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000237 size_t start_index = class_loader_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark);
238 if (start_index == std::string::npos) {
239 return nullptr;
240 }
241 std::string shared_libraries_spec =
242 class_loader_spec.substr(start_index + 1, class_loader_spec.length() - start_index - 2);
243 std::vector<std::string> shared_libraries;
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000244 size_t cursor = 0;
245 while (cursor != shared_libraries_spec.length()) {
Brad Stenning9c924e82021-10-11 19:09:00 -0700246 bool is_after = false;
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000247 size_t shared_library_separator =
248 shared_libraries_spec.find_first_of(kClassLoaderSharedLibrarySeparator, cursor);
249 size_t shared_library_open =
250 shared_libraries_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, cursor);
251 std::string shared_library_spec;
252 if (shared_library_separator == std::string::npos) {
253 // Only one shared library, for example:
254 // PCL[...]
Brad Stenning9c924e82021-10-11 19:09:00 -0700255 if (shared_libraries_spec[cursor] == kClassLoaderSharedLibraryAfterSeparator) {
256 // This library was marked to be loaded after the dex path
257 is_after = true;
258 // Pass the shared library after separator marker.
259 ++cursor;
260 }
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000261 shared_library_spec =
262 shared_libraries_spec.substr(cursor, shared_libraries_spec.length() - cursor);
263 cursor = shared_libraries_spec.length();
264 } else if ((shared_library_open == std::string::npos) ||
265 (shared_library_open > shared_library_separator)) {
266 // We found a shared library without nested shared libraries, for example:
267 // PCL[...]#PCL[...]{...}
Brad Stenning9c924e82021-10-11 19:09:00 -0700268 if (shared_libraries_spec[cursor] == kClassLoaderSharedLibraryAfterSeparator) {
269 // This library was marked to be loaded after the dex path
270 is_after = true;
271 // Pass the shared library after separator marker.
272 ++cursor;
273 }
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000274 shared_library_spec =
275 shared_libraries_spec.substr(cursor, shared_library_separator - cursor);
276 cursor = shared_library_separator + 1;
277 } else {
278 // The shared library contains nested shared libraries. Find the matching closing shared
279 // marker for it.
280 size_t closing_marker =
281 FindMatchingSharedLibraryCloseMarker(shared_libraries_spec, shared_library_open);
282 if (closing_marker == std::string::npos) {
283 // No matching closing marker, return an error.
284 return nullptr;
285 }
Brad Stenning9c924e82021-10-11 19:09:00 -0700286 if (shared_libraries_spec[cursor] == kClassLoaderSharedLibraryAfterSeparator) {
287 // This library was marked to be loaded after the dex path
288 is_after = true;
289 // Pass the shared library after separator marker.
290 ++cursor;
291 }
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000292 shared_library_spec = shared_libraries_spec.substr(cursor, closing_marker + 1 - cursor);
293 cursor = closing_marker + 1;
294 if (cursor != shared_libraries_spec.length() &&
295 shared_libraries_spec[cursor] == kClassLoaderSharedLibrarySeparator) {
296 // Pass the shared library separator marker.
297 ++cursor;
298 }
299 }
Brad Stenning9c924e82021-10-11 19:09:00 -0700300
301 std::unique_ptr<ClassLoaderInfo> shared_library_info(
302 ParseInternal(shared_library_spec, parse_checksums));
303 if (shared_library_info == nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000304 return nullptr;
305 }
Brad Stenning9c924e82021-10-11 19:09:00 -0700306 if (is_after) {
307 info->shared_libraries_after.push_back(std::move(shared_library_info));
308 } else {
309 info->shared_libraries.push_back(std::move(shared_library_info));
310 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000311 }
312 }
313
314 return info;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700315}
316
317// Extracts the class loader type from the given spec.
318// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
319// recognized.
320ClassLoaderContext::ClassLoaderType
321ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
David Brazdil1a9ac532019-03-05 11:57:13 +0000322 const ClassLoaderType kValidTypes[] = { kPathClassLoader,
323 kDelegateLastClassLoader,
324 kInMemoryDexClassLoader };
Calin Juravle87e2cb62017-06-13 21:48:45 -0700325 for (const ClassLoaderType& type : kValidTypes) {
326 const char* type_str = GetClassLoaderTypeName(type);
327 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
328 return type;
329 }
330 }
331 return kInvalidClassLoader;
332}
333
334// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
335// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
336// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700337bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700338 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700339 // By default we load the dex files in a PathClassLoader.
340 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
341 // tests)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000342 class_loader_chain_.reset(new ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700343 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700344 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700345
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000346 CHECK(class_loader_chain_ == nullptr);
347 class_loader_chain_.reset(ParseInternal(spec, parse_checksums));
348 return class_loader_chain_ != nullptr;
349}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700350
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000351ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal(
352 const std::string& spec, bool parse_checksums) {
353 CHECK(!spec.empty());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000354 std::string remaining = spec;
355 std::unique_ptr<ClassLoaderInfo> first(nullptr);
356 ClassLoaderInfo* previous_iteration = nullptr;
357 while (!remaining.empty()) {
358 std::string class_loader_spec;
359 size_t first_class_loader_separator = remaining.find_first_of(kClassLoaderSeparator);
360 size_t first_shared_library_open =
361 remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark);
362 if (first_class_loader_separator == std::string::npos) {
363 // Only one class loader, for example:
364 // PCL[...]
365 class_loader_spec = remaining;
366 remaining = "";
367 } else if ((first_shared_library_open == std::string::npos) ||
368 (first_shared_library_open > first_class_loader_separator)) {
369 // We found a class loader spec without shared libraries, for example:
370 // PCL[...];PCL[...]{...}
371 class_loader_spec = remaining.substr(0, first_class_loader_separator);
372 remaining = remaining.substr(first_class_loader_separator + 1,
373 remaining.size() - first_class_loader_separator - 1);
374 } else {
375 // The class loader spec contains shared libraries. Find the matching closing
376 // shared library marker for it.
377
Yi Kongd5fe17e2019-10-01 16:18:47 -0700378 size_t shared_library_close =
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000379 FindMatchingSharedLibraryCloseMarker(remaining, first_shared_library_open);
380 if (shared_library_close == std::string::npos) {
381 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
382 return nullptr;
383 }
384 class_loader_spec = remaining.substr(0, shared_library_close + 1);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000385
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000386 // Compute the remaining string to analyze.
387 if (remaining.size() == shared_library_close + 1) {
388 remaining = "";
389 } else if ((remaining.size() == shared_library_close + 2) ||
390 (remaining.at(shared_library_close + 1) != kClassLoaderSeparator)) {
391 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
392 return nullptr;
393 } else {
394 remaining = remaining.substr(shared_library_close + 2,
395 remaining.size() - shared_library_close - 2);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000396 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700397 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000398
399 std::unique_ptr<ClassLoaderInfo> info =
400 ParseClassLoaderSpec(class_loader_spec, parse_checksums);
401 if (info == nullptr) {
402 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
403 return nullptr;
404 }
405 if (first == nullptr) {
Andreas Gampe41c911f2018-11-19 11:34:16 -0800406 first = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000407 previous_iteration = first.get();
408 } else {
409 CHECK(previous_iteration != nullptr);
Andreas Gampe41c911f2018-11-19 11:34:16 -0800410 previous_iteration->parent = std::move(info);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000411 previous_iteration = previous_iteration->parent.get();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700412 }
413 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000414 return first.release();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700415}
416
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800417// Opens requested class path files and appends them to opened_dex_files. If the dex files have
418// been stripped, this opens them from their oat files (which get added to opened_oat_files).
Calin Juravle5ff23932020-12-11 18:26:14 -0800419bool ClassLoaderContext::OpenDexFiles(const std::string& classpath_dir,
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800420 const std::vector<int>& fds,
421 bool only_read_checksums) {
422 switch (dex_files_state_) {
423 case kDexFilesNotOpened: break; // files not opened, continue.
424 case kDexFilesOpenFailed: return false; // previous attempt failed.
425 case kDexFilesOpened: return true; // previous attempt succeed.
426 case kDexFilesChecksumsRead:
427 if (only_read_checksums) {
428 return true; // we already read the checksums.
429 } else {
430 break; // we already read the checksums but have to open the dex files; continue.
431 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700432 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700433
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800434 // Assume we can open the files. If not, we will adjust as we go.
435 dex_files_state_ = only_read_checksums ? kDexFilesChecksumsRead : kDexFilesOpened;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700436
Calin Juravle87e2cb62017-06-13 21:48:45 -0700437 // Note that we try to open all dex files even if some fail.
438 // We may get resource-only apks which we cannot load.
439 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
440 // no dex files. So that we can distinguish the real failures...
David Sehr013fd802018-01-11 22:55:24 -0800441 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000442 std::vector<ClassLoaderInfo*> work_list;
Nicolas Geoffray525fa422021-04-19 07:50:35 +0000443 if (class_loader_chain_ == nullptr) {
444 return true;
445 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000446 work_list.push_back(class_loader_chain_.get());
David Brazdil89821862019-03-19 13:57:43 +0000447 size_t dex_file_index = 0;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000448 while (!work_list.empty()) {
449 ClassLoaderInfo* info = work_list.back();
450 work_list.pop_back();
David Brazdil93d339d2019-03-27 09:56:45 +0000451 DCHECK(info->type != kInMemoryDexClassLoader) << __FUNCTION__ << " not supported for IMC";
452
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800453 // Holds the dex locations for the classpath files we've opened.
454 std::vector<std::string> dex_locations;
455 // Holds the checksums for the classpath files we've opened.
456 std::vector<uint32_t> dex_checksums;
457
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000458 for (const std::string& cp_elem : info->classpath) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700459 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000460 std::string location = cp_elem;
461 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000462 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700463 }
464
David Brazdil89821862019-03-19 13:57:43 +0000465 // If file descriptors were provided for the class loader context dex paths,
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800466 // get the descriptor which corresponds to this dex path. We assume the `fds`
David Brazdil89821862019-03-19 13:57:43 +0000467 // vector follows the same order as a flattened class loader context.
468 int fd = -1;
469 if (!fds.empty()) {
470 if (dex_file_index >= fds.size()) {
471 LOG(WARNING) << "Number of FDs is smaller than number of dex files in the context";
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800472 dex_files_state_ = kDexFilesOpenFailed;
David Brazdil89821862019-03-19 13:57:43 +0000473 return false;
474 }
475
476 fd = fds[dex_file_index++];
477 DCHECK_GE(fd, 0);
478 }
479
Calin Juravle87e2cb62017-06-13 21:48:45 -0700480 std::string error_msg;
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800481 if (only_read_checksums) {
482 bool zip_file_only_contains_uncompress_dex;
483 if (!dex_file_loader.GetMultiDexChecksums(location.c_str(),
484 &dex_checksums,
485 &dex_locations,
486 &error_msg,
487 fd,
488 &zip_file_only_contains_uncompress_dex)) {
489 LOG(WARNING) << "Could not get dex checksums for location " << location << ", fd=" << fd;
490 dex_files_state_ = kDexFilesOpenFailed;
491 }
492 } else {
493 // When opening the dex files from the context we expect their checksum to match their
494 // contents. So pass true to verify_checksum.
495 // We don't need to do structural dex file verification, we only need to
496 // check the checksum, so pass false to verify.
497 size_t opened_dex_files_index = info->opened_dex_files.size();
498 if (!dex_file_loader.Open(location.c_str(),
499 fd,
500 location.c_str(),
501 /*verify=*/ false,
502 /*verify_checksum=*/ true,
503 &error_msg,
504 &info->opened_dex_files)) {
505 LOG(WARNING) << "Could not open dex files for location " << location << ", fd=" << fd;
506 dex_files_state_ = kDexFilesOpenFailed;
507 } else {
508 for (size_t k = opened_dex_files_index; k < info->opened_dex_files.size(); k++) {
509 std::unique_ptr<const DexFile>& dex = info->opened_dex_files[k];
510 dex_locations.push_back(dex->GetLocation());
511 dex_checksums.push_back(dex->GetLocationChecksum());
512 }
513 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700514 }
515 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700516
517 // We finished opening the dex files from the classpath.
518 // Now update the classpath and the checksum with the locations of the dex files.
519 //
520 // We do this because initially the classpath contains the paths of the dex files; and
521 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
522 // file paths with the actual dex locations being loaded.
523 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
524 // location in the class paths.
525 // Note that this will also remove the paths that could not be opened.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000526 info->original_classpath = std::move(info->classpath);
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800527 DCHECK(dex_locations.size() == dex_checksums.size());
528 info->classpath = dex_locations;
529 info->checksums = dex_checksums;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000530 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700531 }
532
David Brazdil89821862019-03-19 13:57:43 +0000533 // Check that if file descriptors were provided, there were exactly as many
534 // as we have encountered while iterating over this class loader context.
535 if (dex_file_index != fds.size()) {
536 LOG(WARNING) << fds.size() << " FDs provided but only " << dex_file_index
537 << " dex files are in the class loader context";
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800538 dex_files_state_ = kDexFilesOpenFailed;
David Brazdil89821862019-03-19 13:57:43 +0000539 }
540
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800541 return dex_files_state_ != kDexFilesOpenFailed;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700542}
543
544bool ClassLoaderContext::RemoveLocationsFromClassPaths(
545 const dchecked_vector<std::string>& locations) {
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800546 CHECK_EQ(dex_files_state_, kDexFilesNotOpened)
Calin Juravle87e2cb62017-06-13 21:48:45 -0700547 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
548
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000549 if (class_loader_chain_ == nullptr) {
550 return false;
551 }
552
Calin Juravle87e2cb62017-06-13 21:48:45 -0700553 std::set<std::string> canonical_locations;
554 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700555 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700556 }
557 bool removed_locations = false;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000558 std::vector<ClassLoaderInfo*> work_list;
559 work_list.push_back(class_loader_chain_.get());
560 while (!work_list.empty()) {
561 ClassLoaderInfo* info = work_list.back();
562 work_list.pop_back();
563 size_t initial_size = info->classpath.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700564 auto kept_it = std::remove_if(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000565 info->classpath.begin(),
566 info->classpath.end(),
Calin Juravle87e2cb62017-06-13 21:48:45 -0700567 [canonical_locations](const std::string& location) {
568 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700569 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700570 });
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000571 info->classpath.erase(kept_it, info->classpath.end());
572 if (initial_size != info->classpath.size()) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700573 removed_locations = true;
574 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000575 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700576 }
577 return removed_locations;
578}
579
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700580std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700581 return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700582}
583
Mathieu Chartierc4440772018-04-16 14:40:56 -0700584std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
585 ClassLoaderContext* stored_context) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700586 return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700587}
588
Dan Zimmermanb682ea42019-12-23 06:59:06 -0800589std::map<std::string, std::string>
590ClassLoaderContext::EncodeClassPathContexts(const std::string& base_dir) const {
591 CheckDexFilesOpened("EncodeClassPathContexts");
592 if (class_loader_chain_ == nullptr) {
593 return std::map<std::string, std::string>{};
594 }
595
596 std::map<std::string, std::string> results;
597 std::vector<std::string> dex_locations;
598 std::vector<uint32_t> checksums;
599 dex_locations.reserve(class_loader_chain_->original_classpath.size());
600
601 std::ostringstream encoded_libs_and_parent_stream;
602 EncodeSharedLibAndParent(*class_loader_chain_,
603 base_dir,
604 /*for_dex2oat=*/true,
605 /*stored_info=*/nullptr,
606 encoded_libs_and_parent_stream);
607 std::string encoded_libs_and_parent(encoded_libs_and_parent_stream.str());
608
609 std::set<std::string> seen_locations;
610 for (const std::string& path : class_loader_chain_->classpath) {
611 // The classpath will contain multiple entries for multidex files, so make sure this is the
612 // first time we're seeing this file.
613 const std::string base_location(DexFileLoader::GetBaseLocation(path));
614 if (!seen_locations.insert(base_location).second) {
615 continue;
616 }
617
618 std::ostringstream out;
619 EncodeClassPath(base_dir, dex_locations, checksums, class_loader_chain_->type, out);
620 out << encoded_libs_and_parent;
621 results.emplace(base_location, out.str());
622
623 dex_locations.push_back(base_location);
624 }
625
626 return results;
627}
628
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700629std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700630 bool for_dex2oat,
631 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700632 CheckDexFilesOpened("EncodeContextForOatFile");
Calin Juravle87e2cb62017-06-13 21:48:45 -0700633
Mathieu Chartierc4440772018-04-16 14:40:56 -0700634 if (stored_context != nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000635 DCHECK_EQ(GetParentChainSize(), stored_context->GetParentChainSize());
Mathieu Chartierc4440772018-04-16 14:40:56 -0700636 }
637
Calin Juravle7b0648a2017-07-07 18:40:50 -0700638 std::ostringstream out;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000639 if (class_loader_chain_ == nullptr) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700640 // We can get in this situation if the context was created with a class path containing the
641 // source dex files which were later removed (happens during run-tests).
642 out << GetClassLoaderTypeName(kPathClassLoader)
643 << kClassLoaderOpeningMark
644 << kClassLoaderClosingMark;
645 return out.str();
646 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700647
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000648 EncodeContextInternal(
649 *class_loader_chain_,
650 base_dir,
651 for_dex2oat,
652 (stored_context == nullptr ? nullptr : stored_context->class_loader_chain_.get()),
653 out);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700654 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700655}
656
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800657void ClassLoaderContext::EncodeClassPath(const std::string& base_dir,
658 const std::vector<std::string>& dex_locations,
659 const std::vector<uint32_t>& checksums,
660 ClassLoaderType type,
661 std::ostringstream& out) const {
662 CHECK(checksums.empty() || dex_locations.size() == checksums.size());
663 out << GetClassLoaderTypeName(type);
664 out << kClassLoaderOpeningMark;
665 const size_t len = dex_locations.size();
666 for (size_t k = 0; k < len; k++) {
Vladimir Marko1be1c072022-02-23 12:30:39 +0000667 const std::string& location = dex_locations[k];
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800668 if (k > 0) {
669 out << kClasspathSeparator;
670 }
671 if (type == kInMemoryDexClassLoader) {
672 out << kInMemoryDexClassLoaderDexLocationMagic;
673 } else if (!base_dir.empty()
674 && location.substr(0, base_dir.length()) == base_dir) {
675 // Find paths that were relative and convert them back from absolute.
676 out << location.substr(base_dir.length() + 1).c_str();
677 } else {
678 out << location.c_str();
679 }
680 if (!checksums.empty()) {
681 out << kDexFileChecksumSeparator;
682 out << checksums[k];
683 }
684 }
685 out << kClassLoaderClosingMark;
686}
687
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000688void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info,
689 const std::string& base_dir,
690 bool for_dex2oat,
691 ClassLoaderInfo* stored_info,
692 std::ostringstream& out) const {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800693 std::vector<std::string> locations;
694 std::vector<uint32_t> checksums;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000695 std::set<std::string> seen_locations;
696 SafeMap<std::string, std::string> remap;
697 if (stored_info != nullptr) {
698 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
699 // Note that we don't care if the same name appears twice.
700 remap.Put(info.original_classpath[k], stored_info->classpath[k]);
701 }
702 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800703
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000704 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
705 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
706 if (for_dex2oat) {
707 // dex2oat only needs the base location. It cannot accept multidex locations.
708 // So ensure we only add each file once.
709 bool new_insert = seen_locations.insert(
710 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
711 if (!new_insert) {
712 continue;
713 }
714 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800715
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000716 std::string location = dex_file->GetLocation();
717 // If there is a stored class loader remap, fix up the multidex strings.
718 if (!remap.empty()) {
719 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
720 auto it = remap.find(base_dex_location);
721 CHECK(it != remap.end()) << base_dex_location;
722 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
723 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800724 locations.emplace_back(std::move(location));
725
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000726 // dex2oat does not need the checksums.
727 if (!for_dex2oat) {
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800728 checksums.push_back(dex_file->GetLocationChecksum());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000729 }
730 }
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800731 EncodeClassPath(base_dir, locations, checksums, info.type, out);
732 EncodeSharedLibAndParent(info, base_dir, for_dex2oat, stored_info, out);
733}
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000734
Dan Zimmerman7d511d92019-12-23 07:00:51 -0800735void ClassLoaderContext::EncodeSharedLibAndParent(const ClassLoaderInfo& info,
736 const std::string& base_dir,
737 bool for_dex2oat,
738 ClassLoaderInfo* stored_info,
739 std::ostringstream& out) const {
Brad Stenning9c924e82021-10-11 19:09:00 -0700740 if (!info.shared_libraries.empty() || !info.shared_libraries_after.empty()) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000741 out << kClassLoaderSharedLibraryOpeningMark;
742 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
743 if (i > 0) {
744 out << kClassLoaderSharedLibrarySeparator;
745 }
746 EncodeContextInternal(
747 *info.shared_libraries[i].get(),
748 base_dir,
749 for_dex2oat,
750 (stored_info == nullptr ? nullptr : stored_info->shared_libraries[i].get()),
751 out);
752 }
Brad Stenning9c924e82021-10-11 19:09:00 -0700753
754 for (uint32_t i = 0; i < info.shared_libraries_after.size(); ++i) {
755 if (i > 0 || !info.shared_libraries.empty()) {
756 out << kClassLoaderSharedLibrarySeparator;
757 }
758 out << kClassLoaderSharedLibraryAfterSeparator;
759 EncodeContextInternal(
760 *info.shared_libraries_after[i].get(),
761 base_dir,
762 for_dex2oat,
763 (stored_info == nullptr ? nullptr : stored_info->shared_libraries_after[i].get()),
764 out);
765 }
766
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000767 out << kClassLoaderSharedLibraryClosingMark;
768 }
769 if (info.parent != nullptr) {
770 out << kClassLoaderSeparator;
771 EncodeContextInternal(
772 *info.parent.get(),
773 base_dir,
774 for_dex2oat,
775 (stored_info == nullptr ? nullptr : stored_info->parent.get()),
776 out);
777 }
778}
779
780// Returns the WellKnownClass for the given class loader type.
781static jclass GetClassLoaderClass(ClassLoaderContext::ClassLoaderType type) {
782 switch (type) {
783 case ClassLoaderContext::kPathClassLoader:
784 return WellKnownClasses::dalvik_system_PathClassLoader;
785 case ClassLoaderContext::kDelegateLastClassLoader:
786 return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +0000787 case ClassLoaderContext::kInMemoryDexClassLoader:
788 return WellKnownClasses::dalvik_system_InMemoryDexClassLoader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000789 case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch.
790 }
791 LOG(FATAL) << "Invalid class loader type " << type;
792 UNREACHABLE();
793}
794
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000795static std::string FlattenClasspath(const std::vector<std::string>& classpath) {
796 return android::base::Join(classpath, ':');
797}
798
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000799static ObjPtr<mirror::ClassLoader> CreateClassLoaderInternal(
800 Thread* self,
801 ScopedObjectAccess& soa,
802 const ClassLoaderContext::ClassLoaderInfo& info,
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000803 bool for_shared_library,
804 VariableSizedHandleScope& map_scope,
805 std::map<std::string, Handle<mirror::ClassLoader>>& canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000806 bool add_compilation_sources,
807 const std::vector<const DexFile*>& compilation_sources)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000808 REQUIRES_SHARED(Locks::mutator_lock_) {
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000809 if (for_shared_library) {
810 // Check if the shared library has already been created.
811 auto search = canonicalized_libraries.find(FlattenClasspath(info.classpath));
812 if (search != canonicalized_libraries.end()) {
813 return search->second.Get();
814 }
815 }
816
Brad Stenning9c924e82021-10-11 19:09:00 -0700817 StackHandleScope<4> hs(self);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000818 MutableHandle<mirror::ObjectArray<mirror::ClassLoader>> libraries(
819 hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr));
Brad Stenning9c924e82021-10-11 19:09:00 -0700820 MutableHandle<mirror::ObjectArray<mirror::ClassLoader>> libraries_after(
821 hs.NewHandle<mirror::ObjectArray<mirror::ClassLoader>>(nullptr));
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000822
823 if (!info.shared_libraries.empty()) {
824 libraries.Assign(mirror::ObjectArray<mirror::ClassLoader>::Alloc(
825 self,
826 GetClassRoot<mirror::ObjectArray<mirror::ClassLoader>>(),
827 info.shared_libraries.size()));
828 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
829 // We should only add the compilation sources to the first class loader.
830 libraries->Set(i,
831 CreateClassLoaderInternal(
832 self,
833 soa,
834 *info.shared_libraries[i].get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000835 /* for_shared_library= */ true,
836 map_scope,
837 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000838 /* add_compilation_sources= */ false,
839 compilation_sources));
840 }
841 }
842
Brad Stenning9c924e82021-10-11 19:09:00 -0700843 if (!info.shared_libraries_after.empty()) {
844 libraries_after.Assign(mirror::ObjectArray<mirror::ClassLoader>::Alloc(
845 self,
846 GetClassRoot<mirror::ObjectArray<mirror::ClassLoader>>(),
847 info.shared_libraries_after.size()));
848 for (uint32_t i = 0; i < info.shared_libraries_after.size(); ++i) {
849 // We should only add the compilation sources to the first class loader.
850 libraries_after->Set(i,
851 CreateClassLoaderInternal(
852 self,
853 soa,
854 *info.shared_libraries_after[i].get(),
855 /* for_shared_library= */ true,
856 map_scope,
857 canonicalized_libraries,
858 /* add_compilation_sources= */ false,
859 compilation_sources));
860 }
861 }
862
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000863 MutableHandle<mirror::ClassLoader> parent = hs.NewHandle<mirror::ClassLoader>(nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000864 if (info.parent != nullptr) {
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000865 // We should only add the compilation sources to the first class loader.
866 parent.Assign(CreateClassLoaderInternal(
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000867 self,
868 soa,
869 *info.parent.get(),
870 /* for_shared_library= */ false,
871 map_scope,
872 canonicalized_libraries,
873 /* add_compilation_sources= */ false,
874 compilation_sources));
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000875 }
876 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
877 info.opened_dex_files);
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000878 if (add_compilation_sources) {
879 // For the first class loader, its classpath comes first, followed by compilation sources.
880 // This ensures that whenever we need to resolve classes from it the classpath elements
881 // come first.
882 class_path_files.insert(class_path_files.end(),
883 compilation_sources.begin(),
884 compilation_sources.end());
885 }
886 Handle<mirror::Class> loader_class = hs.NewHandle<mirror::Class>(
887 soa.Decode<mirror::Class>(GetClassLoaderClass(info.type)));
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000888 ObjPtr<mirror::ClassLoader> loader =
889 Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
890 self,
891 class_path_files,
892 loader_class,
Nicolas Geoffraye1672732018-11-30 01:09:49 +0000893 parent,
Brad Stenning9c924e82021-10-11 19:09:00 -0700894 libraries,
895 libraries_after);
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000896 if (for_shared_library) {
897 canonicalized_libraries[FlattenClasspath(info.classpath)] =
898 map_scope.NewHandle<mirror::ClassLoader>(loader);
899 }
900 return loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000901}
902
Calin Juravle87e2cb62017-06-13 21:48:45 -0700903jobject ClassLoaderContext::CreateClassLoader(
904 const std::vector<const DexFile*>& compilation_sources) const {
905 CheckDexFilesOpened("CreateClassLoader");
906
907 Thread* self = Thread::Current();
908 ScopedObjectAccess soa(self);
909
Nicolas Geoffray982eced2021-03-29 08:49:38 +0100910 CHECK(class_loader_chain_ != nullptr);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700911
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000912 // Create a map of canonicalized shared libraries. As we're holding objects,
913 // we're creating a variable size handle scope to put handles in the map.
914 VariableSizedHandleScope map_scope(self);
915 std::map<std::string, Handle<mirror::ClassLoader>> canonicalized_libraries;
916
917 // Create the class loader.
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000918 ObjPtr<mirror::ClassLoader> loader =
919 CreateClassLoaderInternal(self,
920 soa,
921 *class_loader_chain_.get(),
Nicolas Geoffraycb2e1dd2018-11-20 11:15:13 +0000922 /* for_shared_library= */ false,
923 map_scope,
924 canonicalized_libraries,
Nicolas Geoffray6b9fd8c2018-11-16 10:25:42 +0000925 /* add_compilation_sources= */ true,
926 compilation_sources);
927 // Make it a global ref and return.
928 ScopedLocalRef<jobject> local_ref(
929 soa.Env(), soa.Env()->AddLocalReference<jobject>(loader));
930 return soa.Env()->NewGlobalRef(local_ref.get());
Calin Juravle87e2cb62017-06-13 21:48:45 -0700931}
932
933std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
934 CheckDexFilesOpened("FlattenOpenedDexFiles");
935
936 std::vector<const DexFile*> result;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000937 if (class_loader_chain_ == nullptr) {
938 return result;
939 }
940 std::vector<ClassLoaderInfo*> work_list;
941 work_list.push_back(class_loader_chain_.get());
942 while (!work_list.empty()) {
943 ClassLoaderInfo* info = work_list.back();
944 work_list.pop_back();
945 for (const std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700946 result.push_back(dex_file.get());
947 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000948 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700949 }
950 return result;
951}
952
David Brazdil89821862019-03-19 13:57:43 +0000953std::string ClassLoaderContext::FlattenDexPaths() const {
954 if (class_loader_chain_ == nullptr) {
955 return "";
956 }
957
958 std::vector<std::string> result;
959 std::vector<ClassLoaderInfo*> work_list;
960 work_list.push_back(class_loader_chain_.get());
961 while (!work_list.empty()) {
962 ClassLoaderInfo* info = work_list.back();
963 work_list.pop_back();
964 for (const std::string& dex_path : info->classpath) {
965 result.push_back(dex_path);
966 }
967 AddToWorkList(info, work_list);
968 }
969 return FlattenClasspath(result);
970}
971
Calin Juravle87e2cb62017-06-13 21:48:45 -0700972const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
973 switch (type) {
974 case kPathClassLoader: return kPathClassLoaderString;
975 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
David Brazdil1a9ac532019-03-05 11:57:13 +0000976 case kInMemoryDexClassLoader: return kInMemoryDexClassLoaderString;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700977 default:
978 LOG(FATAL) << "Invalid class loader type " << type;
979 UNREACHABLE();
980 }
981}
982
983void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800984 CHECK_NE(dex_files_state_, kDexFilesNotOpened)
Calin Juravle87e2cb62017-06-13 21:48:45 -0700985 << "Dex files were not successfully opened before the call to " << calling_method
Calin Juravle6e6f1b22020-12-15 19:13:19 -0800986 << "status=" << dex_files_state_;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700987}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700988
Calin Juravle57d0acc2017-07-11 17:41:30 -0700989// Collects the dex files from the give Java dex_file object. Only the dex files with
990// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
991static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
992 ArtField* const cookie_field,
993 std::vector<const DexFile*>* out_dex_files)
994 REQUIRES_SHARED(Locks::mutator_lock_) {
995 if (java_dex_file == nullptr) {
996 return true;
997 }
998 // On the Java side, the dex files are stored in the cookie field.
Vladimir Marko4617d582019-03-28 13:48:31 +0000999 ObjPtr<mirror::LongArray> long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
Calin Juravle57d0acc2017-07-11 17:41:30 -07001000 if (long_array == nullptr) {
1001 // This should never happen so log a warning.
1002 LOG(ERROR) << "Unexpected null cookie";
1003 return false;
1004 }
1005 int32_t long_array_size = long_array->GetLength();
1006 // Index 0 from the long array stores the oat file. The dex files start at index 1.
1007 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +01001008 const DexFile* cp_dex_file =
1009 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -07001010 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
1011 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
1012 // cp_dex_file can be null.
1013 out_dex_files->push_back(cp_dex_file);
1014 }
1015 }
1016 return true;
1017}
1018
1019// Collects all the dex files loaded by the given class loader.
1020// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
1021// a null list of dex elements or a null dex element).
1022static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
1023 Handle<mirror::ClassLoader> class_loader,
1024 std::vector<const DexFile*>* out_dex_files)
1025 REQUIRES_SHARED(Locks::mutator_lock_) {
Dan Zimmermanb682ea42019-12-23 06:59:06 -08001026 CHECK(IsInstanceOfBaseDexClassLoader(soa, class_loader));
Calin Juravle57d0acc2017-07-11 17:41:30 -07001027
1028 // All supported class loaders inherit from BaseDexClassLoader.
1029 // We need to get the DexPathList and loop through it.
1030 ArtField* const cookie_field =
1031 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
1032 ArtField* const dex_file_field =
1033 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
1034 ObjPtr<mirror::Object> dex_path_list =
1035 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
1036 GetObject(class_loader.Get());
1037 CHECK(cookie_field != nullptr);
1038 CHECK(dex_file_field != nullptr);
1039 if (dex_path_list == nullptr) {
1040 // This may be null if the current class loader is under construction and it does not
1041 // have its fields setup yet.
1042 return true;
1043 }
1044 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
1045 ObjPtr<mirror::Object> dex_elements_obj =
1046 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
1047 GetObject(dex_path_list);
1048 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
1049 // at the mCookie which is a DexFile vector.
1050 if (dex_elements_obj == nullptr) {
1051 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
1052 // and assume we have no elements.
1053 return true;
1054 } else {
1055 StackHandleScope<1> hs(soa.Self());
1056 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
1057 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
Alex Lighta9bbc082019-11-14 14:51:41 -08001058 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001059 if (element == nullptr) {
1060 // Should never happen, log an error and break.
1061 // TODO(calin): It's unclear if we should just assert here.
1062 // This code was propagated to oat_file_manager from the class linker where it would
1063 // throw a NPE. For now, return false which will mark this class loader as unsupported.
1064 LOG(ERROR) << "Unexpected null in the dex element list";
1065 return false;
1066 }
1067 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
1068 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1069 return false;
1070 }
1071 }
1072 }
1073
1074 return true;
1075}
1076
1077static bool GetDexFilesFromDexElementsArray(
1078 ScopedObjectAccessAlreadyRunnable& soa,
1079 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1080 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
1081 DCHECK(dex_elements != nullptr);
1082
1083 ArtField* const cookie_field =
1084 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
1085 ArtField* const dex_file_field =
1086 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Vladimir Marko0984e482019-03-27 16:41:41 +00001087 const ObjPtr<mirror::Class> element_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001088 WellKnownClasses::dalvik_system_DexPathList__Element);
Vladimir Marko0984e482019-03-27 16:41:41 +00001089 const ObjPtr<mirror::Class> dexfile_class = soa.Decode<mirror::Class>(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001090 WellKnownClasses::dalvik_system_DexFile);
1091
Alex Lighta9bbc082019-11-14 14:51:41 -08001092 for (auto element : dex_elements.Iterate<mirror::Object>()) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001093 // We can hit a null element here because this is invoked with a partially filled dex_elements
1094 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
1095 // list of dex files which were opened before.
1096 if (element == nullptr) {
1097 continue;
1098 }
1099
1100 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
1101 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
1102 // a historical glitch. All the java code opens dex files using an array of Elements.
1103 ObjPtr<mirror::Object> dex_file;
1104 if (element_class == element->GetClass()) {
1105 dex_file = dex_file_field->GetObject(element);
1106 } else if (dexfile_class == element->GetClass()) {
1107 dex_file = element;
1108 } else {
1109 LOG(ERROR) << "Unsupported element in dex_elements: "
1110 << mirror::Class::PrettyClass(element->GetClass());
1111 return false;
1112 }
1113
1114 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
1115 return false;
1116 }
1117 }
1118 return true;
1119}
1120
1121// Adds the `class_loader` info to the `context`.
1122// The dex file present in `dex_elements` array (if not null) will be added at the end of
1123// the classpath.
1124// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
1125// BootClassLoader. Note that the class loader chain is expected to be short.
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001126bool ClassLoaderContext::CreateInfoFromClassLoader(
Calin Juravle57d0acc2017-07-11 17:41:30 -07001127 ScopedObjectAccessAlreadyRunnable& soa,
1128 Handle<mirror::ClassLoader> class_loader,
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001129 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
1130 ClassLoaderInfo* child_info,
Brad Stenning9c924e82021-10-11 19:09:00 -07001131 bool is_shared_library,
1132 bool is_after)
Calin Juravle57d0acc2017-07-11 17:41:30 -07001133 REQUIRES_SHARED(Locks::mutator_lock_) {
1134 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
1135 // Nothing to do for the boot class loader as we don't add its dex files to the context.
1136 return true;
1137 }
1138
1139 ClassLoaderContext::ClassLoaderType type;
1140 if (IsPathOrDexClassLoader(soa, class_loader)) {
1141 type = kPathClassLoader;
1142 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
1143 type = kDelegateLastClassLoader;
David Brazdil1a9ac532019-03-05 11:57:13 +00001144 } else if (IsInMemoryDexClassLoader(soa, class_loader)) {
1145 type = kInMemoryDexClassLoader;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001146 } else {
1147 LOG(WARNING) << "Unsupported class loader";
1148 return false;
1149 }
1150
1151 // Inspect the class loader for its dex files.
1152 std::vector<const DexFile*> dex_files_loaded;
1153 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
1154
1155 // If we have a dex_elements array extract its dex elements now.
1156 // This is used in two situations:
1157 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
1158 // passing the list of already open dex files each time. This ensures that we see the
1159 // correct context even if the ClassLoader under construction is not fully build.
1160 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
1161 // appending them to the current class loader. When the new code paths are loaded in
1162 // BaseDexClassLoader, the paths already present in the class loader will be passed
1163 // in the dex_elements array.
1164 if (dex_elements != nullptr) {
1165 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
1166 }
1167
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001168 ClassLoaderInfo* info = new ClassLoaderContext::ClassLoaderInfo(type);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001169 // Attach the `ClassLoaderInfo` now, before populating dex files, as only the
1170 // `ClassLoaderContext` knows whether these dex files should be deleted or not.
1171 if (child_info == nullptr) {
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001172 class_loader_chain_.reset(info);
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001173 } else if (is_shared_library) {
Brad Stenning9c924e82021-10-11 19:09:00 -07001174 if (is_after) {
1175 child_info->shared_libraries_after.push_back(std::unique_ptr<ClassLoaderInfo>(info));
1176 } else {
1177 child_info->shared_libraries.push_back(std::unique_ptr<ClassLoaderInfo>(info));
1178 }
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001179 } else {
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001180 child_info->parent.reset(info);
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001181 }
1182
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001183 // Now that `info` is in the chain, populate dex files.
Calin Juravle57d0acc2017-07-11 17:41:30 -07001184 for (const DexFile* dex_file : dex_files_loaded) {
David Brazdil93d339d2019-03-27 09:56:45 +00001185 // Dex location of dex files loaded with InMemoryDexClassLoader is always bogus.
1186 // Use a magic value for the classpath instead.
1187 info->classpath.push_back((type == kInMemoryDexClassLoader)
1188 ? kInMemoryDexClassLoaderDexLocationMagic
1189 : dex_file->GetLocation());
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001190 info->checksums.push_back(dex_file->GetLocationChecksum());
1191 info->opened_dex_files.emplace_back(dex_file);
Calin Juravle57d0acc2017-07-11 17:41:30 -07001192 }
1193
Calin Juravle57d0acc2017-07-11 17:41:30 -07001194 // Note that dex_elements array is null here. The elements are considered to be part of the
1195 // current class loader and are not passed to the parents.
1196 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001197
1198 // Add the shared libraries.
Brad Stenning9c924e82021-10-11 19:09:00 -07001199 StackHandleScope<5> hs(Thread::Current());
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001200 ArtField* field =
1201 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoaders);
1202 ObjPtr<mirror::Object> raw_shared_libraries = field->GetObject(class_loader.Get());
1203 if (raw_shared_libraries != nullptr) {
1204 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries =
1205 hs.NewHandle(raw_shared_libraries->AsObjectArray<mirror::ClassLoader>());
1206 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
Alex Lighta9bbc082019-11-14 14:51:41 -08001207 for (auto library : shared_libraries.Iterate<mirror::ClassLoader>()) {
1208 temp_loader.Assign(library);
Brad Stenning9c924e82021-10-11 19:09:00 -07001209 if (!CreateInfoFromClassLoader(soa,
1210 temp_loader,
1211 null_dex_elements,
1212 info,
1213 /*is_shared_library=*/ true,
1214 /*is_after=*/ false)) {
1215 return false;
1216 }
1217 }
1218 }
1219 ArtField* field2 = jni::DecodeArtField(
1220 WellKnownClasses::dalvik_system_BaseDexClassLoader_sharedLibraryLoadersAfter);
1221 ObjPtr<mirror::Object> raw_shared_libraries_after = field2->GetObject(class_loader.Get());
1222 if (raw_shared_libraries_after != nullptr) {
1223 Handle<mirror::ObjectArray<mirror::ClassLoader>> shared_libraries_after =
1224 hs.NewHandle(raw_shared_libraries_after->AsObjectArray<mirror::ClassLoader>());
1225 MutableHandle<mirror::ClassLoader> temp_loader = hs.NewHandle<mirror::ClassLoader>(nullptr);
1226 for (auto library : shared_libraries_after.Iterate<mirror::ClassLoader>()) {
1227 temp_loader.Assign(library);
1228 if (!CreateInfoFromClassLoader(soa,
1229 temp_loader,
1230 null_dex_elements,
1231 info,
1232 /*is_shared_library=*/ true,
1233 /*is_after=*/ true)) {
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001234 return false;
1235 }
1236 }
1237 }
1238
1239 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
1240 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
Brad Stenning9c924e82021-10-11 19:09:00 -07001241 if (!CreateInfoFromClassLoader(soa,
1242 parent,
1243 null_dex_elements,
1244 info,
1245 /*is_shared_library=*/ false,
1246 /*is_after=*/ false)) {
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001247 return false;
1248 }
1249 return true;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001250}
1251
1252std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
1253 jobject class_loader,
1254 jobjectArray dex_elements) {
Calin Juravle98071152021-01-27 18:41:58 -08001255 ScopedTrace trace(__FUNCTION__);
Calin Juravle3f918642017-07-11 19:04:20 -07001256
Nicolas Geoffray525fa422021-04-19 07:50:35 +00001257 if (class_loader == nullptr) {
1258 return nullptr;
1259 }
Calin Juravle57d0acc2017-07-11 17:41:30 -07001260 ScopedObjectAccess soa(Thread::Current());
1261 StackHandleScope<2> hs(soa.Self());
1262 Handle<mirror::ClassLoader> h_class_loader =
1263 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1264 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
1265 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
Nicolas Geoffray1717a492018-11-30 01:02:50 +00001266 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/ false));
Brad Stenning9c924e82021-10-11 19:09:00 -07001267 if (!result->CreateInfoFromClassLoader(soa,
1268 h_class_loader,
1269 h_dex_elements,
1270 nullptr,
1271 /*is_shared_library=*/ false,
1272 /*is_after=*/ false)) {
Calin Juravle57d0acc2017-07-11 17:41:30 -07001273 return nullptr;
1274 }
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001275 return result;
Calin Juravle57d0acc2017-07-11 17:41:30 -07001276}
1277
Dan Zimmermanb682ea42019-12-23 06:59:06 -08001278std::map<std::string, std::string>
1279ClassLoaderContext::EncodeClassPathContextsForClassLoader(jobject class_loader) {
1280 std::unique_ptr<ClassLoaderContext> clc =
1281 ClassLoaderContext::CreateContextForClassLoader(class_loader, nullptr);
1282 if (clc != nullptr) {
1283 return clc->EncodeClassPathContexts("");
1284 }
1285
1286 ScopedObjectAccess soa(Thread::Current());
1287 StackHandleScope<1> hs(soa.Self());
1288 Handle<mirror::ClassLoader> h_class_loader =
1289 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
1290 if (!IsInstanceOfBaseDexClassLoader(soa, h_class_loader)) {
1291 return std::map<std::string, std::string>{};
1292 }
1293
1294 std::vector<const DexFile*> dex_files_loaded;
1295 CollectDexFilesFromSupportedClassLoader(soa, h_class_loader, &dex_files_loaded);
1296
1297 std::map<std::string, std::string> results;
1298 for (const DexFile* dex_file : dex_files_loaded) {
1299 results.emplace(DexFileLoader::GetBaseLocation(dex_file->GetLocation()),
1300 ClassLoaderContext::kUnsupportedClassLoaderContextEncoding);
1301 }
1302 return results;
1303}
1304
Dan Zimmermanc9fa7702020-01-31 13:35:12 -08001305bool ClassLoaderContext::IsValidEncoding(const std::string& possible_encoded_class_loader_context) {
1306 return ClassLoaderContext::Create(possible_encoded_class_loader_context.c_str()) != nullptr
1307 || possible_encoded_class_loader_context == kUnsupportedClassLoaderContextEncoding;
1308}
1309
Mathieu Chartieradc90862018-05-11 13:03:06 -07001310ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
1311 const std::string& context_spec,
1312 bool verify_names,
1313 bool verify_checksums) const {
Calin Juravle98071152021-01-27 18:41:58 -08001314 ScopedTrace trace(__FUNCTION__);
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001315 if (verify_names || verify_checksums) {
Calin Juravle6e6f1b22020-12-15 19:13:19 -08001316 DCHECK(dex_files_state_ == kDexFilesChecksumsRead || dex_files_state_ == kDexFilesOpened)
1317 << "dex_files_state_=" << dex_files_state_;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001318 }
Calin Juravlec5b215f2017-09-12 14:49:37 -07001319
Calin Juravle3f918642017-07-11 19:04:20 -07001320 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001321 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -07001322 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -07001323 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001324 }
1325
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001326 ClassLoaderInfo* info = class_loader_chain_.get();
1327 ClassLoaderInfo* expected = expected_context.class_loader_chain_.get();
1328 CHECK(info != nullptr);
1329 CHECK(expected != nullptr);
1330 if (!ClassLoaderInfoMatch(*info, *expected, context_spec, verify_names, verify_checksums)) {
Mathieu Chartieradc90862018-05-11 13:03:06 -07001331 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -07001332 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001333 return VerificationResult::kVerifies;
1334}
Calin Juravle3f918642017-07-11 19:04:20 -07001335
Vladimir Marko36ec5982019-11-28 10:55:16 +00001336// Returns true if absolute `path` ends with relative `suffix` starting at
1337// a directory name boundary, i.e. after a '/'. For example, "foo/bar"
1338// is a valid suffix of "/data/foo/bar" but not "/data-foo/bar".
1339static inline bool AbsolutePathHasRelativeSuffix(const std::string& path,
1340 const std::string& suffix) {
1341 DCHECK(IsAbsoluteLocation(path));
1342 DCHECK(!IsAbsoluteLocation(suffix));
1343 return (path.size() > suffix.size()) &&
1344 (path[path.size() - suffix.size() - 1u] == '/') &&
1345 (std::string_view(path).substr(/*pos*/ path.size() - suffix.size()) == suffix);
1346}
1347
Calin Juravleb495e7f2020-04-06 19:29:45 -07001348// Returns true if the given dex names are mathing, false otherwise.
1349static bool AreDexNameMatching(const std::string& actual_dex_name,
1350 const std::string& expected_dex_name) {
1351 // Compute the dex location that must be compared.
1352 // We shouldn't do a naive comparison `actual_dex_name == expected_dex_name`
1353 // because even if they refer to the same file, one could be encoded as a relative location
1354 // and the other as an absolute one.
1355 bool is_dex_name_absolute = IsAbsoluteLocation(actual_dex_name);
1356 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_dex_name);
1357 bool dex_names_match = false;
1358
1359 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
1360 // If both locations are absolute or relative then compare them as they are.
1361 // This is usually the case for: shared libraries and secondary dex files.
1362 dex_names_match = (actual_dex_name == expected_dex_name);
1363 } else if (is_dex_name_absolute) {
1364 // The runtime name is absolute but the compiled name (the expected one) is relative.
1365 // This is the case for split apks which depend on base or on other splits.
1366 dex_names_match =
1367 AbsolutePathHasRelativeSuffix(actual_dex_name, expected_dex_name);
1368 } else if (is_expected_dex_name_absolute) {
1369 // The runtime name is relative but the compiled name is absolute.
1370 // There is no expected use case that would end up here as dex files are always loaded
1371 // with their absolute location. However, be tolerant and do the best effort (in case
1372 // there are unexpected new use case...).
1373 dex_names_match =
1374 AbsolutePathHasRelativeSuffix(expected_dex_name, actual_dex_name);
1375 } else {
1376 // Both locations are relative. In this case there's not much we can be sure about
1377 // except that the names are the same. The checksum will ensure that the files are
1378 // are same. This should not happen outside testing and manual invocations.
1379 dex_names_match = (actual_dex_name == expected_dex_name);
1380 }
1381
1382 return dex_names_match;
1383}
1384
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001385bool ClassLoaderContext::ClassLoaderInfoMatch(
1386 const ClassLoaderInfo& info,
1387 const ClassLoaderInfo& expected_info,
1388 const std::string& context_spec,
1389 bool verify_names,
1390 bool verify_checksums) const {
1391 if (info.type != expected_info.type) {
1392 LOG(WARNING) << "ClassLoaderContext type mismatch"
1393 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
1394 << ", found=" << GetClassLoaderTypeName(info.type)
1395 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1396 return false;
1397 }
1398 if (info.classpath.size() != expected_info.classpath.size()) {
1399 LOG(WARNING) << "ClassLoaderContext classpath size mismatch"
1400 << ". expected=" << expected_info.classpath.size()
1401 << ", found=" << info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001402 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001403 return false;
1404 }
Calin Juravle3f918642017-07-11 19:04:20 -07001405
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001406 if (verify_checksums) {
1407 DCHECK_EQ(info.classpath.size(), info.checksums.size());
1408 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
1409 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001410
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001411 if (verify_names) {
Calin Juravle3f918642017-07-11 19:04:20 -07001412 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravleb495e7f2020-04-06 19:29:45 -07001413 bool dex_names_match = AreDexNameMatching(info.classpath[k], expected_info.classpath[k]);
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001414
1415 // Compare the locations.
Vladimir Marko36ec5982019-11-28 10:55:16 +00001416 if (!dex_names_match) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001417 LOG(WARNING) << "ClassLoaderContext classpath element mismatch"
Calin Juravle3f918642017-07-11 19:04:20 -07001418 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001419 << ", found=" << info.classpath[k]
1420 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001421 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001422 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001423
1424 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -07001425 if (info.checksums[k] != expected_info.checksums[k]) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001426 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch"
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001427 << ". expected=" << expected_info.checksums[k]
1428 << ", found=" << info.checksums[k]
1429 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001430 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001431 }
1432 }
1433 }
Calin Juravle3f918642017-07-11 19:04:20 -07001434
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001435 if (info.shared_libraries.size() != expected_info.shared_libraries.size()) {
1436 LOG(WARNING) << "ClassLoaderContext shared library size mismatch. "
Nicolas Geoffraye1672732018-11-30 01:09:49 +00001437 << "Expected=" << expected_info.shared_libraries.size()
1438 << ", found=" << info.shared_libraries.size()
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001439 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1440 return false;
Calin Juravlec79470d2017-07-12 17:37:42 -07001441 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001442 for (size_t i = 0; i < info.shared_libraries.size(); ++i) {
1443 if (!ClassLoaderInfoMatch(*info.shared_libraries[i].get(),
1444 *expected_info.shared_libraries[i].get(),
1445 context_spec,
1446 verify_names,
1447 verify_checksums)) {
1448 return false;
1449 }
1450 }
1451 if (info.parent.get() == nullptr) {
1452 if (expected_info.parent.get() != nullptr) {
1453 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1454 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1455 return false;
1456 }
1457 return true;
1458 } else if (expected_info.parent.get() == nullptr) {
1459 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1460 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1461 return false;
1462 } else {
1463 return ClassLoaderInfoMatch(*info.parent.get(),
1464 *expected_info.parent.get(),
1465 context_spec,
1466 verify_names,
1467 verify_checksums);
1468 }
Calin Juravlec79470d2017-07-12 17:37:42 -07001469}
1470
Calin Juravlea63a2e92020-04-15 20:02:00 -07001471std::set<const DexFile*> ClassLoaderContext::CheckForDuplicateDexFiles(
Calin Juravleb495e7f2020-04-06 19:29:45 -07001472 const std::vector<const DexFile*>& dex_files_to_check) {
Calin Juravle6e6f1b22020-12-15 19:13:19 -08001473 DCHECK_EQ(dex_files_state_, kDexFilesOpened);
Calin Juravleb495e7f2020-04-06 19:29:45 -07001474
Calin Juravlea63a2e92020-04-15 20:02:00 -07001475 std::set<const DexFile*> result;
Calin Juravleb495e7f2020-04-06 19:29:45 -07001476
Nicolas Geoffray982eced2021-03-29 08:49:38 +01001477 // If the chain is null there's nothing we can check, return an empty list.
Calin Juravlea63a2e92020-04-15 20:02:00 -07001478 // The class loader chain can be null if there were issues when creating the
1479 // class loader context (e.g. tests).
Nicolas Geoffray982eced2021-03-29 08:49:38 +01001480 if (class_loader_chain_ == nullptr) {
Calin Juravleb495e7f2020-04-06 19:29:45 -07001481 return result;
1482 }
1483
Calin Juravlea63a2e92020-04-15 20:02:00 -07001484 // We only check the current Class Loader which the first one in the chain.
1485 // Cross class-loader duplicates may be a valid scenario (though unlikely
1486 // in the Android world) - and as such we decide not to warn on them.
1487 ClassLoaderInfo* info = class_loader_chain_.get();
1488 for (size_t k = 0; k < info->classpath.size(); k++) {
1489 for (const DexFile* dex_file : dex_files_to_check) {
1490 if (info->checksums[k] == dex_file->GetLocationChecksum()
1491 && AreDexNameMatching(info->classpath[k], dex_file->GetLocation())) {
1492 result.insert(dex_file);
Calin Juravleb495e7f2020-04-06 19:29:45 -07001493 }
1494 }
Calin Juravleb495e7f2020-04-06 19:29:45 -07001495 }
1496
1497 return result;
1498}
1499
Calin Juravle87e2cb62017-06-13 21:48:45 -07001500} // namespace art