blob: e7051b35d88e73867d3a87590e8c8608e1bca6dc [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
Calin Juravle19915892017-08-03 17:10:36 +000071std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
72 return Create("");
73}
74
Calin Juravle87e2cb62017-06-13 21:48:45 -070075std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
76 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
77 if (result->Parse(spec)) {
78 return result;
79 } else {
80 return nullptr;
81 }
82}
83
Calin Juravle7b0648a2017-07-07 18:40:50 -070084// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
85// The checksum part of the format is expected only if parse_cheksums is true.
Calin Juravle87e2cb62017-06-13 21:48:45 -070086bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
Calin Juravle7b0648a2017-07-07 18:40:50 -070087 ClassLoaderType class_loader_type,
88 bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -070089 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
90 size_t type_str_size = strlen(class_loader_type_str);
91
92 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
93
94 // Check the opening and closing markers.
95 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
96 return false;
97 }
98 if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
99 return false;
100 }
101
102 // At this point we know the format is ok; continue and extract the classpath.
103 // Note that class loaders with an empty class path are allowed.
104 std::string classpath = class_loader_spec.substr(type_str_size + 1,
105 class_loader_spec.length() - type_str_size - 2);
106
107 class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700108
109 if (!parse_checksums) {
110 Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
111 } else {
112 std::vector<std::string> classpath_elements;
113 Split(classpath, kClasspathSeparator, &classpath_elements);
114 for (const std::string& element : classpath_elements) {
115 std::vector<std::string> dex_file_with_checksum;
116 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
117 if (dex_file_with_checksum.size() != 2) {
118 return false;
119 }
120 uint32_t checksum = 0;
121 if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
122 return false;
123 }
124 class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
125 class_loader_chain_.back().checksums.push_back(checksum);
126 }
127 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700128
129 return true;
130}
131
132// Extracts the class loader type from the given spec.
133// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
134// recognized.
135ClassLoaderContext::ClassLoaderType
136ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
137 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
138 for (const ClassLoaderType& type : kValidTypes) {
139 const char* type_str = GetClassLoaderTypeName(type);
140 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
141 return type;
142 }
143 }
144 return kInvalidClassLoader;
145}
146
147// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
148// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
149// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700150bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700151 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700152 // By default we load the dex files in a PathClassLoader.
153 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
154 // tests)
155 class_loader_chain_.push_back(ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700156 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700157 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700158
Calin Juravle87e2cb62017-06-13 21:48:45 -0700159 // Stop early if we detect the special shared library, which may be passed as the classpath
160 // for dex2oat when we want to skip the shared libraries check.
161 if (spec == OatFile::kSpecialSharedLibrary) {
162 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
163 special_shared_library_ = true;
164 return true;
165 }
166
167 std::vector<std::string> class_loaders;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700168 Split(spec, kClassLoaderSeparator, &class_loaders);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700169
170 for (const std::string& class_loader : class_loaders) {
171 ClassLoaderType type = ExtractClassLoaderType(class_loader);
172 if (type == kInvalidClassLoader) {
173 LOG(ERROR) << "Invalid class loader type: " << class_loader;
174 return false;
175 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700176 if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700177 LOG(ERROR) << "Invalid class loader spec: " << class_loader;
178 return false;
179 }
180 }
181 return true;
182}
183
184// Opens requested class path files and appends them to opened_dex_files. If the dex files have
185// been stripped, this opens them from their oat files (which get added to opened_oat_files).
186bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
187 CHECK(!dex_files_open_attempted_) << "OpenDexFiles should not be called twice";
188
189 dex_files_open_attempted_ = true;
190 // Assume we can open all dex files. If not, we will set this to false as we go.
191 dex_files_open_result_ = true;
192
193 if (special_shared_library_) {
194 // Nothing to open if the context is a special shared library.
195 return true;
196 }
197
198 // Note that we try to open all dex files even if some fail.
199 // We may get resource-only apks which we cannot load.
200 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
201 // no dex files. So that we can distinguish the real failures...
202 for (ClassLoaderInfo& info : class_loader_chain_) {
203 for (const std::string& cp_elem : info.classpath) {
204 // If path is relative, append it to the provided base directory.
205 std::string location = cp_elem;
206 if (location[0] != '/') {
207 location = classpath_dir + '/' + location;
208 }
209 std::string error_msg;
210 // When opening the dex files from the context we expect their checksum to match their
211 // contents. So pass true to verify_checksum.
212 if (!DexFile::Open(location.c_str(),
213 location.c_str(),
214 /*verify_checksum*/ true,
215 &error_msg,
216 &info.opened_dex_files)) {
217 // If we fail to open the dex file because it's been stripped, try to open the dex file
218 // from its corresponding oat file.
219 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
220 // (for example, if the pre-build is only quicken and we want to re-compile it
221 // speed-profile).
222 // TODO(calin): Use the vdex directly instead of going through the oat file.
223 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
224 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
225 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
226 if (oat_file != nullptr &&
227 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
228 info.opened_oat_files.push_back(std::move(oat_file));
229 info.opened_dex_files.insert(info.opened_dex_files.end(),
230 std::make_move_iterator(oat_dex_files.begin()),
231 std::make_move_iterator(oat_dex_files.end()));
232 } else {
233 LOG(WARNING) << "Could not open dex files from location: " << location;
234 dex_files_open_result_ = false;
235 }
236 }
237 }
238 }
239
240 return dex_files_open_result_;
241}
242
243bool ClassLoaderContext::RemoveLocationsFromClassPaths(
244 const dchecked_vector<std::string>& locations) {
245 CHECK(!dex_files_open_attempted_)
246 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
247
248 std::set<std::string> canonical_locations;
249 for (const std::string& location : locations) {
250 canonical_locations.insert(DexFile::GetDexCanonicalLocation(location.c_str()));
251 }
252 bool removed_locations = false;
253 for (ClassLoaderInfo& info : class_loader_chain_) {
254 size_t initial_size = info.classpath.size();
255 auto kept_it = std::remove_if(
256 info.classpath.begin(),
257 info.classpath.end(),
258 [canonical_locations](const std::string& location) {
259 return ContainsElement(canonical_locations,
260 DexFile::GetDexCanonicalLocation(location.c_str()));
261 });
262 info.classpath.erase(kept_it, info.classpath.end());
263 if (initial_size != info.classpath.size()) {
264 removed_locations = true;
265 }
266 }
267 return removed_locations;
268}
269
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700270std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
271 return EncodeContext(base_dir, /*for_dex2oat*/ true);
272}
273
Calin Juravle87e2cb62017-06-13 21:48:45 -0700274std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700275 return EncodeContext(base_dir, /*for_dex2oat*/ false);
276}
277
278std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
279 bool for_dex2oat) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700280 CheckDexFilesOpened("EncodeContextForOatFile");
281 if (special_shared_library_) {
282 return OatFile::kSpecialSharedLibrary;
283 }
284
Calin Juravle7b0648a2017-07-07 18:40:50 -0700285 std::ostringstream out;
Calin Juravle1a509c82017-07-24 16:51:21 -0700286 if (class_loader_chain_.empty()) {
287 // We can get in this situation if the context was created with a class path containing the
288 // source dex files which were later removed (happens during run-tests).
289 out << GetClassLoaderTypeName(kPathClassLoader)
290 << kClassLoaderOpeningMark
291 << kClassLoaderClosingMark;
292 return out.str();
293 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700294
Calin Juravle7b0648a2017-07-07 18:40:50 -0700295 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
296 const ClassLoaderInfo& info = class_loader_chain_[i];
297 if (i > 0) {
298 out << kClassLoaderSeparator;
299 }
300 out << GetClassLoaderTypeName(info.type);
301 out << kClassLoaderOpeningMark;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700302 std::set<std::string> seen_locations;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700303 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
304 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700305 if (for_dex2oat) {
306 // dex2oat only needs the base location. It cannot accept multidex locations.
307 // So ensure we only add each file once.
308 bool new_insert = seen_locations.insert(dex_file->GetBaseLocation()).second;
309 if (!new_insert) {
310 continue;
311 }
312 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700313 const std::string& location = dex_file->GetLocation();
314 if (k > 0) {
315 out << kClasspathSeparator;
316 }
317 // Find paths that were relative and convert them back from absolute.
318 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
319 out << location.substr(base_dir.length() + 1).c_str();
320 } else {
321 out << dex_file->GetLocation().c_str();
322 }
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700323 // dex2oat does not need the checksums.
324 if (!for_dex2oat) {
325 out << kDexFileChecksumSeparator;
326 out << dex_file->GetLocationChecksum();
327 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700328 }
329 out << kClassLoaderClosingMark;
330 }
331 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700332}
333
334jobject ClassLoaderContext::CreateClassLoader(
335 const std::vector<const DexFile*>& compilation_sources) const {
336 CheckDexFilesOpened("CreateClassLoader");
337
338 Thread* self = Thread::Current();
339 ScopedObjectAccess soa(self);
340
Calin Juravlec79470d2017-07-12 17:37:42 -0700341 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700342
Calin Juravlec79470d2017-07-12 17:37:42 -0700343 if (class_loader_chain_.empty()) {
344 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700345 }
346
Calin Juravlec79470d2017-07-12 17:37:42 -0700347 // Create the class loaders starting from the top most parent (the one on the last position
348 // in the chain) but omit the first class loader which will contain the compilation_sources and
349 // needs special handling.
350 jobject current_parent = nullptr; // the starting parent is the BootClassLoader.
351 for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
352 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
353 class_loader_chain_[i].opened_dex_files);
354 current_parent = class_linker->CreateWellKnownClassLoader(
355 self,
356 class_path_files,
357 GetClassLoaderClass(class_loader_chain_[i].type),
358 current_parent);
359 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700360
Calin Juravlec79470d2017-07-12 17:37:42 -0700361 // We set up all the parents. Move on to create the first class loader.
362 // Its classpath comes first, followed by compilation sources. This ensures that whenever
363 // we need to resolve classes from it the classpath elements come first.
364
365 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
366 class_loader_chain_[0].opened_dex_files);
367 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
368 compilation_sources.begin(),
369 compilation_sources.end());
370
371 return class_linker->CreateWellKnownClassLoader(
372 self,
373 first_class_loader_classpath,
374 GetClassLoaderClass(class_loader_chain_[0].type),
375 current_parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700376}
377
378std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
379 CheckDexFilesOpened("FlattenOpenedDexFiles");
380
381 std::vector<const DexFile*> result;
382 for (const ClassLoaderInfo& info : class_loader_chain_) {
383 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
384 result.push_back(dex_file.get());
385 }
386 }
387 return result;
388}
389
390const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
391 switch (type) {
392 case kPathClassLoader: return kPathClassLoaderString;
393 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
394 default:
395 LOG(FATAL) << "Invalid class loader type " << type;
396 UNREACHABLE();
397 }
398}
399
400void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
401 CHECK(dex_files_open_attempted_)
402 << "Dex files were not successfully opened before the call to " << calling_method
403 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
404}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700405
Calin Juravle57d0acc2017-07-11 17:41:30 -0700406// Collects the dex files from the give Java dex_file object. Only the dex files with
407// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
408static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
409 ArtField* const cookie_field,
410 std::vector<const DexFile*>* out_dex_files)
411 REQUIRES_SHARED(Locks::mutator_lock_) {
412 if (java_dex_file == nullptr) {
413 return true;
414 }
415 // On the Java side, the dex files are stored in the cookie field.
416 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
417 if (long_array == nullptr) {
418 // This should never happen so log a warning.
419 LOG(ERROR) << "Unexpected null cookie";
420 return false;
421 }
422 int32_t long_array_size = long_array->GetLength();
423 // Index 0 from the long array stores the oat file. The dex files start at index 1.
424 for (int32_t j = 1; j < long_array_size; ++j) {
425 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
426 long_array->GetWithoutChecks(j)));
427 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
428 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
429 // cp_dex_file can be null.
430 out_dex_files->push_back(cp_dex_file);
431 }
432 }
433 return true;
434}
435
436// Collects all the dex files loaded by the given class loader.
437// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
438// a null list of dex elements or a null dex element).
439static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
440 Handle<mirror::ClassLoader> class_loader,
441 std::vector<const DexFile*>* out_dex_files)
442 REQUIRES_SHARED(Locks::mutator_lock_) {
443 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
444
445 // All supported class loaders inherit from BaseDexClassLoader.
446 // We need to get the DexPathList and loop through it.
447 ArtField* const cookie_field =
448 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
449 ArtField* const dex_file_field =
450 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
451 ObjPtr<mirror::Object> dex_path_list =
452 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
453 GetObject(class_loader.Get());
454 CHECK(cookie_field != nullptr);
455 CHECK(dex_file_field != nullptr);
456 if (dex_path_list == nullptr) {
457 // This may be null if the current class loader is under construction and it does not
458 // have its fields setup yet.
459 return true;
460 }
461 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
462 ObjPtr<mirror::Object> dex_elements_obj =
463 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
464 GetObject(dex_path_list);
465 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
466 // at the mCookie which is a DexFile vector.
467 if (dex_elements_obj == nullptr) {
468 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
469 // and assume we have no elements.
470 return true;
471 } else {
472 StackHandleScope<1> hs(soa.Self());
473 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
474 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
475 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
476 mirror::Object* element = dex_elements->GetWithoutChecks(i);
477 if (element == nullptr) {
478 // Should never happen, log an error and break.
479 // TODO(calin): It's unclear if we should just assert here.
480 // This code was propagated to oat_file_manager from the class linker where it would
481 // throw a NPE. For now, return false which will mark this class loader as unsupported.
482 LOG(ERROR) << "Unexpected null in the dex element list";
483 return false;
484 }
485 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
486 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
487 return false;
488 }
489 }
490 }
491
492 return true;
493}
494
495static bool GetDexFilesFromDexElementsArray(
496 ScopedObjectAccessAlreadyRunnable& soa,
497 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
498 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
499 DCHECK(dex_elements != nullptr);
500
501 ArtField* const cookie_field =
502 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
503 ArtField* const dex_file_field =
504 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
505 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
506 WellKnownClasses::dalvik_system_DexPathList__Element);
507 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
508 WellKnownClasses::dalvik_system_DexFile);
509
510 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
511 mirror::Object* element = dex_elements->GetWithoutChecks(i);
512 // We can hit a null element here because this is invoked with a partially filled dex_elements
513 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
514 // list of dex files which were opened before.
515 if (element == nullptr) {
516 continue;
517 }
518
519 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
520 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
521 // a historical glitch. All the java code opens dex files using an array of Elements.
522 ObjPtr<mirror::Object> dex_file;
523 if (element_class == element->GetClass()) {
524 dex_file = dex_file_field->GetObject(element);
525 } else if (dexfile_class == element->GetClass()) {
526 dex_file = element;
527 } else {
528 LOG(ERROR) << "Unsupported element in dex_elements: "
529 << mirror::Class::PrettyClass(element->GetClass());
530 return false;
531 }
532
533 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
534 return false;
535 }
536 }
537 return true;
538}
539
540// Adds the `class_loader` info to the `context`.
541// The dex file present in `dex_elements` array (if not null) will be added at the end of
542// the classpath.
543// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
544// BootClassLoader. Note that the class loader chain is expected to be short.
545bool ClassLoaderContext::AddInfoToContextFromClassLoader(
546 ScopedObjectAccessAlreadyRunnable& soa,
547 Handle<mirror::ClassLoader> class_loader,
548 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
549 REQUIRES_SHARED(Locks::mutator_lock_) {
550 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
551 // Nothing to do for the boot class loader as we don't add its dex files to the context.
552 return true;
553 }
554
555 ClassLoaderContext::ClassLoaderType type;
556 if (IsPathOrDexClassLoader(soa, class_loader)) {
557 type = kPathClassLoader;
558 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
559 type = kDelegateLastClassLoader;
560 } else {
561 LOG(WARNING) << "Unsupported class loader";
562 return false;
563 }
564
565 // Inspect the class loader for its dex files.
566 std::vector<const DexFile*> dex_files_loaded;
567 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
568
569 // If we have a dex_elements array extract its dex elements now.
570 // This is used in two situations:
571 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
572 // passing the list of already open dex files each time. This ensures that we see the
573 // correct context even if the ClassLoader under construction is not fully build.
574 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
575 // appending them to the current class loader. When the new code paths are loaded in
576 // BaseDexClassLoader, the paths already present in the class loader will be passed
577 // in the dex_elements array.
578 if (dex_elements != nullptr) {
579 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
580 }
581
582 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
583 ClassLoaderInfo& info = class_loader_chain_.back();
584 for (const DexFile* dex_file : dex_files_loaded) {
585 info.classpath.push_back(dex_file->GetLocation());
586 info.checksums.push_back(dex_file->GetLocationChecksum());
587 info.opened_dex_files.emplace_back(dex_file);
588 }
589
590 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
591
592 StackHandleScope<1> hs(Thread::Current());
593 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
594
595 // Note that dex_elements array is null here. The elements are considered to be part of the
596 // current class loader and are not passed to the parents.
597 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
598 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
599}
600
601std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
602 jobject class_loader,
603 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700604 CHECK(class_loader != nullptr);
605
Calin Juravle57d0acc2017-07-11 17:41:30 -0700606 ScopedObjectAccess soa(Thread::Current());
607 StackHandleScope<2> hs(soa.Self());
608 Handle<mirror::ClassLoader> h_class_loader =
609 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
610 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
611 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
612
Calin Juravle57d0acc2017-07-11 17:41:30 -0700613 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
614 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
615 return result;
616 } else {
617 return nullptr;
618 }
619}
620
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700621bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) const {
Calin Juravle3f918642017-07-11 19:04:20 -0700622 ClassLoaderContext expected_context;
623 if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
624 LOG(WARNING) << "Invalid class loader context: " << context_spec;
625 return false;
626 }
627
628 if (expected_context.special_shared_library_) {
629 return true;
630 }
631
632 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
633 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
634 << expected_context.class_loader_chain_.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700635 << ", actual=" << class_loader_chain_.size()
636 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700637 return false;
638 }
639
640 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
641 const ClassLoaderInfo& info = class_loader_chain_[i];
642 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
643 if (info.type != expected_info.type) {
644 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
645 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700646 << ", found=" << GetClassLoaderTypeName(info.type)
647 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700648 return false;
649 }
650 if (info.classpath.size() != expected_info.classpath.size()) {
651 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
652 << ". expected=" << expected_info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700653 << ", found=" << info.classpath.size()
654 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700655 return false;
656 }
657
658 DCHECK_EQ(info.classpath.size(), info.checksums.size());
659 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
660
661 for (size_t k = 0; k < info.classpath.size(); k++) {
662 if (info.classpath[k] != expected_info.classpath[k]) {
663 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
664 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700665 << ", found=" << info.classpath[k]
666 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700667 return false;
668 }
669 if (info.checksums[k] != expected_info.checksums[k]) {
670 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
671 << ". expected=" << expected_info.checksums[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700672 << ", found=" << info.checksums[k]
673 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700674 return false;
675 }
676 }
677 }
678 return true;
679}
680
Calin Juravlec79470d2017-07-12 17:37:42 -0700681jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
682 switch (type) {
683 case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
684 case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
685 case kInvalidClassLoader: break; // will fail after the switch.
686 }
687 LOG(FATAL) << "Invalid class loader type " << type;
688 UNREACHABLE();
689}
690
Calin Juravle87e2cb62017-06-13 21:48:45 -0700691} // namespace art
692