blob: de9fe221ff5be02e52c3dc47285a5b34a3a114de [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;
341 work_list.push_back(class_loader_chain_.get());
342 while (!work_list.empty()) {
343 ClassLoaderInfo* info = work_list.back();
344 work_list.pop_back();
345 size_t opened_dex_files_index = info->opened_dex_files.size();
346 for (const std::string& cp_elem : info->classpath) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700347 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000348 std::string location = cp_elem;
349 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000350 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700351 }
352
Calin Juravle87e2cb62017-06-13 21:48:45 -0700353 std::string error_msg;
354 // When opening the dex files from the context we expect their checksum to match their
355 // contents. So pass true to verify_checksum.
David Sehr013fd802018-01-11 22:55:24 -0800356 if (!dex_file_loader.Open(location.c_str(),
357 location.c_str(),
358 Runtime::Current()->IsVerificationEnabled(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700359 /*verify_checksum=*/ true,
David Sehr013fd802018-01-11 22:55:24 -0800360 &error_msg,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000361 &info->opened_dex_files)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700362 // If we fail to open the dex file because it's been stripped, try to open the dex file
363 // from its corresponding oat file.
364 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
365 // (for example, if the pre-build is only quicken and we want to re-compile it
366 // speed-profile).
367 // TODO(calin): Use the vdex directly instead of going through the oat file.
368 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
369 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
370 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
371 if (oat_file != nullptr &&
372 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000373 info->opened_oat_files.push_back(std::move(oat_file));
374 info->opened_dex_files.insert(info->opened_dex_files.end(),
375 std::make_move_iterator(oat_dex_files.begin()),
376 std::make_move_iterator(oat_dex_files.end()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700377 } else {
378 LOG(WARNING) << "Could not open dex files from location: " << location;
379 dex_files_open_result_ = false;
380 }
381 }
382 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700383
384 // We finished opening the dex files from the classpath.
385 // Now update the classpath and the checksum with the locations of the dex files.
386 //
387 // We do this because initially the classpath contains the paths of the dex files; and
388 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
389 // file paths with the actual dex locations being loaded.
390 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
391 // location in the class paths.
392 // Note that this will also remove the paths that could not be opened.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000393 info->original_classpath = std::move(info->classpath);
394 info->classpath.clear();
395 info->checksums.clear();
396 for (size_t k = opened_dex_files_index; k < info->opened_dex_files.size(); k++) {
397 std::unique_ptr<const DexFile>& dex = info->opened_dex_files[k];
398 info->classpath.push_back(dex->GetLocation());
399 info->checksums.push_back(dex->GetLocationChecksum());
Calin Juravlec5b215f2017-09-12 14:49:37 -0700400 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000401 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700402 }
403
404 return dex_files_open_result_;
405}
406
407bool ClassLoaderContext::RemoveLocationsFromClassPaths(
408 const dchecked_vector<std::string>& locations) {
409 CHECK(!dex_files_open_attempted_)
410 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
411
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000412 if (class_loader_chain_ == nullptr) {
413 return false;
414 }
415
Calin Juravle87e2cb62017-06-13 21:48:45 -0700416 std::set<std::string> canonical_locations;
417 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700418 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700419 }
420 bool removed_locations = false;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000421 std::vector<ClassLoaderInfo*> work_list;
422 work_list.push_back(class_loader_chain_.get());
423 while (!work_list.empty()) {
424 ClassLoaderInfo* info = work_list.back();
425 work_list.pop_back();
426 size_t initial_size = info->classpath.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700427 auto kept_it = std::remove_if(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000428 info->classpath.begin(),
429 info->classpath.end(),
Calin Juravle87e2cb62017-06-13 21:48:45 -0700430 [canonical_locations](const std::string& location) {
431 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700432 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700433 });
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000434 info->classpath.erase(kept_it, info->classpath.end());
435 if (initial_size != info->classpath.size()) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700436 removed_locations = true;
437 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000438 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700439 }
440 return removed_locations;
441}
442
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700443std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700444 return EncodeContext(base_dir, /*for_dex2oat=*/ true, /*stored_context=*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700445}
446
Mathieu Chartierc4440772018-04-16 14:40:56 -0700447std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
448 ClassLoaderContext* stored_context) const {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700449 return EncodeContext(base_dir, /*for_dex2oat=*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700450}
451
452std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700453 bool for_dex2oat,
454 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700455 CheckDexFilesOpened("EncodeContextForOatFile");
456 if (special_shared_library_) {
457 return OatFile::kSpecialSharedLibrary;
458 }
459
Mathieu Chartierc4440772018-04-16 14:40:56 -0700460 if (stored_context != nullptr) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000461 DCHECK_EQ(GetParentChainSize(), stored_context->GetParentChainSize());
Mathieu Chartierc4440772018-04-16 14:40:56 -0700462 }
463
Calin Juravle7b0648a2017-07-07 18:40:50 -0700464 std::ostringstream out;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000465 if (class_loader_chain_ == nullptr) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700466 // We can get in this situation if the context was created with a class path containing the
467 // source dex files which were later removed (happens during run-tests).
468 out << GetClassLoaderTypeName(kPathClassLoader)
469 << kClassLoaderOpeningMark
470 << kClassLoaderClosingMark;
471 return out.str();
472 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700473
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000474 EncodeContextInternal(
475 *class_loader_chain_,
476 base_dir,
477 for_dex2oat,
478 (stored_context == nullptr ? nullptr : stored_context->class_loader_chain_.get()),
479 out);
Calin Juravle7b0648a2017-07-07 18:40:50 -0700480 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700481}
482
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000483void ClassLoaderContext::EncodeContextInternal(const ClassLoaderInfo& info,
484 const std::string& base_dir,
485 bool for_dex2oat,
486 ClassLoaderInfo* stored_info,
487 std::ostringstream& out) const {
488 out << GetClassLoaderTypeName(info.type);
489 out << kClassLoaderOpeningMark;
490 std::set<std::string> seen_locations;
491 SafeMap<std::string, std::string> remap;
492 if (stored_info != nullptr) {
493 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
494 // Note that we don't care if the same name appears twice.
495 remap.Put(info.original_classpath[k], stored_info->classpath[k]);
496 }
497 }
498 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
499 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
500 if (for_dex2oat) {
501 // dex2oat only needs the base location. It cannot accept multidex locations.
502 // So ensure we only add each file once.
503 bool new_insert = seen_locations.insert(
504 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
505 if (!new_insert) {
506 continue;
507 }
508 }
509 std::string location = dex_file->GetLocation();
510 // If there is a stored class loader remap, fix up the multidex strings.
511 if (!remap.empty()) {
512 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
513 auto it = remap.find(base_dex_location);
514 CHECK(it != remap.end()) << base_dex_location;
515 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
516 }
517 if (k > 0) {
518 out << kClasspathSeparator;
519 }
520 // Find paths that were relative and convert them back from absolute.
521 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
522 out << location.substr(base_dir.length() + 1).c_str();
523 } else {
524 out << location.c_str();
525 }
526 // dex2oat does not need the checksums.
527 if (!for_dex2oat) {
528 out << kDexFileChecksumSeparator;
529 out << dex_file->GetLocationChecksum();
530 }
531 }
532 out << kClassLoaderClosingMark;
533
534 if (!info.shared_libraries.empty()) {
535 out << kClassLoaderSharedLibraryOpeningMark;
536 for (uint32_t i = 0; i < info.shared_libraries.size(); ++i) {
537 if (i > 0) {
538 out << kClassLoaderSharedLibrarySeparator;
539 }
540 EncodeContextInternal(
541 *info.shared_libraries[i].get(),
542 base_dir,
543 for_dex2oat,
544 (stored_info == nullptr ? nullptr : stored_info->shared_libraries[i].get()),
545 out);
546 }
547 out << kClassLoaderSharedLibraryClosingMark;
548 }
549 if (info.parent != nullptr) {
550 out << kClassLoaderSeparator;
551 EncodeContextInternal(
552 *info.parent.get(),
553 base_dir,
554 for_dex2oat,
555 (stored_info == nullptr ? nullptr : stored_info->parent.get()),
556 out);
557 }
558}
559
560// Returns the WellKnownClass for the given class loader type.
561static jclass GetClassLoaderClass(ClassLoaderContext::ClassLoaderType type) {
562 switch (type) {
563 case ClassLoaderContext::kPathClassLoader:
564 return WellKnownClasses::dalvik_system_PathClassLoader;
565 case ClassLoaderContext::kDelegateLastClassLoader:
566 return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
567 case ClassLoaderContext::kInvalidClassLoader: break; // will fail after the switch.
568 }
569 LOG(FATAL) << "Invalid class loader type " << type;
570 UNREACHABLE();
571}
572
573static jobject CreateClassLoaderInternal(Thread* self,
574 const ClassLoaderContext::ClassLoaderInfo& info)
575 REQUIRES_SHARED(Locks::mutator_lock_) {
576 CHECK(info.shared_libraries.empty()) << "Class loader shared library not implemented yet";
577 jobject parent = nullptr;
578 if (info.parent != nullptr) {
579 parent = CreateClassLoaderInternal(self, *info.parent.get());
580 }
581 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
582 info.opened_dex_files);
583 return Runtime::Current()->GetClassLinker()->CreateWellKnownClassLoader(
584 self,
585 class_path_files,
586 GetClassLoaderClass(info.type),
587 parent);
588}
589
Calin Juravle87e2cb62017-06-13 21:48:45 -0700590jobject ClassLoaderContext::CreateClassLoader(
591 const std::vector<const DexFile*>& compilation_sources) const {
592 CheckDexFilesOpened("CreateClassLoader");
593
594 Thread* self = Thread::Current();
595 ScopedObjectAccess soa(self);
596
Calin Juravlec79470d2017-07-12 17:37:42 -0700597 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700598
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000599 if (class_loader_chain_ == nullptr) {
Calin Juravlec79470d2017-07-12 17:37:42 -0700600 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700601 }
602
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000603 // Create the class loader of the parent.
604 jobject parent = nullptr;
605 if (class_loader_chain_->parent != nullptr) {
606 parent = CreateClassLoaderInternal(self, *class_loader_chain_->parent.get());
Calin Juravlec79470d2017-07-12 17:37:42 -0700607 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700608
Calin Juravlec79470d2017-07-12 17:37:42 -0700609 // We set up all the parents. Move on to create the first class loader.
610 // Its classpath comes first, followed by compilation sources. This ensures that whenever
611 // we need to resolve classes from it the classpath elements come first.
612
613 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000614 class_loader_chain_->opened_dex_files);
Calin Juravlec79470d2017-07-12 17:37:42 -0700615 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000616 compilation_sources.begin(),
617 compilation_sources.end());
Calin Juravlec79470d2017-07-12 17:37:42 -0700618
619 return class_linker->CreateWellKnownClassLoader(
620 self,
621 first_class_loader_classpath,
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000622 GetClassLoaderClass(class_loader_chain_->type),
623 parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700624}
625
626std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
627 CheckDexFilesOpened("FlattenOpenedDexFiles");
628
629 std::vector<const DexFile*> result;
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000630 if (class_loader_chain_ == nullptr) {
631 return result;
632 }
633 std::vector<ClassLoaderInfo*> work_list;
634 work_list.push_back(class_loader_chain_.get());
635 while (!work_list.empty()) {
636 ClassLoaderInfo* info = work_list.back();
637 work_list.pop_back();
638 for (const std::unique_ptr<const DexFile>& dex_file : info->opened_dex_files) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700639 result.push_back(dex_file.get());
640 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000641 AddToWorkList(info, work_list);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700642 }
643 return result;
644}
645
646const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
647 switch (type) {
648 case kPathClassLoader: return kPathClassLoaderString;
649 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
650 default:
651 LOG(FATAL) << "Invalid class loader type " << type;
652 UNREACHABLE();
653 }
654}
655
656void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
657 CHECK(dex_files_open_attempted_)
658 << "Dex files were not successfully opened before the call to " << calling_method
659 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
660}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700661
Calin Juravle57d0acc2017-07-11 17:41:30 -0700662// Collects the dex files from the give Java dex_file object. Only the dex files with
663// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
664static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
665 ArtField* const cookie_field,
666 std::vector<const DexFile*>* out_dex_files)
667 REQUIRES_SHARED(Locks::mutator_lock_) {
668 if (java_dex_file == nullptr) {
669 return true;
670 }
671 // On the Java side, the dex files are stored in the cookie field.
672 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
673 if (long_array == nullptr) {
674 // This should never happen so log a warning.
675 LOG(ERROR) << "Unexpected null cookie";
676 return false;
677 }
678 int32_t long_array_size = long_array->GetLength();
679 // Index 0 from the long array stores the oat file. The dex files start at index 1.
680 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +0100681 const DexFile* cp_dex_file =
682 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700683 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
684 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
685 // cp_dex_file can be null.
686 out_dex_files->push_back(cp_dex_file);
687 }
688 }
689 return true;
690}
691
692// Collects all the dex files loaded by the given class loader.
693// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
694// a null list of dex elements or a null dex element).
695static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
696 Handle<mirror::ClassLoader> class_loader,
697 std::vector<const DexFile*>* out_dex_files)
698 REQUIRES_SHARED(Locks::mutator_lock_) {
699 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
700
701 // All supported class loaders inherit from BaseDexClassLoader.
702 // We need to get the DexPathList and loop through it.
703 ArtField* const cookie_field =
704 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
705 ArtField* const dex_file_field =
706 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
707 ObjPtr<mirror::Object> dex_path_list =
708 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
709 GetObject(class_loader.Get());
710 CHECK(cookie_field != nullptr);
711 CHECK(dex_file_field != nullptr);
712 if (dex_path_list == nullptr) {
713 // This may be null if the current class loader is under construction and it does not
714 // have its fields setup yet.
715 return true;
716 }
717 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
718 ObjPtr<mirror::Object> dex_elements_obj =
719 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
720 GetObject(dex_path_list);
721 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
722 // at the mCookie which is a DexFile vector.
723 if (dex_elements_obj == nullptr) {
724 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
725 // and assume we have no elements.
726 return true;
727 } else {
728 StackHandleScope<1> hs(soa.Self());
729 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
730 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
731 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
732 mirror::Object* element = dex_elements->GetWithoutChecks(i);
733 if (element == nullptr) {
734 // Should never happen, log an error and break.
735 // TODO(calin): It's unclear if we should just assert here.
736 // This code was propagated to oat_file_manager from the class linker where it would
737 // throw a NPE. For now, return false which will mark this class loader as unsupported.
738 LOG(ERROR) << "Unexpected null in the dex element list";
739 return false;
740 }
741 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
742 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
743 return false;
744 }
745 }
746 }
747
748 return true;
749}
750
751static bool GetDexFilesFromDexElementsArray(
752 ScopedObjectAccessAlreadyRunnable& soa,
753 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
754 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
755 DCHECK(dex_elements != nullptr);
756
757 ArtField* const cookie_field =
758 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
759 ArtField* const dex_file_field =
760 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
761 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
762 WellKnownClasses::dalvik_system_DexPathList__Element);
763 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
764 WellKnownClasses::dalvik_system_DexFile);
765
766 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
767 mirror::Object* element = dex_elements->GetWithoutChecks(i);
768 // We can hit a null element here because this is invoked with a partially filled dex_elements
769 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
770 // list of dex files which were opened before.
771 if (element == nullptr) {
772 continue;
773 }
774
775 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
776 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
777 // a historical glitch. All the java code opens dex files using an array of Elements.
778 ObjPtr<mirror::Object> dex_file;
779 if (element_class == element->GetClass()) {
780 dex_file = dex_file_field->GetObject(element);
781 } else if (dexfile_class == element->GetClass()) {
782 dex_file = element;
783 } else {
784 LOG(ERROR) << "Unsupported element in dex_elements: "
785 << mirror::Class::PrettyClass(element->GetClass());
786 return false;
787 }
788
789 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
790 return false;
791 }
792 }
793 return true;
794}
795
796// Adds the `class_loader` info to the `context`.
797// The dex file present in `dex_elements` array (if not null) will be added at the end of
798// the classpath.
799// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
800// BootClassLoader. Note that the class loader chain is expected to be short.
801bool ClassLoaderContext::AddInfoToContextFromClassLoader(
802 ScopedObjectAccessAlreadyRunnable& soa,
803 Handle<mirror::ClassLoader> class_loader,
804 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
805 REQUIRES_SHARED(Locks::mutator_lock_) {
806 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
807 // Nothing to do for the boot class loader as we don't add its dex files to the context.
808 return true;
809 }
810
811 ClassLoaderContext::ClassLoaderType type;
812 if (IsPathOrDexClassLoader(soa, class_loader)) {
813 type = kPathClassLoader;
814 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
815 type = kDelegateLastClassLoader;
816 } else {
817 LOG(WARNING) << "Unsupported class loader";
818 return false;
819 }
820
821 // Inspect the class loader for its dex files.
822 std::vector<const DexFile*> dex_files_loaded;
823 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
824
825 // If we have a dex_elements array extract its dex elements now.
826 // This is used in two situations:
827 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
828 // passing the list of already open dex files each time. This ensures that we see the
829 // correct context even if the ClassLoader under construction is not fully build.
830 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
831 // appending them to the current class loader. When the new code paths are loaded in
832 // BaseDexClassLoader, the paths already present in the class loader will be passed
833 // in the dex_elements array.
834 if (dex_elements != nullptr) {
835 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
836 }
837
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000838 ClassLoaderInfo* info = new ClassLoaderContext::ClassLoaderInfo(type);
839 if (class_loader_chain_ == nullptr) {
840 class_loader_chain_.reset(info);
841 } else {
842 ClassLoaderInfo* child = class_loader_chain_.get();
843 while (child->parent != nullptr) {
844 child = child->parent.get();
845 }
846 child->parent.reset(info);
847 }
848
Calin Juravle57d0acc2017-07-11 17:41:30 -0700849 for (const DexFile* dex_file : dex_files_loaded) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000850 info->classpath.push_back(dex_file->GetLocation());
851 info->checksums.push_back(dex_file->GetLocationChecksum());
852 info->opened_dex_files.emplace_back(dex_file);
Calin Juravle57d0acc2017-07-11 17:41:30 -0700853 }
854
855 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
856
857 StackHandleScope<1> hs(Thread::Current());
858 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
859
860 // Note that dex_elements array is null here. The elements are considered to be part of the
861 // current class loader and are not passed to the parents.
862 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
863 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
864}
865
866std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
867 jobject class_loader,
868 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700869 CHECK(class_loader != nullptr);
870
Calin Juravle57d0acc2017-07-11 17:41:30 -0700871 ScopedObjectAccess soa(Thread::Current());
872 StackHandleScope<2> hs(soa.Self());
873 Handle<mirror::ClassLoader> h_class_loader =
874 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
875 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
876 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
877
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700878 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files=*/ false));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700879 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
880 return result;
881 } else {
882 return nullptr;
883 }
884}
885
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700886static bool IsAbsoluteLocation(const std::string& location) {
887 return !location.empty() && location[0] == '/';
888}
889
Mathieu Chartieradc90862018-05-11 13:03:06 -0700890ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
891 const std::string& context_spec,
892 bool verify_names,
893 bool verify_checksums) const {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700894 if (verify_names || verify_checksums) {
895 DCHECK(dex_files_open_attempted_);
896 DCHECK(dex_files_open_result_);
897 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700898
Calin Juravle3f918642017-07-11 19:04:20 -0700899 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700900 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -0700901 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700902 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700903 }
904
Calin Juravlec5b215f2017-09-12 14:49:37 -0700905 // Special shared library contexts always match. They essentially instruct the runtime
906 // to ignore the class path check because the oat file is known to be loaded in different
907 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
908 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700909 if (expected_context.special_shared_library_) {
910 // Special case where we are the only entry in the class path.
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000911 if (class_loader_chain_->parent == nullptr && class_loader_chain_->classpath.size() == 0) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700912 return VerificationResult::kVerifies;
913 }
914 return VerificationResult::kForcedToSkipChecks;
915 } else if (special_shared_library_) {
916 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -0700917 }
918
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000919 ClassLoaderInfo* info = class_loader_chain_.get();
920 ClassLoaderInfo* expected = expected_context.class_loader_chain_.get();
921 CHECK(info != nullptr);
922 CHECK(expected != nullptr);
923 if (!ClassLoaderInfoMatch(*info, *expected, context_spec, verify_names, verify_checksums)) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700924 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700925 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000926 return VerificationResult::kVerifies;
927}
Calin Juravle3f918642017-07-11 19:04:20 -0700928
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000929bool ClassLoaderContext::ClassLoaderInfoMatch(
930 const ClassLoaderInfo& info,
931 const ClassLoaderInfo& expected_info,
932 const std::string& context_spec,
933 bool verify_names,
934 bool verify_checksums) const {
935 if (info.type != expected_info.type) {
936 LOG(WARNING) << "ClassLoaderContext type mismatch"
937 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
938 << ", found=" << GetClassLoaderTypeName(info.type)
939 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
940 return false;
941 }
942 if (info.classpath.size() != expected_info.classpath.size()) {
943 LOG(WARNING) << "ClassLoaderContext classpath size mismatch"
944 << ". expected=" << expected_info.classpath.size()
945 << ", found=" << info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700946 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000947 return false;
948 }
Calin Juravle3f918642017-07-11 19:04:20 -0700949
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000950 if (verify_checksums) {
951 DCHECK_EQ(info.classpath.size(), info.checksums.size());
952 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
953 }
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700954
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000955 if (verify_names) {
Calin Juravle3f918642017-07-11 19:04:20 -0700956 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700957 // Compute the dex location that must be compared.
958 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
959 // because even if they refer to the same file, one could be encoded as a relative location
960 // and the other as an absolute one.
961 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
962 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
963 std::string dex_name;
964 std::string expected_dex_name;
965
966 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
967 // If both locations are absolute or relative then compare them as they are.
968 // This is usually the case for: shared libraries and secondary dex files.
969 dex_name = info.classpath[k];
970 expected_dex_name = expected_info.classpath[k];
971 } else if (is_dex_name_absolute) {
972 // The runtime name is absolute but the compiled name (the expected one) is relative.
973 // This is the case for split apks which depend on base or on other splits.
974 dex_name = info.classpath[k];
975 expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
976 info.classpath[k].c_str(), expected_info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +0000977 } else if (is_expected_dex_name_absolute) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700978 // The runtime name is relative but the compiled name is absolute.
979 // There is no expected use case that would end up here as dex files are always loaded
980 // with their absolute location. However, be tolerant and do the best effort (in case
981 // there are unexpected new use case...).
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700982 dex_name = OatFile::ResolveRelativeEncodedDexLocation(
983 expected_info.classpath[k].c_str(), info.classpath[k]);
984 expected_dex_name = expected_info.classpath[k];
Calin Juravle92003fe2017-09-06 02:22:57 +0000985 } else {
986 // Both locations are relative. In this case there's not much we can be sure about
987 // except that the names are the same. The checksum will ensure that the files are
988 // are same. This should not happen outside testing and manual invocations.
989 dex_name = info.classpath[k];
990 expected_dex_name = expected_info.classpath[k];
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700991 }
992
993 // Compare the locations.
994 if (dex_name != expected_dex_name) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000995 LOG(WARNING) << "ClassLoaderContext classpath element mismatch"
Calin Juravle3f918642017-07-11 19:04:20 -0700996 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700997 << ", found=" << info.classpath[k]
998 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +0000999 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001000 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001001
1002 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -07001003 if (info.checksums[k] != expected_info.checksums[k]) {
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001004 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch"
Calin Juravle1e96a5d2017-09-05 17:10:48 -07001005 << ". expected=" << expected_info.checksums[k]
1006 << ", found=" << info.checksums[k]
1007 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001008 return false;
Calin Juravle3f918642017-07-11 19:04:20 -07001009 }
1010 }
1011 }
Calin Juravle3f918642017-07-11 19:04:20 -07001012
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001013 if (info.shared_libraries.size() != expected_info.shared_libraries.size()) {
1014 LOG(WARNING) << "ClassLoaderContext shared library size mismatch. "
1015 << "Expected=" << expected_info.classpath.size()
1016 << ", found=" << info.classpath.size()
1017 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1018 return false;
Calin Juravlec79470d2017-07-12 17:37:42 -07001019 }
Nicolas Geoffray06af3b42018-10-29 10:39:04 +00001020 for (size_t i = 0; i < info.shared_libraries.size(); ++i) {
1021 if (!ClassLoaderInfoMatch(*info.shared_libraries[i].get(),
1022 *expected_info.shared_libraries[i].get(),
1023 context_spec,
1024 verify_names,
1025 verify_checksums)) {
1026 return false;
1027 }
1028 }
1029 if (info.parent.get() == nullptr) {
1030 if (expected_info.parent.get() != nullptr) {
1031 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1032 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1033 return false;
1034 }
1035 return true;
1036 } else if (expected_info.parent.get() == nullptr) {
1037 LOG(WARNING) << "ClassLoaderContext parent mismatch. "
1038 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
1039 return false;
1040 } else {
1041 return ClassLoaderInfoMatch(*info.parent.get(),
1042 *expected_info.parent.get(),
1043 context_spec,
1044 verify_names,
1045 verify_checksums);
1046 }
Calin Juravlec79470d2017-07-12 17:37:42 -07001047}
1048
Calin Juravle87e2cb62017-06-13 21:48:45 -07001049} // namespace art