blob: eab3b86d3d79dc8cc168669a8fd110e59e01305b [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),
Calin Juravle41acdc12017-07-18 17:45:32 -070048 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070049
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
Calin Juravlec79470d2017-07-12 17:37:42 -0700308 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700309
Calin Juravlec79470d2017-07-12 17:37:42 -0700310 if (class_loader_chain_.empty()) {
311 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700312 }
313
Calin Juravlec79470d2017-07-12 17:37:42 -0700314 // Create the class loaders starting from the top most parent (the one on the last position
315 // in the chain) but omit the first class loader which will contain the compilation_sources and
316 // needs special handling.
317 jobject current_parent = nullptr; // the starting parent is the BootClassLoader.
318 for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
319 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
320 class_loader_chain_[i].opened_dex_files);
321 current_parent = class_linker->CreateWellKnownClassLoader(
322 self,
323 class_path_files,
324 GetClassLoaderClass(class_loader_chain_[i].type),
325 current_parent);
326 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700327
Calin Juravlec79470d2017-07-12 17:37:42 -0700328 // We set up all the parents. Move on to create the first class loader.
329 // Its classpath comes first, followed by compilation sources. This ensures that whenever
330 // we need to resolve classes from it the classpath elements come first.
331
332 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
333 class_loader_chain_[0].opened_dex_files);
334 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
335 compilation_sources.begin(),
336 compilation_sources.end());
337
338 return class_linker->CreateWellKnownClassLoader(
339 self,
340 first_class_loader_classpath,
341 GetClassLoaderClass(class_loader_chain_[0].type),
342 current_parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700343}
344
345std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
346 CheckDexFilesOpened("FlattenOpenedDexFiles");
347
348 std::vector<const DexFile*> result;
349 for (const ClassLoaderInfo& info : class_loader_chain_) {
350 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
351 result.push_back(dex_file.get());
352 }
353 }
354 return result;
355}
356
357const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
358 switch (type) {
359 case kPathClassLoader: return kPathClassLoaderString;
360 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
361 default:
362 LOG(FATAL) << "Invalid class loader type " << type;
363 UNREACHABLE();
364 }
365}
366
367void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
368 CHECK(dex_files_open_attempted_)
369 << "Dex files were not successfully opened before the call to " << calling_method
370 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
371}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700372
Calin Juravle57d0acc2017-07-11 17:41:30 -0700373// Collects the dex files from the give Java dex_file object. Only the dex files with
374// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
375static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
376 ArtField* const cookie_field,
377 std::vector<const DexFile*>* out_dex_files)
378 REQUIRES_SHARED(Locks::mutator_lock_) {
379 if (java_dex_file == nullptr) {
380 return true;
381 }
382 // On the Java side, the dex files are stored in the cookie field.
383 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
384 if (long_array == nullptr) {
385 // This should never happen so log a warning.
386 LOG(ERROR) << "Unexpected null cookie";
387 return false;
388 }
389 int32_t long_array_size = long_array->GetLength();
390 // Index 0 from the long array stores the oat file. The dex files start at index 1.
391 for (int32_t j = 1; j < long_array_size; ++j) {
392 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
393 long_array->GetWithoutChecks(j)));
394 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
395 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
396 // cp_dex_file can be null.
397 out_dex_files->push_back(cp_dex_file);
398 }
399 }
400 return true;
401}
402
403// Collects all the dex files loaded by the given class loader.
404// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
405// a null list of dex elements or a null dex element).
406static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
407 Handle<mirror::ClassLoader> class_loader,
408 std::vector<const DexFile*>* out_dex_files)
409 REQUIRES_SHARED(Locks::mutator_lock_) {
410 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
411
412 // All supported class loaders inherit from BaseDexClassLoader.
413 // We need to get the DexPathList and loop through it.
414 ArtField* const cookie_field =
415 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
416 ArtField* const dex_file_field =
417 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
418 ObjPtr<mirror::Object> dex_path_list =
419 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
420 GetObject(class_loader.Get());
421 CHECK(cookie_field != nullptr);
422 CHECK(dex_file_field != nullptr);
423 if (dex_path_list == nullptr) {
424 // This may be null if the current class loader is under construction and it does not
425 // have its fields setup yet.
426 return true;
427 }
428 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
429 ObjPtr<mirror::Object> dex_elements_obj =
430 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
431 GetObject(dex_path_list);
432 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
433 // at the mCookie which is a DexFile vector.
434 if (dex_elements_obj == nullptr) {
435 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
436 // and assume we have no elements.
437 return true;
438 } else {
439 StackHandleScope<1> hs(soa.Self());
440 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
441 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
442 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
443 mirror::Object* element = dex_elements->GetWithoutChecks(i);
444 if (element == nullptr) {
445 // Should never happen, log an error and break.
446 // TODO(calin): It's unclear if we should just assert here.
447 // This code was propagated to oat_file_manager from the class linker where it would
448 // throw a NPE. For now, return false which will mark this class loader as unsupported.
449 LOG(ERROR) << "Unexpected null in the dex element list";
450 return false;
451 }
452 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
453 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
454 return false;
455 }
456 }
457 }
458
459 return true;
460}
461
462static bool GetDexFilesFromDexElementsArray(
463 ScopedObjectAccessAlreadyRunnable& soa,
464 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
465 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
466 DCHECK(dex_elements != nullptr);
467
468 ArtField* const cookie_field =
469 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
470 ArtField* const dex_file_field =
471 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
472 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
473 WellKnownClasses::dalvik_system_DexPathList__Element);
474 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
475 WellKnownClasses::dalvik_system_DexFile);
476
477 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
478 mirror::Object* element = dex_elements->GetWithoutChecks(i);
479 // We can hit a null element here because this is invoked with a partially filled dex_elements
480 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
481 // list of dex files which were opened before.
482 if (element == nullptr) {
483 continue;
484 }
485
486 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
487 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
488 // a historical glitch. All the java code opens dex files using an array of Elements.
489 ObjPtr<mirror::Object> dex_file;
490 if (element_class == element->GetClass()) {
491 dex_file = dex_file_field->GetObject(element);
492 } else if (dexfile_class == element->GetClass()) {
493 dex_file = element;
494 } else {
495 LOG(ERROR) << "Unsupported element in dex_elements: "
496 << mirror::Class::PrettyClass(element->GetClass());
497 return false;
498 }
499
500 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
501 return false;
502 }
503 }
504 return true;
505}
506
507// Adds the `class_loader` info to the `context`.
508// The dex file present in `dex_elements` array (if not null) will be added at the end of
509// the classpath.
510// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
511// BootClassLoader. Note that the class loader chain is expected to be short.
512bool ClassLoaderContext::AddInfoToContextFromClassLoader(
513 ScopedObjectAccessAlreadyRunnable& soa,
514 Handle<mirror::ClassLoader> class_loader,
515 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
516 REQUIRES_SHARED(Locks::mutator_lock_) {
517 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
518 // Nothing to do for the boot class loader as we don't add its dex files to the context.
519 return true;
520 }
521
522 ClassLoaderContext::ClassLoaderType type;
523 if (IsPathOrDexClassLoader(soa, class_loader)) {
524 type = kPathClassLoader;
525 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
526 type = kDelegateLastClassLoader;
527 } else {
528 LOG(WARNING) << "Unsupported class loader";
529 return false;
530 }
531
532 // Inspect the class loader for its dex files.
533 std::vector<const DexFile*> dex_files_loaded;
534 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
535
536 // If we have a dex_elements array extract its dex elements now.
537 // This is used in two situations:
538 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
539 // passing the list of already open dex files each time. This ensures that we see the
540 // correct context even if the ClassLoader under construction is not fully build.
541 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
542 // appending them to the current class loader. When the new code paths are loaded in
543 // BaseDexClassLoader, the paths already present in the class loader will be passed
544 // in the dex_elements array.
545 if (dex_elements != nullptr) {
546 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
547 }
548
549 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
550 ClassLoaderInfo& info = class_loader_chain_.back();
551 for (const DexFile* dex_file : dex_files_loaded) {
552 info.classpath.push_back(dex_file->GetLocation());
553 info.checksums.push_back(dex_file->GetLocationChecksum());
554 info.opened_dex_files.emplace_back(dex_file);
555 }
556
557 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
558
559 StackHandleScope<1> hs(Thread::Current());
560 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
561
562 // Note that dex_elements array is null here. The elements are considered to be part of the
563 // current class loader and are not passed to the parents.
564 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
565 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
566}
567
568std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
569 jobject class_loader,
570 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700571 CHECK(class_loader != nullptr);
572
Calin Juravle57d0acc2017-07-11 17:41:30 -0700573 ScopedObjectAccess soa(Thread::Current());
574 StackHandleScope<2> hs(soa.Self());
575 Handle<mirror::ClassLoader> h_class_loader =
576 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
577 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
578 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
579
Calin Juravle57d0acc2017-07-11 17:41:30 -0700580 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
581 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
582 return result;
583 } else {
584 return nullptr;
585 }
586}
587
Calin Juravle3f918642017-07-11 19:04:20 -0700588bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) {
589 ClassLoaderContext expected_context;
590 if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
591 LOG(WARNING) << "Invalid class loader context: " << context_spec;
592 return false;
593 }
594
595 if (expected_context.special_shared_library_) {
596 return true;
597 }
598
599 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
600 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
601 << expected_context.class_loader_chain_.size()
602 << ", actual=" << class_loader_chain_.size();
603 return false;
604 }
605
606 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
607 const ClassLoaderInfo& info = class_loader_chain_[i];
608 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
609 if (info.type != expected_info.type) {
610 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
611 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
612 << ", found=" << GetClassLoaderTypeName(info.type);
613 return false;
614 }
615 if (info.classpath.size() != expected_info.classpath.size()) {
616 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
617 << ". expected=" << expected_info.classpath.size()
618 << ", found=" << info.classpath.size();
619 return false;
620 }
621
622 DCHECK_EQ(info.classpath.size(), info.checksums.size());
623 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
624
625 for (size_t k = 0; k < info.classpath.size(); k++) {
626 if (info.classpath[k] != expected_info.classpath[k]) {
627 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
628 << ". expected=" << expected_info.classpath[k]
629 << ", found=" << info.classpath[k];
630 return false;
631 }
632 if (info.checksums[k] != expected_info.checksums[k]) {
633 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
634 << ". expected=" << expected_info.checksums[k]
635 << ", found=" << info.checksums[k];
636 return false;
637 }
638 }
639 }
640 return true;
641}
642
Calin Juravlec79470d2017-07-12 17:37:42 -0700643jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
644 switch (type) {
645 case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
646 case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
647 case kInvalidClassLoader: break; // will fail after the switch.
648 }
649 LOG(FATAL) << "Invalid class loader type " << type;
650 UNREACHABLE();
651}
652
Calin Juravle87e2cb62017-06-13 21:48:45 -0700653} // namespace art
654