blob: 678ae8f2880b8dc6ae2f91c4288fb7ebdbb6dd79 [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"
Calin Juravle87e2cb62017-06-13 21:48:45 -070024#include "dex_file.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070025#include "handle_scope-inl.h"
26#include "jni_internal.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070027#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070028#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070029#include "runtime.h"
30#include "scoped_thread_state_change-inl.h"
31#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070032#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070033
34namespace art {
35
36static constexpr char kPathClassLoaderString[] = "PCL";
37static constexpr char kDelegateLastClassLoaderString[] = "DLC";
38static constexpr char kClassLoaderOpeningMark = '[';
39static constexpr char kClassLoaderClosingMark = ']';
Calin Juravle7b0648a2017-07-07 18:40:50 -070040static constexpr char kClassLoaderSeparator = ';';
41static constexpr char kClasspathSeparator = ':';
42static constexpr char kDexFileChecksumSeparator = '*';
Calin Juravle87e2cb62017-06-13 21:48:45 -070043
44ClassLoaderContext::ClassLoaderContext()
45 : special_shared_library_(false),
46 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070047 dex_files_open_result_(false),
48 owns_the_dex_files_(false) {}
49
50ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
51 : special_shared_library_(false),
52 dex_files_open_attempted_(true),
53 dex_files_open_result_(true),
54 owns_the_dex_files_(owns_the_dex_files) {}
55
56ClassLoaderContext::~ClassLoaderContext() {
57 if (!owns_the_dex_files_) {
58 // If the context does not own the dex/oat files release the unique pointers to
59 // make sure we do not de-allocate them.
60 for (ClassLoaderInfo& info : class_loader_chain_) {
61 for (std::unique_ptr<OatFile>& oat_file : info.opened_oat_files) {
62 oat_file.release();
63 }
64 for (std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
65 dex_file.release();
66 }
67 }
68 }
69}
Calin Juravle87e2cb62017-06-13 21:48:45 -070070
71std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
72 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
73 if (result->Parse(spec)) {
74 return result;
75 } else {
76 return nullptr;
77 }
78}
79
Calin Juravle7b0648a2017-07-07 18:40:50 -070080// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
81// The checksum part of the format is expected only if parse_cheksums is true.
Calin Juravle87e2cb62017-06-13 21:48:45 -070082bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
Calin Juravle7b0648a2017-07-07 18:40:50 -070083 ClassLoaderType class_loader_type,
84 bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -070085 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
86 size_t type_str_size = strlen(class_loader_type_str);
87
88 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
89
90 // Check the opening and closing markers.
91 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
92 return false;
93 }
94 if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
95 return false;
96 }
97
98 // At this point we know the format is ok; continue and extract the classpath.
99 // Note that class loaders with an empty class path are allowed.
100 std::string classpath = class_loader_spec.substr(type_str_size + 1,
101 class_loader_spec.length() - type_str_size - 2);
102
103 class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700104
105 if (!parse_checksums) {
106 Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
107 } else {
108 std::vector<std::string> classpath_elements;
109 Split(classpath, kClasspathSeparator, &classpath_elements);
110 for (const std::string& element : classpath_elements) {
111 std::vector<std::string> dex_file_with_checksum;
112 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
113 if (dex_file_with_checksum.size() != 2) {
114 return false;
115 }
116 uint32_t checksum = 0;
117 if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
118 return false;
119 }
120 class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
121 class_loader_chain_.back().checksums.push_back(checksum);
122 }
123 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700124
125 return true;
126}
127
128// Extracts the class loader type from the given spec.
129// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
130// recognized.
131ClassLoaderContext::ClassLoaderType
132ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
133 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
134 for (const ClassLoaderType& type : kValidTypes) {
135 const char* type_str = GetClassLoaderTypeName(type);
136 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
137 return type;
138 }
139 }
140 return kInvalidClassLoader;
141}
142
143// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
144// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
145// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700146bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700147 if (spec.empty()) {
Calin Juravle7b0648a2017-07-07 18:40:50 -0700148 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700149 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700150
Calin Juravle87e2cb62017-06-13 21:48:45 -0700151 // Stop early if we detect the special shared library, which may be passed as the classpath
152 // for dex2oat when we want to skip the shared libraries check.
153 if (spec == OatFile::kSpecialSharedLibrary) {
154 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
155 special_shared_library_ = true;
156 return true;
157 }
158
159 std::vector<std::string> class_loaders;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700160 Split(spec, kClassLoaderSeparator, &class_loaders);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700161
162 for (const std::string& class_loader : class_loaders) {
163 ClassLoaderType type = ExtractClassLoaderType(class_loader);
164 if (type == kInvalidClassLoader) {
165 LOG(ERROR) << "Invalid class loader type: " << class_loader;
166 return false;
167 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700168 if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700169 LOG(ERROR) << "Invalid class loader spec: " << class_loader;
170 return false;
171 }
172 }
173 return true;
174}
175
176// Opens requested class path files and appends them to opened_dex_files. If the dex files have
177// been stripped, this opens them from their oat files (which get added to opened_oat_files).
178bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
179 CHECK(!dex_files_open_attempted_) << "OpenDexFiles should not be called twice";
180
181 dex_files_open_attempted_ = true;
182 // Assume we can open all dex files. If not, we will set this to false as we go.
183 dex_files_open_result_ = true;
184
185 if (special_shared_library_) {
186 // Nothing to open if the context is a special shared library.
187 return true;
188 }
189
190 // Note that we try to open all dex files even if some fail.
191 // We may get resource-only apks which we cannot load.
192 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
193 // no dex files. So that we can distinguish the real failures...
194 for (ClassLoaderInfo& info : class_loader_chain_) {
195 for (const std::string& cp_elem : info.classpath) {
196 // If path is relative, append it to the provided base directory.
197 std::string location = cp_elem;
198 if (location[0] != '/') {
199 location = classpath_dir + '/' + location;
200 }
201 std::string error_msg;
202 // When opening the dex files from the context we expect their checksum to match their
203 // contents. So pass true to verify_checksum.
204 if (!DexFile::Open(location.c_str(),
205 location.c_str(),
206 /*verify_checksum*/ true,
207 &error_msg,
208 &info.opened_dex_files)) {
209 // If we fail to open the dex file because it's been stripped, try to open the dex file
210 // from its corresponding oat file.
211 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
212 // (for example, if the pre-build is only quicken and we want to re-compile it
213 // speed-profile).
214 // TODO(calin): Use the vdex directly instead of going through the oat file.
215 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
216 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
217 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
218 if (oat_file != nullptr &&
219 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
220 info.opened_oat_files.push_back(std::move(oat_file));
221 info.opened_dex_files.insert(info.opened_dex_files.end(),
222 std::make_move_iterator(oat_dex_files.begin()),
223 std::make_move_iterator(oat_dex_files.end()));
224 } else {
225 LOG(WARNING) << "Could not open dex files from location: " << location;
226 dex_files_open_result_ = false;
227 }
228 }
229 }
230 }
231
232 return dex_files_open_result_;
233}
234
235bool ClassLoaderContext::RemoveLocationsFromClassPaths(
236 const dchecked_vector<std::string>& locations) {
237 CHECK(!dex_files_open_attempted_)
238 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
239
240 std::set<std::string> canonical_locations;
241 for (const std::string& location : locations) {
242 canonical_locations.insert(DexFile::GetDexCanonicalLocation(location.c_str()));
243 }
244 bool removed_locations = false;
245 for (ClassLoaderInfo& info : class_loader_chain_) {
246 size_t initial_size = info.classpath.size();
247 auto kept_it = std::remove_if(
248 info.classpath.begin(),
249 info.classpath.end(),
250 [canonical_locations](const std::string& location) {
251 return ContainsElement(canonical_locations,
252 DexFile::GetDexCanonicalLocation(location.c_str()));
253 });
254 info.classpath.erase(kept_it, info.classpath.end());
255 if (initial_size != info.classpath.size()) {
256 removed_locations = true;
257 }
258 }
259 return removed_locations;
260}
261
262std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
263 CheckDexFilesOpened("EncodeContextForOatFile");
264 if (special_shared_library_) {
265 return OatFile::kSpecialSharedLibrary;
266 }
267
268 if (class_loader_chain_.empty()) {
269 return "";
270 }
271
Calin Juravle7b0648a2017-07-07 18:40:50 -0700272 std::ostringstream out;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700273
Calin Juravle7b0648a2017-07-07 18:40:50 -0700274 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
275 const ClassLoaderInfo& info = class_loader_chain_[i];
276 if (i > 0) {
277 out << kClassLoaderSeparator;
278 }
279 out << GetClassLoaderTypeName(info.type);
280 out << kClassLoaderOpeningMark;
281 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
282 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
283 const std::string& location = dex_file->GetLocation();
284 if (k > 0) {
285 out << kClasspathSeparator;
286 }
287 // Find paths that were relative and convert them back from absolute.
288 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
289 out << location.substr(base_dir.length() + 1).c_str();
290 } else {
291 out << dex_file->GetLocation().c_str();
292 }
293 out << kDexFileChecksumSeparator;
294 out << dex_file->GetLocationChecksum();
295 }
296 out << kClassLoaderClosingMark;
297 }
298 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700299}
300
301jobject ClassLoaderContext::CreateClassLoader(
302 const std::vector<const DexFile*>& compilation_sources) const {
303 CheckDexFilesOpened("CreateClassLoader");
304
305 Thread* self = Thread::Current();
306 ScopedObjectAccess soa(self);
307
308 std::vector<const DexFile*> class_path_files;
309
310 // TODO(calin): Transition period: assume we only have a classloader until
311 // the oat file assistant implements the full class loader check.
312 if (!class_loader_chain_.empty()) {
313 CHECK_EQ(1u, class_loader_chain_.size());
314 CHECK_EQ(kPathClassLoader, class_loader_chain_[0].type);
315 class_path_files = MakeNonOwningPointerVector(class_loader_chain_[0].opened_dex_files);
316 }
317
318 // Classpath: first the class-path given; then the dex files we'll compile.
319 // Thus we'll resolve the class-path first.
320 class_path_files.insert(class_path_files.end(),
321 compilation_sources.begin(),
322 compilation_sources.end());
323
324 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
325 return class_linker->CreatePathClassLoader(self, class_path_files);
326}
327
328std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
329 CheckDexFilesOpened("FlattenOpenedDexFiles");
330
331 std::vector<const DexFile*> result;
332 for (const ClassLoaderInfo& info : class_loader_chain_) {
333 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
334 result.push_back(dex_file.get());
335 }
336 }
337 return result;
338}
339
340const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
341 switch (type) {
342 case kPathClassLoader: return kPathClassLoaderString;
343 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
344 default:
345 LOG(FATAL) << "Invalid class loader type " << type;
346 UNREACHABLE();
347 }
348}
349
350void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
351 CHECK(dex_files_open_attempted_)
352 << "Dex files were not successfully opened before the call to " << calling_method
353 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
354}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700355
Calin Juravle57d0acc2017-07-11 17:41:30 -0700356// Collects the dex files from the give Java dex_file object. Only the dex files with
357// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
358static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
359 ArtField* const cookie_field,
360 std::vector<const DexFile*>* out_dex_files)
361 REQUIRES_SHARED(Locks::mutator_lock_) {
362 if (java_dex_file == nullptr) {
363 return true;
364 }
365 // On the Java side, the dex files are stored in the cookie field.
366 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
367 if (long_array == nullptr) {
368 // This should never happen so log a warning.
369 LOG(ERROR) << "Unexpected null cookie";
370 return false;
371 }
372 int32_t long_array_size = long_array->GetLength();
373 // Index 0 from the long array stores the oat file. The dex files start at index 1.
374 for (int32_t j = 1; j < long_array_size; ++j) {
375 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
376 long_array->GetWithoutChecks(j)));
377 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
378 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
379 // cp_dex_file can be null.
380 out_dex_files->push_back(cp_dex_file);
381 }
382 }
383 return true;
384}
385
386// Collects all the dex files loaded by the given class loader.
387// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
388// a null list of dex elements or a null dex element).
389static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
390 Handle<mirror::ClassLoader> class_loader,
391 std::vector<const DexFile*>* out_dex_files)
392 REQUIRES_SHARED(Locks::mutator_lock_) {
393 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
394
395 // All supported class loaders inherit from BaseDexClassLoader.
396 // We need to get the DexPathList and loop through it.
397 ArtField* const cookie_field =
398 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
399 ArtField* const dex_file_field =
400 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
401 ObjPtr<mirror::Object> dex_path_list =
402 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
403 GetObject(class_loader.Get());
404 CHECK(cookie_field != nullptr);
405 CHECK(dex_file_field != nullptr);
406 if (dex_path_list == nullptr) {
407 // This may be null if the current class loader is under construction and it does not
408 // have its fields setup yet.
409 return true;
410 }
411 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
412 ObjPtr<mirror::Object> dex_elements_obj =
413 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
414 GetObject(dex_path_list);
415 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
416 // at the mCookie which is a DexFile vector.
417 if (dex_elements_obj == nullptr) {
418 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
419 // and assume we have no elements.
420 return true;
421 } else {
422 StackHandleScope<1> hs(soa.Self());
423 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
424 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
425 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
426 mirror::Object* element = dex_elements->GetWithoutChecks(i);
427 if (element == nullptr) {
428 // Should never happen, log an error and break.
429 // TODO(calin): It's unclear if we should just assert here.
430 // This code was propagated to oat_file_manager from the class linker where it would
431 // throw a NPE. For now, return false which will mark this class loader as unsupported.
432 LOG(ERROR) << "Unexpected null in the dex element list";
433 return false;
434 }
435 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
436 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
437 return false;
438 }
439 }
440 }
441
442 return true;
443}
444
445static bool GetDexFilesFromDexElementsArray(
446 ScopedObjectAccessAlreadyRunnable& soa,
447 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
448 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
449 DCHECK(dex_elements != nullptr);
450
451 ArtField* const cookie_field =
452 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
453 ArtField* const dex_file_field =
454 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
455 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
456 WellKnownClasses::dalvik_system_DexPathList__Element);
457 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
458 WellKnownClasses::dalvik_system_DexFile);
459
460 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
461 mirror::Object* element = dex_elements->GetWithoutChecks(i);
462 // We can hit a null element here because this is invoked with a partially filled dex_elements
463 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
464 // list of dex files which were opened before.
465 if (element == nullptr) {
466 continue;
467 }
468
469 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
470 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
471 // a historical glitch. All the java code opens dex files using an array of Elements.
472 ObjPtr<mirror::Object> dex_file;
473 if (element_class == element->GetClass()) {
474 dex_file = dex_file_field->GetObject(element);
475 } else if (dexfile_class == element->GetClass()) {
476 dex_file = element;
477 } else {
478 LOG(ERROR) << "Unsupported element in dex_elements: "
479 << mirror::Class::PrettyClass(element->GetClass());
480 return false;
481 }
482
483 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
484 return false;
485 }
486 }
487 return true;
488}
489
490// Adds the `class_loader` info to the `context`.
491// The dex file present in `dex_elements` array (if not null) will be added at the end of
492// the classpath.
493// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
494// BootClassLoader. Note that the class loader chain is expected to be short.
495bool ClassLoaderContext::AddInfoToContextFromClassLoader(
496 ScopedObjectAccessAlreadyRunnable& soa,
497 Handle<mirror::ClassLoader> class_loader,
498 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
499 REQUIRES_SHARED(Locks::mutator_lock_) {
500 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
501 // Nothing to do for the boot class loader as we don't add its dex files to the context.
502 return true;
503 }
504
505 ClassLoaderContext::ClassLoaderType type;
506 if (IsPathOrDexClassLoader(soa, class_loader)) {
507 type = kPathClassLoader;
508 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
509 type = kDelegateLastClassLoader;
510 } else {
511 LOG(WARNING) << "Unsupported class loader";
512 return false;
513 }
514
515 // Inspect the class loader for its dex files.
516 std::vector<const DexFile*> dex_files_loaded;
517 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
518
519 // If we have a dex_elements array extract its dex elements now.
520 // This is used in two situations:
521 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
522 // passing the list of already open dex files each time. This ensures that we see the
523 // correct context even if the ClassLoader under construction is not fully build.
524 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
525 // appending them to the current class loader. When the new code paths are loaded in
526 // BaseDexClassLoader, the paths already present in the class loader will be passed
527 // in the dex_elements array.
528 if (dex_elements != nullptr) {
529 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
530 }
531
532 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
533 ClassLoaderInfo& info = class_loader_chain_.back();
534 for (const DexFile* dex_file : dex_files_loaded) {
535 info.classpath.push_back(dex_file->GetLocation());
536 info.checksums.push_back(dex_file->GetLocationChecksum());
537 info.opened_dex_files.emplace_back(dex_file);
538 }
539
540 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
541
542 StackHandleScope<1> hs(Thread::Current());
543 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
544
545 // Note that dex_elements array is null here. The elements are considered to be part of the
546 // current class loader and are not passed to the parents.
547 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
548 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
549}
550
551std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
552 jobject class_loader,
553 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700554 CHECK(class_loader != nullptr);
555
Calin Juravle57d0acc2017-07-11 17:41:30 -0700556 ScopedObjectAccess soa(Thread::Current());
557 StackHandleScope<2> hs(soa.Self());
558 Handle<mirror::ClassLoader> h_class_loader =
559 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
560 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
561 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
562
Calin Juravle57d0acc2017-07-11 17:41:30 -0700563 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
564 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
565 return result;
566 } else {
567 return nullptr;
568 }
569}
570
Calin Juravle3f918642017-07-11 19:04:20 -0700571bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) {
572 ClassLoaderContext expected_context;
573 if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
574 LOG(WARNING) << "Invalid class loader context: " << context_spec;
575 return false;
576 }
577
578 if (expected_context.special_shared_library_) {
579 return true;
580 }
581
582 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
583 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
584 << expected_context.class_loader_chain_.size()
585 << ", actual=" << class_loader_chain_.size();
586 return false;
587 }
588
589 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
590 const ClassLoaderInfo& info = class_loader_chain_[i];
591 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
592 if (info.type != expected_info.type) {
593 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
594 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
595 << ", found=" << GetClassLoaderTypeName(info.type);
596 return false;
597 }
598 if (info.classpath.size() != expected_info.classpath.size()) {
599 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
600 << ". expected=" << expected_info.classpath.size()
601 << ", found=" << info.classpath.size();
602 return false;
603 }
604
605 DCHECK_EQ(info.classpath.size(), info.checksums.size());
606 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
607
608 for (size_t k = 0; k < info.classpath.size(); k++) {
609 if (info.classpath[k] != expected_info.classpath[k]) {
610 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
611 << ". expected=" << expected_info.classpath[k]
612 << ", found=" << info.classpath[k];
613 return false;
614 }
615 if (info.checksums[k] != expected_info.checksums[k]) {
616 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
617 << ". expected=" << expected_info.checksums[k]
618 << ", found=" << info.checksums[k];
619 return false;
620 }
621 }
622 }
623 return true;
624}
625
Calin Juravle87e2cb62017-06-13 21:48:45 -0700626} // namespace art
627