blob: 0bae60a886dbf3b19cbb9091ffcfa88b9931d03d [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 Geoffray06af3b42018-10-29 10:39:04 +0000110// The expected format is:
111// "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]{ClassLoaderType2[...]}".
Calin Juravle7b0648a2017-07-07 18:40:50 -0700112// The checksum part of the format is expected only if parse_cheksums is true.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000113std::unique_ptr<ClassLoaderContext::ClassLoaderInfo> ClassLoaderContext::ParseClassLoaderSpec(
114 const std::string& class_loader_spec,
115 bool parse_checksums) {
116 ClassLoaderType class_loader_type = ExtractClassLoaderType(class_loader_spec);
117 if (class_loader_type == kInvalidClassLoader) {
118 return nullptr;
119 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700120 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
121 size_t type_str_size = strlen(class_loader_type_str);
122
123 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
124
125 // Check the opening and closing markers.
126 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000127 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700128 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000129 if ((class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) &&
130 (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderSharedLibraryClosingMark)) {
131 return nullptr;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700132 }
133
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000134 size_t closing_index = class_loader_spec.find_first_of(kClassLoaderClosingMark);
135
Calin Juravle87e2cb62017-06-13 21:48:45 -0700136 // At this point we know the format is ok; continue and extract the classpath.
137 // Note that class loaders with an empty class path are allowed.
138 std::string classpath = class_loader_spec.substr(type_str_size + 1,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000139 closing_index - type_str_size - 1);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700140
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000141 std::unique_ptr<ClassLoaderInfo> info(new ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700142
143 if (!parse_checksums) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000144 Split(classpath, kClasspathSeparator, &info->classpath);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700145 } else {
146 std::vector<std::string> classpath_elements;
147 Split(classpath, kClasspathSeparator, &classpath_elements);
148 for (const std::string& element : classpath_elements) {
149 std::vector<std::string> dex_file_with_checksum;
150 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
151 if (dex_file_with_checksum.size() != 2) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000152 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700153 }
154 uint32_t checksum = 0;
Tom Cherry7bc8e8f2018-10-05 14:34:13 -0700155 if (!android::base::ParseUint(dex_file_with_checksum[1].c_str(), &checksum)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000156 return nullptr;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700157 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000158 info->classpath.push_back(dex_file_with_checksum[0]);
159 info->checksums.push_back(checksum);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700160 }
161 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700162
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000163 if (class_loader_spec[class_loader_spec.length() - 1] == kClassLoaderSharedLibraryClosingMark) {
164 size_t start_index = class_loader_spec.find_first_of(kClassLoaderSharedLibraryOpeningMark);
165 if (start_index == std::string::npos) {
166 return nullptr;
167 }
168 std::string shared_libraries_spec =
169 class_loader_spec.substr(start_index + 1, class_loader_spec.length() - start_index - 2);
170 std::vector<std::string> shared_libraries;
171 Split(shared_libraries_spec, kClassLoaderSharedLibrarySeparator, &shared_libraries);
172 for (const std::string& shared_library_spec : shared_libraries) {
173 std::unique_ptr<ClassLoaderInfo> shared_library(
174 ParseInternal(shared_library_spec, parse_checksums));
175 if (shared_library == nullptr) {
176 return nullptr;
177 }
178 info->shared_libraries.push_back(std::move(shared_library));
179 }
180 }
181
182 return info;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700183}
184
185// Extracts the class loader type from the given spec.
186// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
187// recognized.
188ClassLoaderContext::ClassLoaderType
189ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
190 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
191 for (const ClassLoaderType& type : kValidTypes) {
192 const char* type_str = GetClassLoaderTypeName(type);
193 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
194 return type;
195 }
196 }
197 return kInvalidClassLoader;
198}
199
200// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
201// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
202// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700203bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700204 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700205 // By default we load the dex files in a PathClassLoader.
206 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
207 // tests)
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000208 class_loader_chain_.reset(new ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700209 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700210 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700211
Calin Juravle87e2cb62017-06-13 21:48:45 -0700212 // Stop early if we detect the special shared library, which may be passed as the classpath
213 // for dex2oat when we want to skip the shared libraries check.
214 if (spec == OatFile::kSpecialSharedLibrary) {
215 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
216 special_shared_library_ = true;
217 return true;
218 }
219
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000220 CHECK(class_loader_chain_ == nullptr);
221 class_loader_chain_.reset(ParseInternal(spec, parse_checksums));
222 return class_loader_chain_ != nullptr;
223}
Calin Juravle87e2cb62017-06-13 21:48:45 -0700224
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000225ClassLoaderContext::ClassLoaderInfo* ClassLoaderContext::ParseInternal(
226 const std::string& spec, bool parse_checksums) {
227 CHECK(!spec.empty());
228 CHECK_NE(spec, OatFile::kSpecialSharedLibrary);
229 std::string remaining = spec;
230 std::unique_ptr<ClassLoaderInfo> first(nullptr);
231 ClassLoaderInfo* previous_iteration = nullptr;
232 while (!remaining.empty()) {
233 std::string class_loader_spec;
234 size_t first_class_loader_separator = remaining.find_first_of(kClassLoaderSeparator);
235 size_t first_shared_library_open =
236 remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark);
237 if (first_class_loader_separator == std::string::npos) {
238 // Only one class loader, for example:
239 // PCL[...]
240 class_loader_spec = remaining;
241 remaining = "";
242 } else if ((first_shared_library_open == std::string::npos) ||
243 (first_shared_library_open > first_class_loader_separator)) {
244 // We found a class loader spec without shared libraries, for example:
245 // PCL[...];PCL[...]{...}
246 class_loader_spec = remaining.substr(0, first_class_loader_separator);
247 remaining = remaining.substr(first_class_loader_separator + 1,
248 remaining.size() - first_class_loader_separator - 1);
249 } else {
250 // The class loader spec contains shared libraries. Find the matching closing
251 // shared library marker for it.
252
253 // Counter of opened shared library marker we've encountered so far.
254 uint32_t counter = 1;
255 // The index at which we're operating in the loop.
256 uint32_t string_index = first_shared_library_open + 1;
257 while (counter != 0) {
258 size_t shared_library_close =
259 remaining.find_first_of(kClassLoaderSharedLibraryClosingMark, string_index);
260 size_t shared_library_open =
261 remaining.find_first_of(kClassLoaderSharedLibraryOpeningMark, string_index);
262 if (shared_library_close == std::string::npos) {
263 // No matching closing market. Return an error.
264 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
265 return nullptr;
266 }
267
268 if ((shared_library_open == std::string::npos) ||
269 (shared_library_close < shared_library_open)) {
270 // We have seen a closing marker. Decrement the counter.
271 --counter;
272 if (counter == 0) {
273 // Found the matching closing marker.
274 class_loader_spec = remaining.substr(0, shared_library_close + 1);
275
276 // Compute the remaining string to analyze.
277 if (remaining.size() == shared_library_close + 1) {
278 remaining = "";
279 } else if ((remaining.size() == shared_library_close + 2) ||
280 (remaining.at(shared_library_close + 1) != kClassLoaderSeparator)) {
281 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
282 return nullptr;
283 } else {
284 remaining = remaining.substr(shared_library_close + 2,
285 remaining.size() - shared_library_close - 2);
286 }
287 } else {
288 // Move the search index forward.
289 string_index = shared_library_close + 1;
290 }
291 } else {
292 // New nested opening marker. Increment the counter and move the search
293 // index after the marker.
294 ++counter;
295 string_index = shared_library_open + 1;
296 }
297 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700298 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000299
300 std::unique_ptr<ClassLoaderInfo> info =
301 ParseClassLoaderSpec(class_loader_spec, parse_checksums);
302 if (info == nullptr) {
303 LOG(ERROR) << "Invalid class loader spec: " << class_loader_spec;
304 return nullptr;
305 }
306 if (first == nullptr) {
307 first.reset(info.release());
308 previous_iteration = first.get();
309 } else {
310 CHECK(previous_iteration != nullptr);
311 previous_iteration->parent.reset(info.release());
312 previous_iteration = previous_iteration->parent.get();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700313 }
314 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000315 return first.release();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700316}
317
318// Opens requested class path files and appends them to opened_dex_files. If the dex files have
319// been stripped, this opens them from their oat files (which get added to opened_oat_files).
320bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700321 if (dex_files_open_attempted_) {
322 // Do not attempt to re-open the files if we already tried.
323 return dex_files_open_result_;
324 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700325
326 dex_files_open_attempted_ = true;
327 // Assume we can open all dex files. If not, we will set this to false as we go.
328 dex_files_open_result_ = true;
329
330 if (special_shared_library_) {
331 // Nothing to open if the context is a special shared library.
332 return true;
333 }
334
335 // Note that we try to open all dex files even if some fail.
336 // We may get resource-only apks which we cannot load.
337 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
338 // no dex files. So that we can distinguish the real failures...
David Sehr013fd802018-01-11 22:55:24 -0800339 const ArtDexFileLoader dex_file_loader;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000340 std::vector<ClassLoaderInfo*> work_list;
Nicolas Geoffray9893c472018-11-13 15:39:53 +0000341 CHECK(class_loader_chain_ != nullptr);
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000342 work_list.push_back(class_loader_chain_.get());
343 while (!work_list.empty()) {
344 ClassLoaderInfo* info = work_list.back();
345 work_list.pop_back();
346 size_t opened_dex_files_index = info->opened_dex_files.size();
347 for (const std::string& cp_elem : info->classpath) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700348 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000349 std::string location = cp_elem;
350 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000351 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700352 }
353
Calin Juravle87e2cb62017-06-13 21:48:45 -0700354 std::string error_msg;
355 // When opening the dex files from the context we expect their checksum to match their
356 // contents. So pass true to verify_checksum.
David Sehr013fd802018-01-11 22:55:24 -0800357 if (!dex_file_loader.Open(location.c_str(),
358 location.c_str(),
359 Runtime::Current()->IsVerificationEnabled(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700360 /*verify_checksum=*/ true,
David Sehr013fd802018-01-11 22:55:24 -0800361 &error_msg,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000362 &info->opened_dex_files)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700363 // If we fail to open the dex file because it's been stripped, try to open the dex file
364 // from its corresponding oat file.
365 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
366 // (for example, if the pre-build is only quicken and we want to re-compile it
367 // speed-profile).
368 // TODO(calin): Use the vdex directly instead of going through the oat file.
369 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
370 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
371 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
372 if (oat_file != nullptr &&
373 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000374 info->opened_oat_files.push_back(std::move(oat_file));
375 info->opened_dex_files.insert(info->opened_dex_files.end(),
376 std::make_move_iterator(oat_dex_files.begin()),
377 std::make_move_iterator(oat_dex_files.end()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700378 } else {
379 LOG(WARNING) << "Could not open dex files from location: " << location;
380 dex_files_open_result_ = false;
381 }
382 }
383 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700384
385 // We finished opening the dex files from the classpath.
386 // Now update the classpath and the checksum with the locations of the dex files.
387 //
388 // We do this because initially the classpath contains the paths of the dex files; and
389 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
390 // file paths with the actual dex locations being loaded.
391 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
392 // location in the class paths.
393 // Note that this will also remove the paths that could not be opened.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000394 info->original_classpath = std::move(info->classpath);
395 info->classpath.clear();
396 info->checksums.clear();
397 for (size_t k = opened_dex_files_index; k < info->opened_dex_files.size(); k++) {
398 std::unique_ptr<const DexFile>& dex = info->opened_dex_files[k];
399 info->classpath.push_back(dex->GetLocation());
400 info->checksums.push_back(dex->GetLocationChecksum());
Calin Juravlec5b215f2017-09-12 14:49:37 -0700401 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000402 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700403 }
404
405 return dex_files_open_result_;
406}
407
408bool ClassLoaderContext::RemoveLocationsFromClassPaths(
409 const dchecked_vector<std::string>& locations) {
410 CHECK(!dex_files_open_attempted_)
411 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
412
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000413 if (class_loader_chain_ == nullptr) {
414 return false;
415 }
416
Calin Juravle87e2cb62017-06-13 21:48:45 -0700417 std::set<std::string> canonical_locations;
418 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700419 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700420 }
421 bool removed_locations = false;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000422 std::vector<ClassLoaderInfo*> work_list;
423 work_list.push_back(class_loader_chain_.get());
424 while (!work_list.empty()) {
425 ClassLoaderInfo* info = work_list.back();
426 work_list.pop_back();
427 size_t initial_size = info->classpath.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700428 auto kept_it = std::remove_if(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000429 info->classpath.begin(),
430 info->classpath.end(),
Calin Juravle87e2cb62017-06-13 21:48:45 -0700431 [canonical_locations](const std::string& location) {
432 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700433 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700434 });
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000435 info->classpath.erase(kept_it, info->classpath.end());
436 if (initial_size != info->classpath.size()) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700437 removed_locations = true;
438 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000439 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700440 }
441 return removed_locations;
442}
443
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700444std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700445 return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700446}
447
Mathieu Chartierc4440772018-04-16 14:40:56 -0700448std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
449 ClassLoaderContext* stored_context) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700450 return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700451}
452
453std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700454 bool for_dex2oat,
455 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700456 CheckDexFilesOpened("EncodeContextForOatFile");
457 if (special_shared_library_) {
458 return OatFile::kSpecialSharedLibrary;
459 }
460
Mathieu Chartierc4440772018-04-16 14:40:56 -0700461 if (stored_context != nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000462 DCHECK_EQ(GetParentChainSize(), stored_context->GetParentChainSize());
Mathieu Chartierc4440772018-04-16 14:40:56 -0700463 }
464
Calin Juravle7b0648a2017-07-07 18:40:50 -0700465 std::ostringstream out;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000466 if (class_loader_chain_ == nullptr) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700467 // We can get in this situation if the context was created with a class path containing the
468 // source dex files which were later removed (happens during run-tests).
469 out << GetClassLoaderTypeName(kPathClassLoader)
470 << kClassLoaderOpeningMark
471 << kClassLoaderClosingMark;
472 return out.str();
473 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700474
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000475 EncodeContextInternal(
476 *class_loader_chain_,
477 base_dir,
478 for_dex2oat,
479 (stored_context == nullptr ? nullptr : stored_context->class_loader_chain_.get()),
480 out);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700481 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700482}
483
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000484void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info,
485 const std::string& base_dir,
486 bool for_dex2oat,
487 ClassLoaderInfo* stored_info,
488 std::ostringstream& out) const {
489 out << GetClassLoaderTypeName(info.type);
490 out << kClassLoaderOpeningMark;
491 std::set<std::string> seen_locations;
492 SafeMap<std::string, std::string> remap;
493 if (stored_info != nullptr) {
494 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
495 // Note that we don't care if the same name appears twice.
496 remap.Put(info.original_classpath[k], stored_info->classpath[k]);
497 }
498 }
499 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
500 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
501 if (for_dex2oat) {
502 // dex2oat only needs the base location. It cannot accept multidex locations.
503 // So ensure we only add each file once.
504 bool new_insert = seen_locations.insert(
505 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
506 if (!new_insert) {
507 continue;
508 }
509 }
510 std::string location = dex_file->GetLocation();
511 // If there is a stored class loader remap, fix up the multidex strings.
512 if (!remap.empty()) {
513 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
514 auto it = remap.find(base_dex_location);
515 CHECK(it != remap.end()) << base_dex_location;
516 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
517 }
518 if (k > 0) {
519 out << kClasspathSeparator;
520 }
521 // Find paths that were relative and convert them back from absolute.
522 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
523 out << location.substr(base_dir.length() + 1).c_str();
524 } else {
525 out << location.c_str();
526 }
527 // dex2oat does not need the checksums.
528 if (!for_dex2oat) {
529 out << kDexFileChecksumSeparator;
530 out << dex_file->GetLocationChecksum();
531 }
532 }
533 out << kClassLoaderClosingMark;
534
535 if (!info.shared_libraries.empty()) {
536 out << kClassLoaderSharedLibraryOpeningMark;
537 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
538 if (i > 0) {
539 out << kClassLoaderSharedLibrarySeparator;
540 }
541 EncodeContextInternal(
542 *info.shared_libraries[i].get(),
543 base_dir,
544 for_dex2oat,
545 (stored_info == nullptr ? nullptr : stored_info->shared_libraries[i].get()),
546 out);
547 }
548 out << kClassLoaderSharedLibraryClosingMark;
549 }
550 if (info.parent != nullptr) {
551 out << kClassLoaderSeparator;
552 EncodeContextInternal(
553 *info.parent.get(),
554 base_dir,
555 for_dex2oat,
556 (stored_info == nullptr ? nullptr : stored_info->parent.get()),
557 out);
558 }
559}
560
561// Returns the WellKnownClass for the given class loader type.
562static jclass GetClassLoaderClass(ClassLoaderContext::ClassLoaderType type) {
563 switch (type) {
564 case ClassLoaderContext::kPathClassLoader:
565 return WellKnownClasses::dalvik_system_PathClassLoader;
566 case ClassLoaderContext::kDelegateLastClassLoader:
567 return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
568 case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch.
569 }
570 LOG(FATAL) << "Invalid class loader type " << type;
571 UNREACHABLE();
572}
573
574static jobject CreateClassLoaderInternal(Thread* self,
575 const ClassLoaderContext::ClassLoaderInfo& info)
576 REQUIRES_SHARED(Locks::mutator_lock_) {
577 CHECK(info.shared_libraries.empty()) << "Class loader shared library not implemented yet";
578 jobject parent = nullptr;
579 if (info.parent != nullptr) {
580 parent = CreateClassLoaderInternal(self, *info.parent.get());
581 }
582 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
583 info.opened_dex_files);
584 return Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
585 self,
586 class_path_files,
587 GetClassLoaderClass(info.type),
588 parent);
589}
590
Calin Juravle87e2cb62017-06-13 21:48:45 -0700591jobject ClassLoaderContext::CreateClassLoader(
592 const std::vector<const DexFile*>& compilation_sources) const {
593 CheckDexFilesOpened("CreateClassLoader");
594
595 Thread* self = Thread::Current();
596 ScopedObjectAccess soa(self);
597
Calin Juravlec79470d2017-07-12 17:37:42 -0700598 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700599
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000600 if (class_loader_chain_ == nullptr) {
Calin Juravlec79470d2017-07-12 17:37:42 -0700601 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700602 }
603
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000604 // Create the class loader of the parent.
605 jobject parent = nullptr;
606 if (class_loader_chain_->parent != nullptr) {
607 parent = CreateClassLoaderInternal(self, *class_loader_chain_->parent.get());
Calin Juravlec79470d2017-07-12 17:37:42 -0700608 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700609
Calin Juravlec79470d2017-07-12 17:37:42 -0700610 // We set up all the parents. Move on to create the first class loader.
611 // Its classpath comes first, followed by compilation sources. This ensures that whenever
612 // we need to resolve classes from it the classpath elements come first.
613
614 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000615 class_loader_chain_->opened_dex_files);
Calin Juravlec79470d2017-07-12 17:37:42 -0700616 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000617 compilation_sources.begin(),
618 compilation_sources.end());
Calin Juravlec79470d2017-07-12 17:37:42 -0700619
620 return class_linker->CreateWellKnownClassLoader(
621 self,
622 first_class_loader_classpath,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000623 GetClassLoaderClass(class_loader_chain_->type),
624 parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700625}
626
627std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
628 CheckDexFilesOpened("FlattenOpenedDexFiles");
629
630 std::vector<const DexFile*> result;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000631 if (class_loader_chain_ == nullptr) {
632 return result;
633 }
634 std::vector<ClassLoaderInfo*> work_list;
635 work_list.push_back(class_loader_chain_.get());
636 while (!work_list.empty()) {
637 ClassLoaderInfo* info = work_list.back();
638 work_list.pop_back();
639 for (const std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700640 result.push_back(dex_file.get());
641 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000642 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700643 }
644 return result;
645}
646
647const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
648 switch (type) {
649 case kPathClassLoader: return kPathClassLoaderString;
650 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
651 default:
652 LOG(FATAL) << "Invalid class loader type " << type;
653 UNREACHABLE();
654 }
655}
656
657void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
658 CHECK(dex_files_open_attempted_)
659 << "Dex files were not successfully opened before the call to " << calling_method
660 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
661}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700662
Calin Juravle57d0acc2017-07-11 17:41:30 -0700663// Collects the dex files from the give Java dex_file object. Only the dex files with
664// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
665static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
666 ArtField* const cookie_field,
667 std::vector<const DexFile*>* out_dex_files)
668 REQUIRES_SHARED(Locks::mutator_lock_) {
669 if (java_dex_file == nullptr) {
670 return true;
671 }
672 // On the Java side, the dex files are stored in the cookie field.
673 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
674 if (long_array == nullptr) {
675 // This should never happen so log a warning.
676 LOG(ERROR) << "Unexpected null cookie";
677 return false;
678 }
679 int32_t long_array_size = long_array->GetLength();
680 // Index 0 from the long array stores the oat file. The dex files start at index 1.
681 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +0100682 const DexFile* cp_dex_file =
683 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700684 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
685 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
686 // cp_dex_file can be null.
687 out_dex_files->push_back(cp_dex_file);
688 }
689 }
690 return true;
691}
692
693// Collects all the dex files loaded by the given class loader.
694// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
695// a null list of dex elements or a null dex element).
696static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
697 Handle<mirror::ClassLoader> class_loader,
698 std::vector<const DexFile*>* out_dex_files)
699 REQUIRES_SHARED(Locks::mutator_lock_) {
700 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
701
702 // All supported class loaders inherit from BaseDexClassLoader.
703 // We need to get the DexPathList and loop through it.
704 ArtField* const cookie_field =
705 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
706 ArtField* const dex_file_field =
707 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
708 ObjPtr<mirror::Object> dex_path_list =
709 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
710 GetObject(class_loader.Get());
711 CHECK(cookie_field != nullptr);
712 CHECK(dex_file_field != nullptr);
713 if (dex_path_list == nullptr) {
714 // This may be null if the current class loader is under construction and it does not
715 // have its fields setup yet.
716 return true;
717 }
718 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
719 ObjPtr<mirror::Object> dex_elements_obj =
720 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
721 GetObject(dex_path_list);
722 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
723 // at the mCookie which is a DexFile vector.
724 if (dex_elements_obj == nullptr) {
725 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
726 // and assume we have no elements.
727 return true;
728 } else {
729 StackHandleScope<1> hs(soa.Self());
730 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
731 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
732 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
733 mirror::Object* element = dex_elements->GetWithoutChecks(i);
734 if (element == nullptr) {
735 // Should never happen, log an error and break.
736 // TODO(calin): It's unclear if we should just assert here.
737 // This code was propagated to oat_file_manager from the class linker where it would
738 // throw a NPE. For now, return false which will mark this class loader as unsupported.
739 LOG(ERROR) << "Unexpected null in the dex element list";
740 return false;
741 }
742 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
743 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
744 return false;
745 }
746 }
747 }
748
749 return true;
750}
751
752static bool GetDexFilesFromDexElementsArray(
753 ScopedObjectAccessAlreadyRunnable& soa,
754 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
755 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
756 DCHECK(dex_elements != nullptr);
757
758 ArtField* const cookie_field =
759 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
760 ArtField* const dex_file_field =
761 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
762 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
763 WellKnownClasses::dalvik_system_DexPathList__Element);
764 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
765 WellKnownClasses::dalvik_system_DexFile);
766
767 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
768 mirror::Object* element = dex_elements->GetWithoutChecks(i);
769 // We can hit a null element here because this is invoked with a partially filled dex_elements
770 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
771 // list of dex files which were opened before.
772 if (element == nullptr) {
773 continue;
774 }
775
776 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
777 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
778 // a historical glitch. All the java code opens dex files using an array of Elements.
779 ObjPtr<mirror::Object> dex_file;
780 if (element_class == element->GetClass()) {
781 dex_file = dex_file_field->GetObject(element);
782 } else if (dexfile_class == element->GetClass()) {
783 dex_file = element;
784 } else {
785 LOG(ERROR) << "Unsupported element in dex_elements: "
786 << mirror::Class::PrettyClass(element->GetClass());
787 return false;
788 }
789
790 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
791 return false;
792 }
793 }
794 return true;
795}
796
797// Adds the `class_loader` info to the `context`.
798// The dex file present in `dex_elements` array (if not null) will be added at the end of
799// the classpath.
800// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
801// BootClassLoader. Note that the class loader chain is expected to be short.
802bool ClassLoaderContext::AddInfoToContextFromClassLoader(
803 ScopedObjectAccessAlreadyRunnable& soa,
804 Handle<mirror::ClassLoader> class_loader,
805 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
806 REQUIRES_SHARED(Locks::mutator_lock_) {
807 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
808 // Nothing to do for the boot class loader as we don't add its dex files to the context.
809 return true;
810 }
811
812 ClassLoaderContext::ClassLoaderType type;
813 if (IsPathOrDexClassLoader(soa, class_loader)) {
814 type = kPathClassLoader;
815 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
816 type = kDelegateLastClassLoader;
817 } else {
818 LOG(WARNING) << "Unsupported class loader";
819 return false;
820 }
821
822 // Inspect the class loader for its dex files.
823 std::vector<const DexFile*> dex_files_loaded;
824 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
825
826 // If we have a dex_elements array extract its dex elements now.
827 // This is used in two situations:
828 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
829 // passing the list of already open dex files each time. This ensures that we see the
830 // correct context even if the ClassLoader under construction is not fully build.
831 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
832 // appending them to the current class loader. When the new code paths are loaded in
833 // BaseDexClassLoader, the paths already present in the class loader will be passed
834 // in the dex_elements array.
835 if (dex_elements != nullptr) {
836 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
837 }
838
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000839 ClassLoaderInfo* info = new ClassLoaderContext::ClassLoaderInfo(type);
840 if (class_loader_chain_ == nullptr) {
841 class_loader_chain_.reset(info);
842 } else {
843 ClassLoaderInfo* child = class_loader_chain_.get();
844 while (child->parent != nullptr) {
845 child = child->parent.get();
846 }
847 child->parent.reset(info);
848 }
849
Calin Juravle57d0acc2017-07-11 17:41:30 -0700850 for (const DexFile* dex_file : dex_files_loaded) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000851 info->classpath.push_back(dex_file->GetLocation());
852 info->checksums.push_back(dex_file->GetLocationChecksum());
853 info->opened_dex_files.emplace_back(dex_file);
Calin Juravle57d0acc2017-07-11 17:41:30 -0700854 }
855
856 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
857
858 StackHandleScope<1> hs(Thread::Current());
859 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
860
861 // Note that dex_elements array is null here. The elements are considered to be part of the
862 // current class loader and are not passed to the parents.
863 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
864 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
865}
866
867std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
868 jobject class_loader,
869 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700870 CHECK(class_loader != nullptr);
871
Calin Juravle57d0acc2017-07-11 17:41:30 -0700872 ScopedObjectAccess soa(Thread::Current());
873 StackHandleScope<2> hs(soa.Self());
874 Handle<mirror::ClassLoader> h_class_loader =
875 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
876 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
877 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
878
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700879 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/ false));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700880 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
881 return result;
882 } else {
883 return nullptr;
884 }
885}
886
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700887static bool IsAbsoluteLocation(const std::string& location) {
888 return !location.empty() && location[0] == '/';
889}
890
Mathieu Chartieradc90862018-05-11 13:03:06 -0700891ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
892 const std::string& context_spec,
893 bool verify_names,
894 bool verify_checksums) const {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700895 if (verify_names || verify_checksums) {
896 DCHECK(dex_files_open_attempted_);
897 DCHECK(dex_files_open_result_);
898 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700899
Calin Juravle3f918642017-07-11 19:04:20 -0700900 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700901 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -0700902 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700903 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700904 }
905
Calin Juravlec5b215f2017-09-12 14:49:37 -0700906 // Special shared library contexts always match. They essentially instruct the runtime
907 // to ignore the class path check because the oat file is known to be loaded in different
908 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
909 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700910 if (expected_context.special_shared_library_) {
911 // Special case where we are the only entry in the class path.
Nicolas Geoffray9893c472018-11-13 15:39:53 +0000912 if (class_loader_chain_ != nullptr &&
913 class_loader_chain_->parent == nullptr &&
914 class_loader_chain_->classpath.size() == 0) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700915 return VerificationResult::kVerifies;
916 }
917 return VerificationResult::kForcedToSkipChecks;
918 } else if (special_shared_library_) {
919 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -0700920 }
921
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000922 ClassLoaderInfo* info = class_loader_chain_.get();
923 ClassLoaderInfo* expected = expected_context.class_loader_chain_.get();
924 CHECK(info != nullptr);
925 CHECK(expected != nullptr);
926 if (!ClassLoaderInfoMatch(*info, *expected, context_spec, verify_names, verify_checksums)) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700927 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700928 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000929 return VerificationResult::kVerifies;
930}
Calin Juravle3f918642017-07-11 19:04:20 -0700931
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000932bool ClassLoaderContext::ClassLoaderInfoMatch(
933 const ClassLoaderInfo& info,
934 const ClassLoaderInfo& expected_info,
935 const std::string& context_spec,
936 bool verify_names,
937 bool verify_checksums) const {
938 if (info.type != expected_info.type) {
939 LOG(WARNING) << "ClassLoaderContext type mismatch"
940 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
941 << ", found=" << GetClassLoaderTypeName(info.type)
942 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
943 return false;
944 }
945 if (info.classpath.size() != expected_info.classpath.size()) {
946 LOG(WARNING) << "ClassLoaderContext classpath size mismatch"
947 << ". expected=" << expected_info.classpath.size()
948 << ", found=" << info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700949 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000950 return false;
951 }
Calin Juravle3f918642017-07-11 19:04:20 -0700952
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000953 if (verify_checksums) {
954 DCHECK_EQ(info.classpath.size(), info.checksums.size());
955 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
956 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700957
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000958 if (verify_names) {
Calin Juravle3f918642017-07-11 19:04:20 -0700959 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700960 // Compute the dex location that must be compared.
961 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
962 // because even if they refer to the same file, one could be encoded as a relative location
963 // and the other as an absolute one.
964 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
965 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
966 std::string dex_name;
967 std::string expected_dex_name;
968
969 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
970 // If both locations are absolute or relative then compare them as they are.
971 // This is usually the case for: shared libraries and secondary dex files.
972 dex_name = info.classpath[k];
973 expected_dex_name = expected_info.classpath[k];
974 } else if (is_dex_name_absolute) {
975 // The runtime name is absolute but the compiled name (the expected one) is relative.
976 // This is the case for split apks which depend on base or on other splits.
977 dex_name = info.classpath[k];
978 expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
979 info.classpath[k].c_str(), expected_info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +0000980 } else if (is_expected_dex_name_absolute) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700981 // The runtime name is relative but the compiled name is absolute.
982 // There is no expected use case that would end up here as dex files are always loaded
983 // with their absolute location. However, be tolerant and do the best effort (in case
984 // there are unexpected new use case...).
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700985 dex_name = OatFile::ResolveRelativeEncodedDexLocation(
986 expected_info.classpath[k].c_str(), info.classpath[k]);
987 expected_dex_name = expected_info.classpath[k];
Calin Juravle92003fe2017-09-06 02:22:57 +0000988 } else {
989 // Both locations are relative. In this case there's not much we can be sure about
990 // except that the names are the same. The checksum will ensure that the files are
991 // are same. This should not happen outside testing and manual invocations.
992 dex_name = info.classpath[k];
993 expected_dex_name = expected_info.classpath[k];
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700994 }
995
996 // Compare the locations.
997 if (dex_name != expected_dex_name) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000998 LOG(WARNING) << "ClassLoaderContext classpath element mismatch"
Calin Juravle3f918642017-07-11 19:04:20 -0700999 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -07001000 << ", found=" << info.classpath[k]
1001 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001002 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001003 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001004
1005 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -07001006 if (info.checksums[k] != expected_info.checksums[k]) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001007 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch"
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001008 << ". expected=" << expected_info.checksums[k]
1009 << ", found=" << info.checksums[k]
1010 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001011 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001012 }
1013 }
1014 }
Calin Juravle3f918642017-07-11 19:04:20 -07001015
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001016 if (info.shared_libraries.size() != expected_info.shared_libraries.size()) {
1017 LOG(WARNING) << "ClassLoaderContext shared library size mismatch. "
1018 << "Expected=" << expected_info.classpath.size()
1019 << ", found=" << info.classpath.size()
1020 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1021 return false;
Calin Juravlec79470d2017-07-12 17:37:42 -07001022 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001023 for (size_t i = 0; i < info.shared_libraries.size(); ++i) {
1024 if (!ClassLoaderInfoMatch(*info.shared_libraries[i].get(),
1025 *expected_info.shared_libraries[i].get(),
1026 context_spec,
1027 verify_names,
1028 verify_checksums)) {
1029 return false;
1030 }
1031 }
1032 if (info.parent.get() == nullptr) {
1033 if (expected_info.parent.get() != nullptr) {
1034 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1035 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1036 return false;
1037 }
1038 return true;
1039 } else if (expected_info.parent.get() == nullptr) {
1040 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1041 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1042 return false;
1043 } else {
1044 return ClassLoaderInfoMatch(*info.parent.get(),
1045 *expected_info.parent.get(),
1046 context_spec,
1047 verify_names,
1048 verify_checksums);
1049 }
Calin Juravlec79470d2017-07-12 17:37:42 -07001050}
1051
Calin Juravle87e2cb62017-06-13 21:48:45 -07001052} // namespace art