blob: a6e5c2147a2c0c39f47edf683b6dc75bd4ea2674 [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
356bool ClassLoaderContext::DecodePathClassLoaderContextFromOatFileKey(
357 const std::string& context_spec,
358 std::vector<std::string>* out_classpath,
359 std::vector<uint32_t>* out_checksums,
360 bool* out_is_special_shared_library) {
361 ClassLoaderContext context;
362 if (!context.Parse(context_spec, /*parse_checksums*/ true)) {
363 LOG(ERROR) << "Invalid class loader context: " << context_spec;
364 return false;
365 }
366
367 *out_is_special_shared_library = context.special_shared_library_;
368 if (context.special_shared_library_) {
369 return true;
370 }
371
372 if (context.class_loader_chain_.empty()) {
373 return true;
374 }
375
376 // TODO(calin): assert that we only have a PathClassLoader until the logic for
377 // checking the context covers all case.
378 CHECK_EQ(1u, context.class_loader_chain_.size());
379 const ClassLoaderInfo& info = context.class_loader_chain_[0];
380 CHECK_EQ(kPathClassLoader, info.type);
381 DCHECK_EQ(info.classpath.size(), info.checksums.size());
382
383 *out_classpath = info.classpath;
384 *out_checksums = info.checksums;
385 return true;
386}
Calin Juravle57d0acc2017-07-11 17:41:30 -0700387
388// Collects the dex files from the give Java dex_file object. Only the dex files with
389// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
390static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
391 ArtField* const cookie_field,
392 std::vector<const DexFile*>* out_dex_files)
393 REQUIRES_SHARED(Locks::mutator_lock_) {
394 if (java_dex_file == nullptr) {
395 return true;
396 }
397 // On the Java side, the dex files are stored in the cookie field.
398 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
399 if (long_array == nullptr) {
400 // This should never happen so log a warning.
401 LOG(ERROR) << "Unexpected null cookie";
402 return false;
403 }
404 int32_t long_array_size = long_array->GetLength();
405 // Index 0 from the long array stores the oat file. The dex files start at index 1.
406 for (int32_t j = 1; j < long_array_size; ++j) {
407 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
408 long_array->GetWithoutChecks(j)));
409 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
410 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
411 // cp_dex_file can be null.
412 out_dex_files->push_back(cp_dex_file);
413 }
414 }
415 return true;
416}
417
418// Collects all the dex files loaded by the given class loader.
419// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
420// a null list of dex elements or a null dex element).
421static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
422 Handle<mirror::ClassLoader> class_loader,
423 std::vector<const DexFile*>* out_dex_files)
424 REQUIRES_SHARED(Locks::mutator_lock_) {
425 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
426
427 // All supported class loaders inherit from BaseDexClassLoader.
428 // We need to get the DexPathList and loop through it.
429 ArtField* const cookie_field =
430 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
431 ArtField* const dex_file_field =
432 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
433 ObjPtr<mirror::Object> dex_path_list =
434 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
435 GetObject(class_loader.Get());
436 CHECK(cookie_field != nullptr);
437 CHECK(dex_file_field != nullptr);
438 if (dex_path_list == nullptr) {
439 // This may be null if the current class loader is under construction and it does not
440 // have its fields setup yet.
441 return true;
442 }
443 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
444 ObjPtr<mirror::Object> dex_elements_obj =
445 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
446 GetObject(dex_path_list);
447 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
448 // at the mCookie which is a DexFile vector.
449 if (dex_elements_obj == nullptr) {
450 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
451 // and assume we have no elements.
452 return true;
453 } else {
454 StackHandleScope<1> hs(soa.Self());
455 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
456 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
457 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
458 mirror::Object* element = dex_elements->GetWithoutChecks(i);
459 if (element == nullptr) {
460 // Should never happen, log an error and break.
461 // TODO(calin): It's unclear if we should just assert here.
462 // This code was propagated to oat_file_manager from the class linker where it would
463 // throw a NPE. For now, return false which will mark this class loader as unsupported.
464 LOG(ERROR) << "Unexpected null in the dex element list";
465 return false;
466 }
467 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
468 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
469 return false;
470 }
471 }
472 }
473
474 return true;
475}
476
477static bool GetDexFilesFromDexElementsArray(
478 ScopedObjectAccessAlreadyRunnable& soa,
479 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
480 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
481 DCHECK(dex_elements != nullptr);
482
483 ArtField* const cookie_field =
484 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
485 ArtField* const dex_file_field =
486 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
487 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
488 WellKnownClasses::dalvik_system_DexPathList__Element);
489 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
490 WellKnownClasses::dalvik_system_DexFile);
491
492 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
493 mirror::Object* element = dex_elements->GetWithoutChecks(i);
494 // We can hit a null element here because this is invoked with a partially filled dex_elements
495 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
496 // list of dex files which were opened before.
497 if (element == nullptr) {
498 continue;
499 }
500
501 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
502 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
503 // a historical glitch. All the java code opens dex files using an array of Elements.
504 ObjPtr<mirror::Object> dex_file;
505 if (element_class == element->GetClass()) {
506 dex_file = dex_file_field->GetObject(element);
507 } else if (dexfile_class == element->GetClass()) {
508 dex_file = element;
509 } else {
510 LOG(ERROR) << "Unsupported element in dex_elements: "
511 << mirror::Class::PrettyClass(element->GetClass());
512 return false;
513 }
514
515 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
516 return false;
517 }
518 }
519 return true;
520}
521
522// Adds the `class_loader` info to the `context`.
523// The dex file present in `dex_elements` array (if not null) will be added at the end of
524// the classpath.
525// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
526// BootClassLoader. Note that the class loader chain is expected to be short.
527bool ClassLoaderContext::AddInfoToContextFromClassLoader(
528 ScopedObjectAccessAlreadyRunnable& soa,
529 Handle<mirror::ClassLoader> class_loader,
530 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
531 REQUIRES_SHARED(Locks::mutator_lock_) {
532 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
533 // Nothing to do for the boot class loader as we don't add its dex files to the context.
534 return true;
535 }
536
537 ClassLoaderContext::ClassLoaderType type;
538 if (IsPathOrDexClassLoader(soa, class_loader)) {
539 type = kPathClassLoader;
540 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
541 type = kDelegateLastClassLoader;
542 } else {
543 LOG(WARNING) << "Unsupported class loader";
544 return false;
545 }
546
547 // Inspect the class loader for its dex files.
548 std::vector<const DexFile*> dex_files_loaded;
549 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
550
551 // If we have a dex_elements array extract its dex elements now.
552 // This is used in two situations:
553 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
554 // passing the list of already open dex files each time. This ensures that we see the
555 // correct context even if the ClassLoader under construction is not fully build.
556 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
557 // appending them to the current class loader. When the new code paths are loaded in
558 // BaseDexClassLoader, the paths already present in the class loader will be passed
559 // in the dex_elements array.
560 if (dex_elements != nullptr) {
561 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
562 }
563
564 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
565 ClassLoaderInfo& info = class_loader_chain_.back();
566 for (const DexFile* dex_file : dex_files_loaded) {
567 info.classpath.push_back(dex_file->GetLocation());
568 info.checksums.push_back(dex_file->GetLocationChecksum());
569 info.opened_dex_files.emplace_back(dex_file);
570 }
571
572 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
573
574 StackHandleScope<1> hs(Thread::Current());
575 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
576
577 // Note that dex_elements array is null here. The elements are considered to be part of the
578 // current class loader and are not passed to the parents.
579 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
580 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
581}
582
583std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
584 jobject class_loader,
585 jobjectArray dex_elements) {
586 ScopedObjectAccess soa(Thread::Current());
587 StackHandleScope<2> hs(soa.Self());
588 Handle<mirror::ClassLoader> h_class_loader =
589 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
590 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
591 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
592
593 CHECK(h_class_loader != nullptr);
594
595 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
596 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
597 return result;
598 } else {
599 return nullptr;
600 }
601}
602
Calin Juravle87e2cb62017-06-13 21:48:45 -0700603} // namespace art
604