blob: 3ec5335a807b99b6177db036f65d5412b3e754a2 [file] [log] [blame]
Calin Juravle87e2cb62017-06-13 21:48:45 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "class_loader_context.h"
18
Calin Juravle57d0acc2017-07-11 17:41:30 -070019#include "art_field-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070020#include "base/dchecked_vector.h"
21#include "base/stl_util.h"
22#include "class_linker.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070023#include "class_loader_utils.h"
David Sehr9e734c72018-01-04 17:56:19 -080024#include "dex/dex_file.h"
25#include "dex/dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070026#include "handle_scope-inl.h"
27#include "jni_internal.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070028#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070029#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070030#include "runtime.h"
31#include "scoped_thread_state_change-inl.h"
32#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070033#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070034
35namespace art {
36
37static constexpr char kPathClassLoaderString[] = "PCL";
38static constexpr char kDelegateLastClassLoaderString[] = "DLC";
39static constexpr char kClassLoaderOpeningMark = '[';
40static constexpr char kClassLoaderClosingMark = ']';
Calin Juravle7b0648a2017-07-07 18:40:50 -070041static constexpr char kClassLoaderSeparator = ';';
42static constexpr char kClasspathSeparator = ':';
43static constexpr char kDexFileChecksumSeparator = '*';
Calin Juravle87e2cb62017-06-13 21:48:45 -070044
45ClassLoaderContext::ClassLoaderContext()
46 : special_shared_library_(false),
47 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070048 dex_files_open_result_(false),
Calin Juravle41acdc12017-07-18 17:45:32 -070049 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070050
51ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
52 : special_shared_library_(false),
53 dex_files_open_attempted_(true),
54 dex_files_open_result_(true),
55 owns_the_dex_files_(owns_the_dex_files) {}
56
57ClassLoaderContext::~ClassLoaderContext() {
58 if (!owns_the_dex_files_) {
59 // If the context does not own the dex/oat files release the unique pointers to
60 // make sure we do not de-allocate them.
61 for (ClassLoaderInfo& info : class_loader_chain_) {
62 for (std::unique_ptr<OatFile>& oat_file : info.opened_oat_files) {
63 oat_file.release();
64 }
65 for (std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
66 dex_file.release();
67 }
68 }
69 }
70}
Calin Juravle87e2cb62017-06-13 21:48:45 -070071
Calin Juravle19915892017-08-03 17:10:36 +000072std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
73 return Create("");
74}
75
Calin Juravle87e2cb62017-06-13 21:48:45 -070076std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
77 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
78 if (result->Parse(spec)) {
79 return result;
80 } else {
81 return nullptr;
82 }
83}
84
Calin Juravle7b0648a2017-07-07 18:40:50 -070085// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
86// The checksum part of the format is expected only if parse_cheksums is true.
Calin Juravle87e2cb62017-06-13 21:48:45 -070087bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
Calin Juravle7b0648a2017-07-07 18:40:50 -070088 ClassLoaderType class_loader_type,
89 bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -070090 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
91 size_t type_str_size = strlen(class_loader_type_str);
92
93 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
94
95 // Check the opening and closing markers.
96 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
97 return false;
98 }
99 if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
100 return false;
101 }
102
103 // At this point we know the format is ok; continue and extract the classpath.
104 // Note that class loaders with an empty class path are allowed.
105 std::string classpath = class_loader_spec.substr(type_str_size + 1,
106 class_loader_spec.length() - type_str_size - 2);
107
108 class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700109
110 if (!parse_checksums) {
111 Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
112 } else {
113 std::vector<std::string> classpath_elements;
114 Split(classpath, kClasspathSeparator, &classpath_elements);
115 for (const std::string& element : classpath_elements) {
116 std::vector<std::string> dex_file_with_checksum;
117 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
118 if (dex_file_with_checksum.size() != 2) {
119 return false;
120 }
121 uint32_t checksum = 0;
122 if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
123 return false;
124 }
125 class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
126 class_loader_chain_.back().checksums.push_back(checksum);
127 }
128 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700129
130 return true;
131}
132
133// Extracts the class loader type from the given spec.
134// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
135// recognized.
136ClassLoaderContext::ClassLoaderType
137ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
138 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
139 for (const ClassLoaderType& type : kValidTypes) {
140 const char* type_str = GetClassLoaderTypeName(type);
141 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
142 return type;
143 }
144 }
145 return kInvalidClassLoader;
146}
147
148// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
149// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
150// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700151bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700152 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700153 // By default we load the dex files in a PathClassLoader.
154 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
155 // tests)
156 class_loader_chain_.push_back(ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700157 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700158 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700159
Calin Juravle87e2cb62017-06-13 21:48:45 -0700160 // Stop early if we detect the special shared library, which may be passed as the classpath
161 // for dex2oat when we want to skip the shared libraries check.
162 if (spec == OatFile::kSpecialSharedLibrary) {
163 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
164 special_shared_library_ = true;
165 return true;
166 }
167
168 std::vector<std::string> class_loaders;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700169 Split(spec, kClassLoaderSeparator, &class_loaders);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700170
171 for (const std::string& class_loader : class_loaders) {
172 ClassLoaderType type = ExtractClassLoaderType(class_loader);
173 if (type == kInvalidClassLoader) {
174 LOG(ERROR) << "Invalid class loader type: " << class_loader;
175 return false;
176 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700177 if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700178 LOG(ERROR) << "Invalid class loader spec: " << class_loader;
179 return false;
180 }
181 }
182 return true;
183}
184
185// Opens requested class path files and appends them to opened_dex_files. If the dex files have
186// been stripped, this opens them from their oat files (which get added to opened_oat_files).
187bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700188 if (dex_files_open_attempted_) {
189 // Do not attempt to re-open the files if we already tried.
190 return dex_files_open_result_;
191 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700192
193 dex_files_open_attempted_ = true;
194 // Assume we can open all dex files. If not, we will set this to false as we go.
195 dex_files_open_result_ = true;
196
197 if (special_shared_library_) {
198 // Nothing to open if the context is a special shared library.
199 return true;
200 }
201
202 // Note that we try to open all dex files even if some fail.
203 // We may get resource-only apks which we cannot load.
204 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
205 // no dex files. So that we can distinguish the real failures...
206 for (ClassLoaderInfo& info : class_loader_chain_) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700207 size_t opened_dex_files_index = info.opened_dex_files.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700208 for (const std::string& cp_elem : info.classpath) {
209 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000210 std::string location = cp_elem;
211 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000212 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700213 }
214
Calin Juravle87e2cb62017-06-13 21:48:45 -0700215 std::string error_msg;
216 // When opening the dex files from the context we expect their checksum to match their
217 // contents. So pass true to verify_checksum.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700218 if (!DexFileLoader::Open(location.c_str(),
219 location.c_str(),
Nicolas Geoffraye875f4c2017-10-26 12:26:43 +0100220 Runtime::Current()->IsVerificationEnabled(),
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700221 /*verify_checksum*/ true,
222 &error_msg,
223 &info.opened_dex_files)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700224 // If we fail to open the dex file because it's been stripped, try to open the dex file
225 // from its corresponding oat file.
226 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
227 // (for example, if the pre-build is only quicken and we want to re-compile it
228 // speed-profile).
229 // TODO(calin): Use the vdex directly instead of going through the oat file.
230 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
231 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
232 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
233 if (oat_file != nullptr &&
234 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
235 info.opened_oat_files.push_back(std::move(oat_file));
236 info.opened_dex_files.insert(info.opened_dex_files.end(),
237 std::make_move_iterator(oat_dex_files.begin()),
238 std::make_move_iterator(oat_dex_files.end()));
239 } else {
240 LOG(WARNING) << "Could not open dex files from location: " << location;
241 dex_files_open_result_ = false;
242 }
243 }
244 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700245
246 // We finished opening the dex files from the classpath.
247 // Now update the classpath and the checksum with the locations of the dex files.
248 //
249 // We do this because initially the classpath contains the paths of the dex files; and
250 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
251 // file paths with the actual dex locations being loaded.
252 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
253 // location in the class paths.
254 // Note that this will also remove the paths that could not be opened.
255 info.classpath.clear();
256 info.checksums.clear();
257 for (size_t k = opened_dex_files_index; k < info.opened_dex_files.size(); k++) {
258 std::unique_ptr<const DexFile>& dex = info.opened_dex_files[k];
259 info.classpath.push_back(dex->GetLocation());
260 info.checksums.push_back(dex->GetLocationChecksum());
261 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700262 }
263
264 return dex_files_open_result_;
265}
266
267bool ClassLoaderContext::RemoveLocationsFromClassPaths(
268 const dchecked_vector<std::string>& locations) {
269 CHECK(!dex_files_open_attempted_)
270 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
271
272 std::set<std::string> canonical_locations;
273 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700274 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700275 }
276 bool removed_locations = false;
277 for (ClassLoaderInfo& info : class_loader_chain_) {
278 size_t initial_size = info.classpath.size();
279 auto kept_it = std::remove_if(
280 info.classpath.begin(),
281 info.classpath.end(),
282 [canonical_locations](const std::string& location) {
283 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700284 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700285 });
286 info.classpath.erase(kept_it, info.classpath.end());
287 if (initial_size != info.classpath.size()) {
288 removed_locations = true;
289 }
290 }
291 return removed_locations;
292}
293
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700294std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
295 return EncodeContext(base_dir, /*for_dex2oat*/ true);
296}
297
Calin Juravle87e2cb62017-06-13 21:48:45 -0700298std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700299 return EncodeContext(base_dir, /*for_dex2oat*/ false);
300}
301
302std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
303 bool for_dex2oat) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700304 CheckDexFilesOpened("EncodeContextForOatFile");
305 if (special_shared_library_) {
306 return OatFile::kSpecialSharedLibrary;
307 }
308
Calin Juravle7b0648a2017-07-07 18:40:50 -0700309 std::ostringstream out;
Calin Juravle1a509c82017-07-24 16:51:21 -0700310 if (class_loader_chain_.empty()) {
311 // We can get in this situation if the context was created with a class path containing the
312 // source dex files which were later removed (happens during run-tests).
313 out << GetClassLoaderTypeName(kPathClassLoader)
314 << kClassLoaderOpeningMark
315 << kClassLoaderClosingMark;
316 return out.str();
317 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700318
Calin Juravle7b0648a2017-07-07 18:40:50 -0700319 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
320 const ClassLoaderInfo& info = class_loader_chain_[i];
321 if (i > 0) {
322 out << kClassLoaderSeparator;
323 }
324 out << GetClassLoaderTypeName(info.type);
325 out << kClassLoaderOpeningMark;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700326 std::set<std::string> seen_locations;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700327 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
328 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700329 if (for_dex2oat) {
330 // dex2oat only needs the base location. It cannot accept multidex locations.
331 // So ensure we only add each file once.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700332 bool new_insert = seen_locations.insert(
333 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700334 if (!new_insert) {
335 continue;
336 }
337 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700338 const std::string& location = dex_file->GetLocation();
339 if (k > 0) {
340 out << kClasspathSeparator;
341 }
342 // Find paths that were relative and convert them back from absolute.
343 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
344 out << location.substr(base_dir.length() + 1).c_str();
345 } else {
346 out << dex_file->GetLocation().c_str();
347 }
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700348 // dex2oat does not need the checksums.
349 if (!for_dex2oat) {
350 out << kDexFileChecksumSeparator;
351 out << dex_file->GetLocationChecksum();
352 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700353 }
354 out << kClassLoaderClosingMark;
355 }
356 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700357}
358
359jobject ClassLoaderContext::CreateClassLoader(
360 const std::vector<const DexFile*>& compilation_sources) const {
361 CheckDexFilesOpened("CreateClassLoader");
362
363 Thread* self = Thread::Current();
364 ScopedObjectAccess soa(self);
365
Calin Juravlec79470d2017-07-12 17:37:42 -0700366 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700367
Calin Juravlec79470d2017-07-12 17:37:42 -0700368 if (class_loader_chain_.empty()) {
369 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700370 }
371
Calin Juravlec79470d2017-07-12 17:37:42 -0700372 // Create the class loaders starting from the top most parent (the one on the last position
373 // in the chain) but omit the first class loader which will contain the compilation_sources and
374 // needs special handling.
375 jobject current_parent = nullptr; // the starting parent is the BootClassLoader.
376 for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
377 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
378 class_loader_chain_[i].opened_dex_files);
379 current_parent = class_linker->CreateWellKnownClassLoader(
380 self,
381 class_path_files,
382 GetClassLoaderClass(class_loader_chain_[i].type),
383 current_parent);
384 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700385
Calin Juravlec79470d2017-07-12 17:37:42 -0700386 // We set up all the parents. Move on to create the first class loader.
387 // Its classpath comes first, followed by compilation sources. This ensures that whenever
388 // we need to resolve classes from it the classpath elements come first.
389
390 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
391 class_loader_chain_[0].opened_dex_files);
392 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
393 compilation_sources.begin(),
394 compilation_sources.end());
395
396 return class_linker->CreateWellKnownClassLoader(
397 self,
398 first_class_loader_classpath,
399 GetClassLoaderClass(class_loader_chain_[0].type),
400 current_parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700401}
402
403std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
404 CheckDexFilesOpened("FlattenOpenedDexFiles");
405
406 std::vector<const DexFile*> result;
407 for (const ClassLoaderInfo& info : class_loader_chain_) {
408 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
409 result.push_back(dex_file.get());
410 }
411 }
412 return result;
413}
414
415const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
416 switch (type) {
417 case kPathClassLoader: return kPathClassLoaderString;
418 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
419 default:
420 LOG(FATAL) << "Invalid class loader type " << type;
421 UNREACHABLE();
422 }
423}
424
425void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
426 CHECK(dex_files_open_attempted_)
427 << "Dex files were not successfully opened before the call to " << calling_method
428 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
429}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700430
Calin Juravle57d0acc2017-07-11 17:41:30 -0700431// Collects the dex files from the give Java dex_file object. Only the dex files with
432// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
433static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
434 ArtField* const cookie_field,
435 std::vector<const DexFile*>* out_dex_files)
436 REQUIRES_SHARED(Locks::mutator_lock_) {
437 if (java_dex_file == nullptr) {
438 return true;
439 }
440 // On the Java side, the dex files are stored in the cookie field.
441 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
442 if (long_array == nullptr) {
443 // This should never happen so log a warning.
444 LOG(ERROR) << "Unexpected null cookie";
445 return false;
446 }
447 int32_t long_array_size = long_array->GetLength();
448 // Index 0 from the long array stores the oat file. The dex files start at index 1.
449 for (int32_t j = 1; j < long_array_size; ++j) {
450 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
451 long_array->GetWithoutChecks(j)));
452 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
453 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
454 // cp_dex_file can be null.
455 out_dex_files->push_back(cp_dex_file);
456 }
457 }
458 return true;
459}
460
461// Collects all the dex files loaded by the given class loader.
462// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
463// a null list of dex elements or a null dex element).
464static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
465 Handle<mirror::ClassLoader> class_loader,
466 std::vector<const DexFile*>* out_dex_files)
467 REQUIRES_SHARED(Locks::mutator_lock_) {
468 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
469
470 // All supported class loaders inherit from BaseDexClassLoader.
471 // We need to get the DexPathList and loop through it.
472 ArtField* const cookie_field =
473 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
474 ArtField* const dex_file_field =
475 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
476 ObjPtr<mirror::Object> dex_path_list =
477 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
478 GetObject(class_loader.Get());
479 CHECK(cookie_field != nullptr);
480 CHECK(dex_file_field != nullptr);
481 if (dex_path_list == nullptr) {
482 // This may be null if the current class loader is under construction and it does not
483 // have its fields setup yet.
484 return true;
485 }
486 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
487 ObjPtr<mirror::Object> dex_elements_obj =
488 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
489 GetObject(dex_path_list);
490 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
491 // at the mCookie which is a DexFile vector.
492 if (dex_elements_obj == nullptr) {
493 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
494 // and assume we have no elements.
495 return true;
496 } else {
497 StackHandleScope<1> hs(soa.Self());
498 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
499 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
500 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
501 mirror::Object* element = dex_elements->GetWithoutChecks(i);
502 if (element == nullptr) {
503 // Should never happen, log an error and break.
504 // TODO(calin): It's unclear if we should just assert here.
505 // This code was propagated to oat_file_manager from the class linker where it would
506 // throw a NPE. For now, return false which will mark this class loader as unsupported.
507 LOG(ERROR) << "Unexpected null in the dex element list";
508 return false;
509 }
510 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
511 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
512 return false;
513 }
514 }
515 }
516
517 return true;
518}
519
520static bool GetDexFilesFromDexElementsArray(
521 ScopedObjectAccessAlreadyRunnable& soa,
522 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
523 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
524 DCHECK(dex_elements != nullptr);
525
526 ArtField* const cookie_field =
527 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
528 ArtField* const dex_file_field =
529 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
530 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
531 WellKnownClasses::dalvik_system_DexPathList__Element);
532 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
533 WellKnownClasses::dalvik_system_DexFile);
534
535 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
536 mirror::Object* element = dex_elements->GetWithoutChecks(i);
537 // We can hit a null element here because this is invoked with a partially filled dex_elements
538 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
539 // list of dex files which were opened before.
540 if (element == nullptr) {
541 continue;
542 }
543
544 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
545 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
546 // a historical glitch. All the java code opens dex files using an array of Elements.
547 ObjPtr<mirror::Object> dex_file;
548 if (element_class == element->GetClass()) {
549 dex_file = dex_file_field->GetObject(element);
550 } else if (dexfile_class == element->GetClass()) {
551 dex_file = element;
552 } else {
553 LOG(ERROR) << "Unsupported element in dex_elements: "
554 << mirror::Class::PrettyClass(element->GetClass());
555 return false;
556 }
557
558 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
559 return false;
560 }
561 }
562 return true;
563}
564
565// Adds the `class_loader` info to the `context`.
566// The dex file present in `dex_elements` array (if not null) will be added at the end of
567// the classpath.
568// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
569// BootClassLoader. Note that the class loader chain is expected to be short.
570bool ClassLoaderContext::AddInfoToContextFromClassLoader(
571 ScopedObjectAccessAlreadyRunnable& soa,
572 Handle<mirror::ClassLoader> class_loader,
573 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
574 REQUIRES_SHARED(Locks::mutator_lock_) {
575 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
576 // Nothing to do for the boot class loader as we don't add its dex files to the context.
577 return true;
578 }
579
580 ClassLoaderContext::ClassLoaderType type;
581 if (IsPathOrDexClassLoader(soa, class_loader)) {
582 type = kPathClassLoader;
583 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
584 type = kDelegateLastClassLoader;
585 } else {
586 LOG(WARNING) << "Unsupported class loader";
587 return false;
588 }
589
590 // Inspect the class loader for its dex files.
591 std::vector<const DexFile*> dex_files_loaded;
592 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
593
594 // If we have a dex_elements array extract its dex elements now.
595 // This is used in two situations:
596 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
597 // passing the list of already open dex files each time. This ensures that we see the
598 // correct context even if the ClassLoader under construction is not fully build.
599 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
600 // appending them to the current class loader. When the new code paths are loaded in
601 // BaseDexClassLoader, the paths already present in the class loader will be passed
602 // in the dex_elements array.
603 if (dex_elements != nullptr) {
604 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
605 }
606
607 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
608 ClassLoaderInfo& info = class_loader_chain_.back();
609 for (const DexFile* dex_file : dex_files_loaded) {
610 info.classpath.push_back(dex_file->GetLocation());
611 info.checksums.push_back(dex_file->GetLocationChecksum());
612 info.opened_dex_files.emplace_back(dex_file);
613 }
614
615 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
616
617 StackHandleScope<1> hs(Thread::Current());
618 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
619
620 // Note that dex_elements array is null here. The elements are considered to be part of the
621 // current class loader and are not passed to the parents.
622 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
623 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
624}
625
626std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
627 jobject class_loader,
628 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700629 CHECK(class_loader != nullptr);
630
Calin Juravle57d0acc2017-07-11 17:41:30 -0700631 ScopedObjectAccess soa(Thread::Current());
632 StackHandleScope<2> hs(soa.Self());
633 Handle<mirror::ClassLoader> h_class_loader =
634 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
635 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
636 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
637
Calin Juravle57d0acc2017-07-11 17:41:30 -0700638 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
639 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
640 return result;
641 } else {
642 return nullptr;
643 }
644}
645
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700646static bool IsAbsoluteLocation(const std::string& location) {
647 return !location.empty() && location[0] == '/';
648}
649
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700650bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) const {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700651 DCHECK(dex_files_open_attempted_);
652 DCHECK(dex_files_open_result_);
653
Calin Juravle3f918642017-07-11 19:04:20 -0700654 ClassLoaderContext expected_context;
655 if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
656 LOG(WARNING) << "Invalid class loader context: " << context_spec;
657 return false;
658 }
659
Calin Juravlec5b215f2017-09-12 14:49:37 -0700660 // Special shared library contexts always match. They essentially instruct the runtime
661 // to ignore the class path check because the oat file is known to be loaded in different
662 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
663 // collision check.
664 if (special_shared_library_ || expected_context.special_shared_library_) {
Calin Juravle3f918642017-07-11 19:04:20 -0700665 return true;
666 }
667
668 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
669 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
670 << expected_context.class_loader_chain_.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700671 << ", actual=" << class_loader_chain_.size()
672 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700673 return false;
674 }
675
676 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
677 const ClassLoaderInfo& info = class_loader_chain_[i];
678 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
679 if (info.type != expected_info.type) {
680 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
681 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700682 << ", found=" << GetClassLoaderTypeName(info.type)
683 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700684 return false;
685 }
686 if (info.classpath.size() != expected_info.classpath.size()) {
687 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
688 << ". expected=" << expected_info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700689 << ", found=" << info.classpath.size()
690 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700691 return false;
692 }
693
694 DCHECK_EQ(info.classpath.size(), info.checksums.size());
695 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
696
697 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700698 // Compute the dex location that must be compared.
699 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
700 // because even if they refer to the same file, one could be encoded as a relative location
701 // and the other as an absolute one.
702 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
703 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
704 std::string dex_name;
705 std::string expected_dex_name;
706
707 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
708 // If both locations are absolute or relative then compare them as they are.
709 // This is usually the case for: shared libraries and secondary dex files.
710 dex_name = info.classpath[k];
711 expected_dex_name = expected_info.classpath[k];
712 } else if (is_dex_name_absolute) {
713 // The runtime name is absolute but the compiled name (the expected one) is relative.
714 // This is the case for split apks which depend on base or on other splits.
715 dex_name = info.classpath[k];
716 expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
717 info.classpath[k].c_str(), expected_info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +0000718 } else if (is_expected_dex_name_absolute) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700719 // The runtime name is relative but the compiled name is absolute.
720 // There is no expected use case that would end up here as dex files are always loaded
721 // with their absolute location. However, be tolerant and do the best effort (in case
722 // there are unexpected new use case...).
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700723 dex_name = OatFile::ResolveRelativeEncodedDexLocation(
724 expected_info.classpath[k].c_str(), info.classpath[k]);
725 expected_dex_name = expected_info.classpath[k];
Calin Juravle92003fe2017-09-06 02:22:57 +0000726 } else {
727 // Both locations are relative. In this case there's not much we can be sure about
728 // except that the names are the same. The checksum will ensure that the files are
729 // are same. This should not happen outside testing and manual invocations.
730 dex_name = info.classpath[k];
731 expected_dex_name = expected_info.classpath[k];
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700732 }
733
734 // Compare the locations.
735 if (dex_name != expected_dex_name) {
Calin Juravle3f918642017-07-11 19:04:20 -0700736 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
737 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700738 << ", found=" << info.classpath[k]
739 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700740 return false;
741 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700742
743 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -0700744 if (info.checksums[k] != expected_info.checksums[k]) {
745 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700746 << ". expected=" << expected_info.checksums[k]
747 << ", found=" << info.checksums[k]
748 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700749 return false;
750 }
751 }
752 }
753 return true;
754}
755
Calin Juravlec79470d2017-07-12 17:37:42 -0700756jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
757 switch (type) {
758 case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
759 case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
760 case kInvalidClassLoader: break; // will fail after the switch.
761 }
762 LOG(FATAL) << "Invalid class loader type " << type;
763 UNREACHABLE();
764}
765
Calin Juravle87e2cb62017-06-13 21:48:45 -0700766} // namespace art
767