blob: 9fe39b1e8fb1853ba664b404c5b1dca61ac0272d [file] [log] [blame]
Calin Juravle87e2cb62017-06-13 21:48:45 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "class_loader_context.h"
18
Andreas Gampef9411702018-09-06 17:16:57 -070019#include <android-base/parseint.h>
20
Calin Juravle57d0acc2017-07-11 17:41:30 -070021#include "art_field-inl.h"
Vladimir Marko78baed52018-10-11 10:44:58 +010022#include "base/casts.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070023#include "base/dchecked_vector.h"
24#include "base/stl_util.h"
25#include "class_linker.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070026#include "class_loader_utils.h"
David Sehr013fd802018-01-11 22:55:24 -080027#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080028#include "dex/dex_file.h"
29#include "dex/dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070030#include "handle_scope-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010031#include "jni/jni_internal.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070032#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070033#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070034#include "runtime.h"
35#include "scoped_thread_state_change-inl.h"
36#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070037#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070038
39namespace art {
40
41static constexpr char kPathClassLoaderString[] = "PCL";
42static constexpr char kDelegateLastClassLoaderString[] = "DLC";
43static constexpr char kClassLoaderOpeningMark = '[';
44static constexpr char kClassLoaderClosingMark = ']';
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000045static constexpr char kClassLoaderSharedLibraryOpeningMark = '{';
46static constexpr char kClassLoaderSharedLibraryClosingMark = '}';
47static constexpr char kClassLoaderSharedLibrarySeparator = '#';
Calin Juravle7b0648a2017-07-07 18:40:50 -070048static constexpr char kClassLoaderSeparator = ';';
49static constexpr char kClasspathSeparator = ':';
50static constexpr char kDexFileChecksumSeparator = '*';
Calin Juravle87e2cb62017-06-13 21:48:45 -070051
52ClassLoaderContext::ClassLoaderContext()
53 : special_shared_library_(false),
54 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070055 dex_files_open_result_(false),
Calin Juravle41acdc12017-07-18 17:45:32 -070056 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070057
58ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
59 : special_shared_library_(false),
60 dex_files_open_attempted_(true),
61 dex_files_open_result_(true),
62 owns_the_dex_files_(owns_the_dex_files) {}
63
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000064// Utility method to add parent and shared libraries of `info` into
65// the `work_list`.
66static void AddToWorkList(
67 ClassLoaderContext::ClassLoaderInfo* info,
68 std::vector<ClassLoaderContext::ClassLoaderInfo*>& work_list) {
69 if (info->parent != nullptr) {
70 work_list.push_back(info->parent.get());
71 }
72 for (size_t i = 0; i < info->shared_libraries.size(); ++i) {
73 work_list.push_back(info->shared_libraries[i].get());
74 }
75}
76
Calin Juravle57d0acc2017-07-11 17:41:30 -070077ClassLoaderContext::~ClassLoaderContext() {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000078 if (!owns_the_dex_files_ && class_loader_chain_ != nullptr) {
Calin Juravle57d0acc2017-07-11 17:41:30 -070079 // If the context does not own the dex/oat files release the unique pointers to
80 // make sure we do not de-allocate them.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000081 std::vector<ClassLoaderInfo*> work_list;
82 work_list.push_back(class_loader_chain_.get());
83 while (!work_list.empty()) {
84 ClassLoaderInfo* info = work_list.back();
85 work_list.pop_back();
86 for (std::unique_ptr<OatFile>& oat_file : info->opened_oat_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -070087 oat_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -070088 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000089 for (std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Andreas Gampeafaf7f82018-10-16 11:32:38 -070090 dex_file.release(); // NOLINT b/117926937
Calin Juravle57d0acc2017-07-11 17:41:30 -070091 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +000092 AddToWorkList(info, work_list);
Calin Juravle57d0acc2017-07-11 17:41:30 -070093 }
94 }
95}
Calin Juravle87e2cb62017-06-13 21:48:45 -070096
Calin Juravle19915892017-08-03 17:10:36 +000097std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
98 return Create("");
99}
100
Calin Juravle87e2cb62017-06-13 21:48:45 -0700101std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
102 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
103 if (result->Parse(spec)) {
104 return result;
105 } else {
106 return nullptr;
107 }
108}
109
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000110static size_t FindMatchingSharedLibraryCloseMarker(const std::string& spec,
111 size_t shared_library_open_index) {
112 // Counter of opened shared library marker we've encountered so far.
113 uint32_t counter = 1;
114 // The index at which we're operating in the loop.
115 uint32_t string_index = shared_library_open_index + 1;
116 size_t shared_library_close = std::string::npos;
117 while (counter != 0) {
118 shared_library_close =
119 spec.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index);
120 size_t shared_library_open =
121 spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, string_index);
122 if (shared_library_close == std::string::npos) {
123 // No matching closing marker. Return an error.
124 break;
125 }
126
127 if ((shared_library_open == std::string::npos) ||
128 (shared_library_close < shared_library_open)) {
129 // We have seen a closing marker. Decrement the counter.
130 --counter;
131 // Move the search index forward.
132 string_index = shared_library_close + 1;
133 } else {
134 // New nested opening marker. Increment the counter and move the search
135 // index after the marker.
136 ++counter;
137 string_index = shared_library_open + 1;
138 }
139 }
140 return shared_library_close;
141}
142
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000143// The expected format is:
144// "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]{ClassLoaderType2[...]}".
Calin Juravle7b0648a2017-07-07 18:40:50 -0700145// The checksum part of the format is expected only if parse_cheksums is true.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000146std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseClassLoaderSpec(
147 const std::string& class_loader_spec,
148 bool parse_checksums) {
149 ClassLoaderType class_loader_type = ExtractClassLoaderType(class_loader_spec);
150 if (class_loader_type == kInvalidClassLoader) {
151 return nullptr;
152 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700153 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
154 size_t type_str_size = strlen(class_loader_type_str);
155
156 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
157
158 // Check the opening and closing markers.
159 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000160 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700161 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000162 if ((class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) &&
163 (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderSharedLibraryClosingMark)) {
164 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700165 }
166
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000167 size_t closing_index = class_loader_spec.find_first_of(kClassLoaderClosingMark);
168
Calin Juravle87e2cb62017-06-13 21:48:45 -0700169 // At this point we know the format is ok; continue and extract the classpath.
170 // Note that class loaders with an empty class path are allowed.
171 std::string classpath = class_loader_spec.substr(type_str_size + 1,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000172 closing_index - type_str_size - 1);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700173
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000174 std::unique_ptr<ClassLoaderInfo> info(new ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700175
176 if (!parse_checksums) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000177 Split(classpath, kClasspathSeparator, &info->classpath);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700178 } else {
179 std::vector<std::string> classpath_elements;
180 Split(classpath, kClasspathSeparator, &classpath_elements);
181 for (const std::string& element : classpath_elements) {
182 std::vector<std::string> dex_file_with_checksum;
183 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
184 if (dex_file_with_checksum.size() != 2) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000185 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700186 }
187 uint32_t checksum = 0;
Tom Cherry7bc8e8f2018-10-05 14:34:13 -0700188 if (!android::base::ParseUint(dex_file_with_checksum[1].c_str(), &checksum)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000189 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700190 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000191 info->classpath.push_back(dex_file_with_checksum[0]);
192 info->checksums.push_back(checksum);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700193 }
194 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700195
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000196 if ((class_loader_spec[class_loader_spec.length() - 1] == kClassLoaderSharedLibraryClosingMark) &&
197 (class_loader_spec[class_loader_spec.length() - 2] != kClassLoaderSharedLibraryOpeningMark)) {
198 // Non-empty list of shared libraries.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000199 size_t start_index = class_loader_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark);
200 if (start_index == std::string::npos) {
201 return nullptr;
202 }
203 std::string shared_libraries_spec =
204 class_loader_spec.substr(start_index + 1, class_loader_spec.length() - start_index - 2);
205 std::vector<std::string> shared_libraries;
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000206 size_t cursor = 0;
207 while (cursor != shared_libraries_spec.length()) {
208 size_t shared_library_separator =
209 shared_libraries_spec.find_first_of(kClassLoaderSharedLibrarySeparator, cursor);
210 size_t shared_library_open =
211 shared_libraries_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark, cursor);
212 std::string shared_library_spec;
213 if (shared_library_separator == std::string::npos) {
214 // Only one shared library, for example:
215 // PCL[...]
216 shared_library_spec =
217 shared_libraries_spec.substr(cursor, shared_libraries_spec.length() - cursor);
218 cursor = shared_libraries_spec.length();
219 } else if ((shared_library_open == std::string::npos) ||
220 (shared_library_open > shared_library_separator)) {
221 // We found a shared library without nested shared libraries, for example:
222 // PCL[...]#PCL[...]{...}
223 shared_library_spec =
224 shared_libraries_spec.substr(cursor, shared_library_separator - cursor);
225 cursor = shared_library_separator + 1;
226 } else {
227 // The shared library contains nested shared libraries. Find the matching closing shared
228 // marker for it.
229 size_t closing_marker =
230 FindMatchingSharedLibraryCloseMarker(shared_libraries_spec, shared_library_open);
231 if (closing_marker == std::string::npos) {
232 // No matching closing marker, return an error.
233 return nullptr;
234 }
235 shared_library_spec = shared_libraries_spec.substr(cursor, closing_marker + 1 - cursor);
236 cursor = closing_marker + 1;
237 if (cursor != shared_libraries_spec.length() &&
238 shared_libraries_spec[cursor] == kClassLoaderSharedLibrarySeparator) {
239 // Pass the shared library separator marker.
240 ++cursor;
241 }
242 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000243 std::unique_ptr<ClassLoaderInfo> shared_library(
244 ParseInternal(shared_library_spec, parse_checksums));
245 if (shared_library == nullptr) {
246 return nullptr;
247 }
248 info->shared_libraries.push_back(std::move(shared_library));
249 }
250 }
251
252 return info;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700253}
254
255// Extracts the class loader type from the given spec.
256// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
257// recognized.
258ClassLoaderContext::ClassLoaderType
259ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
260 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
261 for (const ClassLoaderType& type : kValidTypes) {
262 const char* type_str = GetClassLoaderTypeName(type);
263 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
264 return type;
265 }
266 }
267 return kInvalidClassLoader;
268}
269
270// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
271// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
272// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700273bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700274 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700275 // By default we load the dex files in a PathClassLoader.
276 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
277 // tests)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000278 class_loader_chain_.reset(new ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700279 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700280 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700281
Calin Juravle87e2cb62017-06-13 21:48:45 -0700282 // Stop early if we detect the special shared library, which may be passed as the classpath
283 // for dex2oat when we want to skip the shared libraries check.
284 if (spec == OatFile::kSpecialSharedLibrary) {
285 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
286 special_shared_library_ = true;
287 return true;
288 }
289
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000290 CHECK(class_loader_chain_ == nullptr);
291 class_loader_chain_.reset(ParseInternal(spec, parse_checksums));
292 return class_loader_chain_ != nullptr;
293}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700294
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000295ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal(
296 const std::string& spec, bool parse_checksums) {
297 CHECK(!spec.empty());
298 CHECK_NE(spec, OatFile::kSpecialSharedLibrary);
299 std::string remaining = spec;
300 std::unique_ptr<ClassLoaderInfo> first(nullptr);
301 ClassLoaderInfo* previous_iteration = nullptr;
302 while (!remaining.empty()) {
303 std::string class_loader_spec;
304 size_t first_class_loader_separator = remaining.find_first_of(kClassLoaderSeparator);
305 size_t first_shared_library_open =
306 remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark);
307 if (first_class_loader_separator == std::string::npos) {
308 // Only one class loader, for example:
309 // PCL[...]
310 class_loader_spec = remaining;
311 remaining = "";
312 } else if ((first_shared_library_open == std::string::npos) ||
313 (first_shared_library_open > first_class_loader_separator)) {
314 // We found a class loader spec without shared libraries, for example:
315 // PCL[...];PCL[...]{...}
316 class_loader_spec = remaining.substr(0, first_class_loader_separator);
317 remaining = remaining.substr(first_class_loader_separator + 1,
318 remaining.size() - first_class_loader_separator - 1);
319 } else {
320 // The class loader spec contains shared libraries. Find the matching closing
321 // shared library marker for it.
322
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000323 uint32_t shared_library_close =
324 FindMatchingSharedLibraryCloseMarker(remaining, first_shared_library_open);
325 if (shared_library_close == std::string::npos) {
326 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
327 return nullptr;
328 }
329 class_loader_spec = remaining.substr(0, shared_library_close + 1);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000330
Nicolas Geoffrayf378fff2018-11-19 12:52:26 +0000331 // Compute the remaining string to analyze.
332 if (remaining.size() == shared_library_close + 1) {
333 remaining = "";
334 } else if ((remaining.size() == shared_library_close + 2) ||
335 (remaining.at(shared_library_close + 1) != kClassLoaderSeparator)) {
336 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
337 return nullptr;
338 } else {
339 remaining = remaining.substr(shared_library_close + 2,
340 remaining.size() - shared_library_close - 2);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000341 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700342 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000343
344 std::unique_ptr<ClassLoaderInfo> info =
345 ParseClassLoaderSpec(class_loader_spec, parse_checksums);
346 if (info == nullptr) {
347 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
348 return nullptr;
349 }
350 if (first == nullptr) {
351 first.reset(info.release());
352 previous_iteration = first.get();
353 } else {
354 CHECK(previous_iteration != nullptr);
355 previous_iteration->parent.reset(info.release());
356 previous_iteration = previous_iteration->parent.get();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700357 }
358 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000359 return first.release();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700360}
361
362// Opens requested class path files and appends them to opened_dex_files. If the dex files have
363// been stripped, this opens them from their oat files (which get added to opened_oat_files).
364bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700365 if (dex_files_open_attempted_) {
366 // Do not attempt to re-open the files if we already tried.
367 return dex_files_open_result_;
368 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700369
370 dex_files_open_attempted_ = true;
371 // Assume we can open all dex files. If not, we will set this to false as we go.
372 dex_files_open_result_ = true;
373
374 if (special_shared_library_) {
375 // Nothing to open if the context is a special shared library.
376 return true;
377 }
378
379 // Note that we try to open all dex files even if some fail.
380 // We may get resource-only apks which we cannot load.
381 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
382 // no dex files. So that we can distinguish the real failures...
David Sehr013fd802018-01-11 22:55:24 -0800383 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000384 std::vector<ClassLoaderInfo*> work_list;
Nicolas Geoffray9893c472018-11-13 15:39:53 +0000385 CHECK(class_loader_chain_ != nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000386 work_list.push_back(class_loader_chain_.get());
387 while (!work_list.empty()) {
388 ClassLoaderInfo* info = work_list.back();
389 work_list.pop_back();
390 size_t opened_dex_files_index = info->opened_dex_files.size();
391 for (const std::string& cp_elem : info->classpath) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700392 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000393 std::string location = cp_elem;
394 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000395 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700396 }
397
Calin Juravle87e2cb62017-06-13 21:48:45 -0700398 std::string error_msg;
399 // When opening the dex files from the context we expect their checksum to match their
400 // contents. So pass true to verify_checksum.
David Sehr013fd802018-01-11 22:55:24 -0800401 if (!dex_file_loader.Open(location.c_str(),
402 location.c_str(),
403 Runtime::Current()->IsVerificationEnabled(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700404 /*verify_checksum=*/ true,
David Sehr013fd802018-01-11 22:55:24 -0800405 &error_msg,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000406 &info->opened_dex_files)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700407 // If we fail to open the dex file because it's been stripped, try to open the dex file
408 // from its corresponding oat file.
409 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
410 // (for example, if the pre-build is only quicken and we want to re-compile it
411 // speed-profile).
412 // TODO(calin): Use the vdex directly instead of going through the oat file.
413 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
414 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
415 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
416 if (oat_file != nullptr &&
417 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000418 info->opened_oat_files.push_back(std::move(oat_file));
419 info->opened_dex_files.insert(info->opened_dex_files.end(),
420 std::make_move_iterator(oat_dex_files.begin()),
421 std::make_move_iterator(oat_dex_files.end()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700422 } else {
423 LOG(WARNING) << "Could not open dex files from location: " << location;
424 dex_files_open_result_ = false;
425 }
426 }
427 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700428
429 // We finished opening the dex files from the classpath.
430 // Now update the classpath and the checksum with the locations of the dex files.
431 //
432 // We do this because initially the classpath contains the paths of the dex files; and
433 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
434 // file paths with the actual dex locations being loaded.
435 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
436 // location in the class paths.
437 // Note that this will also remove the paths that could not be opened.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000438 info->original_classpath = std::move(info->classpath);
439 info->classpath.clear();
440 info->checksums.clear();
441 for (size_t k = opened_dex_files_index; k < info->opened_dex_files.size(); k++) {
442 std::unique_ptr<const DexFile>& dex = info->opened_dex_files[k];
443 info->classpath.push_back(dex->GetLocation());
444 info->checksums.push_back(dex->GetLocationChecksum());
Calin Juravlec5b215f2017-09-12 14:49:37 -0700445 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000446 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700447 }
448
449 return dex_files_open_result_;
450}
451
452bool ClassLoaderContext::RemoveLocationsFromClassPaths(
453 const dchecked_vector<std::string>& locations) {
454 CHECK(!dex_files_open_attempted_)
455 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
456
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000457 if (class_loader_chain_ == nullptr) {
458 return false;
459 }
460
Calin Juravle87e2cb62017-06-13 21:48:45 -0700461 std::set<std::string> canonical_locations;
462 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700463 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700464 }
465 bool removed_locations = false;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000466 std::vector<ClassLoaderInfo*> work_list;
467 work_list.push_back(class_loader_chain_.get());
468 while (!work_list.empty()) {
469 ClassLoaderInfo* info = work_list.back();
470 work_list.pop_back();
471 size_t initial_size = info->classpath.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700472 auto kept_it = std::remove_if(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000473 info->classpath.begin(),
474 info->classpath.end(),
Calin Juravle87e2cb62017-06-13 21:48:45 -0700475 [canonical_locations](const std::string& location) {
476 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700477 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700478 });
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000479 info->classpath.erase(kept_it, info->classpath.end());
480 if (initial_size != info->classpath.size()) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700481 removed_locations = true;
482 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000483 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700484 }
485 return removed_locations;
486}
487
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700488std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700489 return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700490}
491
Mathieu Chartierc4440772018-04-16 14:40:56 -0700492std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
493 ClassLoaderContext* stored_context) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700494 return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700495}
496
497std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700498 bool for_dex2oat,
499 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700500 CheckDexFilesOpened("EncodeContextForOatFile");
501 if (special_shared_library_) {
502 return OatFile::kSpecialSharedLibrary;
503 }
504
Mathieu Chartierc4440772018-04-16 14:40:56 -0700505 if (stored_context != nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000506 DCHECK_EQ(GetParentChainSize(), stored_context->GetParentChainSize());
Mathieu Chartierc4440772018-04-16 14:40:56 -0700507 }
508
Calin Juravle7b0648a2017-07-07 18:40:50 -0700509 std::ostringstream out;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000510 if (class_loader_chain_ == nullptr) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700511 // We can get in this situation if the context was created with a class path containing the
512 // source dex files which were later removed (happens during run-tests).
513 out << GetClassLoaderTypeName(kPathClassLoader)
514 << kClassLoaderOpeningMark
515 << kClassLoaderClosingMark;
516 return out.str();
517 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700518
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000519 EncodeContextInternal(
520 *class_loader_chain_,
521 base_dir,
522 for_dex2oat,
523 (stored_context == nullptr ? nullptr : stored_context->class_loader_chain_.get()),
524 out);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700525 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700526}
527
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000528void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info,
529 const std::string& base_dir,
530 bool for_dex2oat,
531 ClassLoaderInfo* stored_info,
532 std::ostringstream& out) const {
533 out << GetClassLoaderTypeName(info.type);
534 out << kClassLoaderOpeningMark;
535 std::set<std::string> seen_locations;
536 SafeMap<std::string, std::string> remap;
537 if (stored_info != nullptr) {
538 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
539 // Note that we don't care if the same name appears twice.
540 remap.Put(info.original_classpath[k], stored_info->classpath[k]);
541 }
542 }
543 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
544 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
545 if (for_dex2oat) {
546 // dex2oat only needs the base location. It cannot accept multidex locations.
547 // So ensure we only add each file once.
548 bool new_insert = seen_locations.insert(
549 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
550 if (!new_insert) {
551 continue;
552 }
553 }
554 std::string location = dex_file->GetLocation();
555 // If there is a stored class loader remap, fix up the multidex strings.
556 if (!remap.empty()) {
557 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
558 auto it = remap.find(base_dex_location);
559 CHECK(it != remap.end()) << base_dex_location;
560 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
561 }
562 if (k > 0) {
563 out << kClasspathSeparator;
564 }
565 // Find paths that were relative and convert them back from absolute.
566 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
567 out << location.substr(base_dir.length() + 1).c_str();
568 } else {
569 out << location.c_str();
570 }
571 // dex2oat does not need the checksums.
572 if (!for_dex2oat) {
573 out << kDexFileChecksumSeparator;
574 out << dex_file->GetLocationChecksum();
575 }
576 }
577 out << kClassLoaderClosingMark;
578
579 if (!info.shared_libraries.empty()) {
580 out << kClassLoaderSharedLibraryOpeningMark;
581 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
582 if (i > 0) {
583 out << kClassLoaderSharedLibrarySeparator;
584 }
585 EncodeContextInternal(
586 *info.shared_libraries[i].get(),
587 base_dir,
588 for_dex2oat,
589 (stored_info == nullptr ? nullptr : stored_info->shared_libraries[i].get()),
590 out);
591 }
592 out << kClassLoaderSharedLibraryClosingMark;
593 }
594 if (info.parent != nullptr) {
595 out << kClassLoaderSeparator;
596 EncodeContextInternal(
597 *info.parent.get(),
598 base_dir,
599 for_dex2oat,
600 (stored_info == nullptr ? nullptr : stored_info->parent.get()),
601 out);
602 }
603}
604
605// Returns the WellKnownClass for the given class loader type.
606static jclass GetClassLoaderClass(ClassLoaderContext::ClassLoaderType type) {
607 switch (type) {
608 case ClassLoaderContext::kPathClassLoader:
609 return WellKnownClasses::dalvik_system_PathClassLoader;
610 case ClassLoaderContext::kDelegateLastClassLoader:
611 return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
612 case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch.
613 }
614 LOG(FATAL) << "Invalid class loader type " << type;
615 UNREACHABLE();
616}
617
618static jobject CreateClassLoaderInternal(Thread* self,
619 const ClassLoaderContext::ClassLoaderInfo& info)
620 REQUIRES_SHARED(Locks::mutator_lock_) {
621 CHECK(info.shared_libraries.empty()) << "Class loader shared library not implemented yet";
622 jobject parent = nullptr;
623 if (info.parent != nullptr) {
624 parent = CreateClassLoaderInternal(self, *info.parent.get());
625 }
626 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
627 info.opened_dex_files);
628 return Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
629 self,
630 class_path_files,
631 GetClassLoaderClass(info.type),
632 parent);
633}
634
Calin Juravle87e2cb62017-06-13 21:48:45 -0700635jobject ClassLoaderContext::CreateClassLoader(
636 const std::vector<const DexFile*>& compilation_sources) const {
637 CheckDexFilesOpened("CreateClassLoader");
638
639 Thread* self = Thread::Current();
640 ScopedObjectAccess soa(self);
641
Calin Juravlec79470d2017-07-12 17:37:42 -0700642 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700643
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000644 if (class_loader_chain_ == nullptr) {
Calin Juravlec79470d2017-07-12 17:37:42 -0700645 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700646 }
647
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000648 // Create the class loader of the parent.
649 jobject parent = nullptr;
650 if (class_loader_chain_->parent != nullptr) {
651 parent = CreateClassLoaderInternal(self, *class_loader_chain_->parent.get());
Calin Juravlec79470d2017-07-12 17:37:42 -0700652 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700653
Calin Juravlec79470d2017-07-12 17:37:42 -0700654 // We set up all the parents. Move on to create the first class loader.
655 // Its classpath comes first, followed by compilation sources. This ensures that whenever
656 // we need to resolve classes from it the classpath elements come first.
657
658 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000659 class_loader_chain_->opened_dex_files);
Calin Juravlec79470d2017-07-12 17:37:42 -0700660 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000661 compilation_sources.begin(),
662 compilation_sources.end());
Calin Juravlec79470d2017-07-12 17:37:42 -0700663
664 return class_linker->CreateWellKnownClassLoader(
665 self,
666 first_class_loader_classpath,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000667 GetClassLoaderClass(class_loader_chain_->type),
668 parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700669}
670
671std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
672 CheckDexFilesOpened("FlattenOpenedDexFiles");
673
674 std::vector<const DexFile*> result;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000675 if (class_loader_chain_ == nullptr) {
676 return result;
677 }
678 std::vector<ClassLoaderInfo*> work_list;
679 work_list.push_back(class_loader_chain_.get());
680 while (!work_list.empty()) {
681 ClassLoaderInfo* info = work_list.back();
682 work_list.pop_back();
683 for (const std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700684 result.push_back(dex_file.get());
685 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000686 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700687 }
688 return result;
689}
690
691const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
692 switch (type) {
693 case kPathClassLoader: return kPathClassLoaderString;
694 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
695 default:
696 LOG(FATAL) << "Invalid class loader type " << type;
697 UNREACHABLE();
698 }
699}
700
701void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
702 CHECK(dex_files_open_attempted_)
703 << "Dex files were not successfully opened before the call to " << calling_method
704 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
705}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700706
Calin Juravle57d0acc2017-07-11 17:41:30 -0700707// Collects the dex files from the give Java dex_file object. Only the dex files with
708// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
709static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
710 ArtField* const cookie_field,
711 std::vector<const DexFile*>* out_dex_files)
712 REQUIRES_SHARED(Locks::mutator_lock_) {
713 if (java_dex_file == nullptr) {
714 return true;
715 }
716 // On the Java side, the dex files are stored in the cookie field.
717 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
718 if (long_array == nullptr) {
719 // This should never happen so log a warning.
720 LOG(ERROR) << "Unexpected null cookie";
721 return false;
722 }
723 int32_t long_array_size = long_array->GetLength();
724 // Index 0 from the long array stores the oat file. The dex files start at index 1.
725 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +0100726 const DexFile* cp_dex_file =
727 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700728 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
729 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
730 // cp_dex_file can be null.
731 out_dex_files->push_back(cp_dex_file);
732 }
733 }
734 return true;
735}
736
737// Collects all the dex files loaded by the given class loader.
738// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
739// a null list of dex elements or a null dex element).
740static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
741 Handle<mirror::ClassLoader> class_loader,
742 std::vector<const DexFile*>* out_dex_files)
743 REQUIRES_SHARED(Locks::mutator_lock_) {
744 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
745
746 // All supported class loaders inherit from BaseDexClassLoader.
747 // We need to get the DexPathList and loop through it.
748 ArtField* const cookie_field =
749 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
750 ArtField* const dex_file_field =
751 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
752 ObjPtr<mirror::Object> dex_path_list =
753 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
754 GetObject(class_loader.Get());
755 CHECK(cookie_field != nullptr);
756 CHECK(dex_file_field != nullptr);
757 if (dex_path_list == nullptr) {
758 // This may be null if the current class loader is under construction and it does not
759 // have its fields setup yet.
760 return true;
761 }
762 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
763 ObjPtr<mirror::Object> dex_elements_obj =
764 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
765 GetObject(dex_path_list);
766 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
767 // at the mCookie which is a DexFile vector.
768 if (dex_elements_obj == nullptr) {
769 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
770 // and assume we have no elements.
771 return true;
772 } else {
773 StackHandleScope<1> hs(soa.Self());
774 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
775 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
776 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
777 mirror::Object* element = dex_elements->GetWithoutChecks(i);
778 if (element == nullptr) {
779 // Should never happen, log an error and break.
780 // TODO(calin): It's unclear if we should just assert here.
781 // This code was propagated to oat_file_manager from the class linker where it would
782 // throw a NPE. For now, return false which will mark this class loader as unsupported.
783 LOG(ERROR) << "Unexpected null in the dex element list";
784 return false;
785 }
786 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
787 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
788 return false;
789 }
790 }
791 }
792
793 return true;
794}
795
796static bool GetDexFilesFromDexElementsArray(
797 ScopedObjectAccessAlreadyRunnable& soa,
798 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
799 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
800 DCHECK(dex_elements != nullptr);
801
802 ArtField* const cookie_field =
803 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
804 ArtField* const dex_file_field =
805 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
806 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
807 WellKnownClasses::dalvik_system_DexPathList__Element);
808 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
809 WellKnownClasses::dalvik_system_DexFile);
810
811 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
812 mirror::Object* element = dex_elements->GetWithoutChecks(i);
813 // We can hit a null element here because this is invoked with a partially filled dex_elements
814 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
815 // list of dex files which were opened before.
816 if (element == nullptr) {
817 continue;
818 }
819
820 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
821 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
822 // a historical glitch. All the java code opens dex files using an array of Elements.
823 ObjPtr<mirror::Object> dex_file;
824 if (element_class == element->GetClass()) {
825 dex_file = dex_file_field->GetObject(element);
826 } else if (dexfile_class == element->GetClass()) {
827 dex_file = element;
828 } else {
829 LOG(ERROR) << "Unsupported element in dex_elements: "
830 << mirror::Class::PrettyClass(element->GetClass());
831 return false;
832 }
833
834 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
835 return false;
836 }
837 }
838 return true;
839}
840
841// Adds the `class_loader` info to the `context`.
842// The dex file present in `dex_elements` array (if not null) will be added at the end of
843// the classpath.
844// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
845// BootClassLoader. Note that the class loader chain is expected to be short.
846bool ClassLoaderContext::AddInfoToContextFromClassLoader(
847 ScopedObjectAccessAlreadyRunnable& soa,
848 Handle<mirror::ClassLoader> class_loader,
849 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
850 REQUIRES_SHARED(Locks::mutator_lock_) {
851 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
852 // Nothing to do for the boot class loader as we don't add its dex files to the context.
853 return true;
854 }
855
856 ClassLoaderContext::ClassLoaderType type;
857 if (IsPathOrDexClassLoader(soa, class_loader)) {
858 type = kPathClassLoader;
859 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
860 type = kDelegateLastClassLoader;
861 } else {
862 LOG(WARNING) << "Unsupported class loader";
863 return false;
864 }
865
866 // Inspect the class loader for its dex files.
867 std::vector<const DexFile*> dex_files_loaded;
868 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
869
870 // If we have a dex_elements array extract its dex elements now.
871 // This is used in two situations:
872 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
873 // passing the list of already open dex files each time. This ensures that we see the
874 // correct context even if the ClassLoader under construction is not fully build.
875 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
876 // appending them to the current class loader. When the new code paths are loaded in
877 // BaseDexClassLoader, the paths already present in the class loader will be passed
878 // in the dex_elements array.
879 if (dex_elements != nullptr) {
880 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
881 }
882
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000883 ClassLoaderInfo* info = new ClassLoaderContext::ClassLoaderInfo(type);
884 if (class_loader_chain_ == nullptr) {
885 class_loader_chain_.reset(info);
886 } else {
887 ClassLoaderInfo* child = class_loader_chain_.get();
888 while (child->parent != nullptr) {
889 child = child->parent.get();
890 }
891 child->parent.reset(info);
892 }
893
Calin Juravle57d0acc2017-07-11 17:41:30 -0700894 for (const DexFile* dex_file : dex_files_loaded) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000895 info->classpath.push_back(dex_file->GetLocation());
896 info->checksums.push_back(dex_file->GetLocationChecksum());
897 info->opened_dex_files.emplace_back(dex_file);
Calin Juravle57d0acc2017-07-11 17:41:30 -0700898 }
899
900 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
901
902 StackHandleScope<1> hs(Thread::Current());
903 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
904
905 // Note that dex_elements array is null here. The elements are considered to be part of the
906 // current class loader and are not passed to the parents.
907 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
908 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
909}
910
911std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
912 jobject class_loader,
913 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700914 CHECK(class_loader != nullptr);
915
Calin Juravle57d0acc2017-07-11 17:41:30 -0700916 ScopedObjectAccess soa(Thread::Current());
917 StackHandleScope<2> hs(soa.Self());
918 Handle<mirror::ClassLoader> h_class_loader =
919 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
920 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
921 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
922
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700923 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/ false));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700924 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
925 return result;
926 } else {
927 return nullptr;
928 }
929}
930
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700931static bool IsAbsoluteLocation(const std::string& location) {
932 return !location.empty() && location[0] == '/';
933}
934
Mathieu Chartieradc90862018-05-11 13:03:06 -0700935ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
936 const std::string& context_spec,
937 bool verify_names,
938 bool verify_checksums) const {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700939 if (verify_names || verify_checksums) {
940 DCHECK(dex_files_open_attempted_);
941 DCHECK(dex_files_open_result_);
942 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700943
Calin Juravle3f918642017-07-11 19:04:20 -0700944 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700945 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -0700946 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700947 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700948 }
949
Calin Juravlec5b215f2017-09-12 14:49:37 -0700950 // Special shared library contexts always match. They essentially instruct the runtime
951 // to ignore the class path check because the oat file is known to be loaded in different
952 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
953 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700954 if (expected_context.special_shared_library_) {
955 // Special case where we are the only entry in the class path.
Nicolas Geoffray9893c472018-11-13 15:39:53 +0000956 if (class_loader_chain_ != nullptr &&
957 class_loader_chain_->parent == nullptr &&
958 class_loader_chain_->classpath.size() == 0) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700959 return VerificationResult::kVerifies;
960 }
961 return VerificationResult::kForcedToSkipChecks;
962 } else if (special_shared_library_) {
963 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -0700964 }
965
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000966 ClassLoaderInfo* info = class_loader_chain_.get();
967 ClassLoaderInfo* expected = expected_context.class_loader_chain_.get();
968 CHECK(info != nullptr);
969 CHECK(expected != nullptr);
970 if (!ClassLoaderInfoMatch(*info, *expected, context_spec, verify_names, verify_checksums)) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700971 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700972 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000973 return VerificationResult::kVerifies;
974}
Calin Juravle3f918642017-07-11 19:04:20 -0700975
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000976bool ClassLoaderContext::ClassLoaderInfoMatch(
977 const ClassLoaderInfo& info,
978 const ClassLoaderInfo& expected_info,
979 const std::string& context_spec,
980 bool verify_names,
981 bool verify_checksums) const {
982 if (info.type != expected_info.type) {
983 LOG(WARNING) << "ClassLoaderContext type mismatch"
984 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
985 << ", found=" << GetClassLoaderTypeName(info.type)
986 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
987 return false;
988 }
989 if (info.classpath.size() != expected_info.classpath.size()) {
990 LOG(WARNING) << "ClassLoaderContext classpath size mismatch"
991 << ". expected=" << expected_info.classpath.size()
992 << ", found=" << info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700993 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000994 return false;
995 }
Calin Juravle3f918642017-07-11 19:04:20 -0700996
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000997 if (verify_checksums) {
998 DCHECK_EQ(info.classpath.size(), info.checksums.size());
999 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
1000 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -07001001
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001002 if (verify_names) {
Calin Juravle3f918642017-07-11 19:04:20 -07001003 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001004 // Compute the dex location that must be compared.
1005 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
1006 // because even if they refer to the same file, one could be encoded as a relative location
1007 // and the other as an absolute one.
1008 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
1009 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
1010 std::string dex_name;
1011 std::string expected_dex_name;
1012
1013 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
1014 // If both locations are absolute or relative then compare them as they are.
1015 // This is usually the case for: shared libraries and secondary dex files.
1016 dex_name = info.classpath[k];
1017 expected_dex_name = expected_info.classpath[k];
1018 } else if (is_dex_name_absolute) {
1019 // The runtime name is absolute but the compiled name (the expected one) is relative.
1020 // This is the case for split apks which depend on base or on other splits.
1021 dex_name = info.classpath[k];
1022 expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
1023 info.classpath[k].c_str(), expected_info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +00001024 } else if (is_expected_dex_name_absolute) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001025 // The runtime name is relative but the compiled name is absolute.
1026 // There is no expected use case that would end up here as dex files are always loaded
1027 // with their absolute location. However, be tolerant and do the best effort (in case
1028 // there are unexpected new use case...).
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001029 dex_name = OatFile::ResolveRelativeEncodedDexLocation(
1030 expected_info.classpath[k].c_str(), info.classpath[k]);
1031 expected_dex_name = expected_info.classpath[k];
Calin Juravle92003fe2017-09-06 02:22:57 +00001032 } else {
1033 // Both locations are relative. In this case there's not much we can be sure about
1034 // except that the names are the same. The checksum will ensure that the files are
1035 // are same. This should not happen outside testing and manual invocations.
1036 dex_name = info.classpath[k];
1037 expected_dex_name = expected_info.classpath[k];
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001038 }
1039
1040 // Compare the locations.
1041 if (dex_name != expected_dex_name) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001042 LOG(WARNING) << "ClassLoaderContext classpath element mismatch"
Calin Juravle3f918642017-07-11 19:04:20 -07001043 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001044 << ", found=" << info.classpath[k]
1045 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001046 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001047 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001048
1049 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -07001050 if (info.checksums[k] != expected_info.checksums[k]) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001051 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch"
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001052 << ". expected=" << expected_info.checksums[k]
1053 << ", found=" << info.checksums[k]
1054 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001055 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001056 }
1057 }
1058 }
Calin Juravle3f918642017-07-11 19:04:20 -07001059
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001060 if (info.shared_libraries.size() != expected_info.shared_libraries.size()) {
1061 LOG(WARNING) << "ClassLoaderContext shared library size mismatch. "
1062 << "Expected=" << expected_info.classpath.size()
1063 << ", found=" << info.classpath.size()
1064 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1065 return false;
Calin Juravlec79470d2017-07-12 17:37:42 -07001066 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001067 for (size_t i = 0; i < info.shared_libraries.size(); ++i) {
1068 if (!ClassLoaderInfoMatch(*info.shared_libraries[i].get(),
1069 *expected_info.shared_libraries[i].get(),
1070 context_spec,
1071 verify_names,
1072 verify_checksums)) {
1073 return false;
1074 }
1075 }
1076 if (info.parent.get() == nullptr) {
1077 if (expected_info.parent.get() != nullptr) {
1078 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1079 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1080 return false;
1081 }
1082 return true;
1083 } else if (expected_info.parent.get() == nullptr) {
1084 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1085 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1086 return false;
1087 } else {
1088 return ClassLoaderInfoMatch(*info.parent.get(),
1089 *expected_info.parent.get(),
1090 context_spec,
1091 verify_names,
1092 verify_checksums);
1093 }
Calin Juravlec79470d2017-07-12 17:37:42 -07001094}
1095
Calin Juravle87e2cb62017-06-13 21:48:45 -07001096} // namespace art