blob: e97c6a085060857415b306d4913a289a0f06d81e [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 Juravle821a2592017-08-11 14:33:38 -070019#include <stdlib.h>
20
21#include "android-base/file.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070022#include "art_field-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070023#include "base/dchecked_vector.h"
24#include "base/stl_util.h"
25#include "class_linker.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070026#include "class_loader_utils.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070027#include "dex_file.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070028#include "handle_scope-inl.h"
29#include "jni_internal.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070030#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070031#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070032#include "runtime.h"
33#include "scoped_thread_state_change-inl.h"
34#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070035#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070036
37namespace art {
38
39static constexpr char kPathClassLoaderString[] = "PCL";
40static constexpr char kDelegateLastClassLoaderString[] = "DLC";
41static constexpr char kClassLoaderOpeningMark = '[';
42static constexpr char kClassLoaderClosingMark = ']';
Calin Juravle7b0648a2017-07-07 18:40:50 -070043static constexpr char kClassLoaderSeparator = ';';
44static constexpr char kClasspathSeparator = ':';
45static constexpr char kDexFileChecksumSeparator = '*';
Calin Juravle87e2cb62017-06-13 21:48:45 -070046
47ClassLoaderContext::ClassLoaderContext()
48 : special_shared_library_(false),
49 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070050 dex_files_open_result_(false),
Calin Juravle41acdc12017-07-18 17:45:32 -070051 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070052
53ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
54 : special_shared_library_(false),
55 dex_files_open_attempted_(true),
56 dex_files_open_result_(true),
57 owns_the_dex_files_(owns_the_dex_files) {}
58
59ClassLoaderContext::~ClassLoaderContext() {
60 if (!owns_the_dex_files_) {
61 // If the context does not own the dex/oat files release the unique pointers to
62 // make sure we do not de-allocate them.
63 for (ClassLoaderInfo& info : class_loader_chain_) {
64 for (std::unique_ptr<OatFile>& oat_file : info.opened_oat_files) {
65 oat_file.release();
66 }
67 for (std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
68 dex_file.release();
69 }
70 }
71 }
72}
Calin Juravle87e2cb62017-06-13 21:48:45 -070073
Calin Juravle19915892017-08-03 17:10:36 +000074std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
75 return Create("");
76}
77
Calin Juravle87e2cb62017-06-13 21:48:45 -070078std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
79 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
80 if (result->Parse(spec)) {
81 return result;
82 } else {
83 return nullptr;
84 }
85}
86
Calin Juravle7b0648a2017-07-07 18:40:50 -070087// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
88// The checksum part of the format is expected only if parse_cheksums is true.
Calin Juravle87e2cb62017-06-13 21:48:45 -070089bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
Calin Juravle7b0648a2017-07-07 18:40:50 -070090 ClassLoaderType class_loader_type,
91 bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -070092 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
93 size_t type_str_size = strlen(class_loader_type_str);
94
95 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
96
97 // Check the opening and closing markers.
98 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
99 return false;
100 }
101 if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
102 return false;
103 }
104
105 // At this point we know the format is ok; continue and extract the classpath.
106 // Note that class loaders with an empty class path are allowed.
107 std::string classpath = class_loader_spec.substr(type_str_size + 1,
108 class_loader_spec.length() - type_str_size - 2);
109
110 class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700111
112 if (!parse_checksums) {
113 Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
114 } else {
115 std::vector<std::string> classpath_elements;
116 Split(classpath, kClasspathSeparator, &classpath_elements);
117 for (const std::string& element : classpath_elements) {
118 std::vector<std::string> dex_file_with_checksum;
119 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
120 if (dex_file_with_checksum.size() != 2) {
121 return false;
122 }
123 uint32_t checksum = 0;
124 if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
125 return false;
126 }
127 class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
128 class_loader_chain_.back().checksums.push_back(checksum);
129 }
130 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700131
132 return true;
133}
134
135// Extracts the class loader type from the given spec.
136// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
137// recognized.
138ClassLoaderContext::ClassLoaderType
139ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
140 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
141 for (const ClassLoaderType& type : kValidTypes) {
142 const char* type_str = GetClassLoaderTypeName(type);
143 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
144 return type;
145 }
146 }
147 return kInvalidClassLoader;
148}
149
150// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
151// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
152// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700153bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700154 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700155 // By default we load the dex files in a PathClassLoader.
156 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
157 // tests)
158 class_loader_chain_.push_back(ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700159 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700160 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700161
Calin Juravle87e2cb62017-06-13 21:48:45 -0700162 // Stop early if we detect the special shared library, which may be passed as the classpath
163 // for dex2oat when we want to skip the shared libraries check.
164 if (spec == OatFile::kSpecialSharedLibrary) {
165 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
166 special_shared_library_ = true;
167 return true;
168 }
169
170 std::vector<std::string> class_loaders;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700171 Split(spec, kClassLoaderSeparator, &class_loaders);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700172
173 for (const std::string& class_loader : class_loaders) {
174 ClassLoaderType type = ExtractClassLoaderType(class_loader);
175 if (type == kInvalidClassLoader) {
176 LOG(ERROR) << "Invalid class loader type: " << class_loader;
177 return false;
178 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700179 if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700180 LOG(ERROR) << "Invalid class loader spec: " << class_loader;
181 return false;
182 }
183 }
184 return true;
185}
186
187// Opens requested class path files and appends them to opened_dex_files. If the dex files have
188// been stripped, this opens them from their oat files (which get added to opened_oat_files).
189bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
190 CHECK(!dex_files_open_attempted_) << "OpenDexFiles should not be called twice";
191
192 dex_files_open_attempted_ = true;
193 // Assume we can open all dex files. If not, we will set this to false as we go.
194 dex_files_open_result_ = true;
195
196 if (special_shared_library_) {
197 // Nothing to open if the context is a special shared library.
198 return true;
199 }
200
201 // Note that we try to open all dex files even if some fail.
202 // We may get resource-only apks which we cannot load.
203 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
204 // no dex files. So that we can distinguish the real failures...
205 for (ClassLoaderInfo& info : class_loader_chain_) {
206 for (const std::string& cp_elem : info.classpath) {
207 // If path is relative, append it to the provided base directory.
Calin Juravle821a2592017-08-11 14:33:38 -0700208 std::string raw_location = cp_elem;
209 if (raw_location[0] != '/') {
210 raw_location = classpath_dir + '/' + raw_location;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700211 }
Calin Juravle821a2592017-08-11 14:33:38 -0700212
213 std::string location; // the real location of the class path element.
214
215 if (!android::base::Realpath(raw_location, &location)) {
216 // If we can't get the realpath of the location there might be something wrong with the
217 // classpath (maybe the file was deleted).
218 // Do not continue in this case and return false.
219 PLOG(ERROR) << "Could not get the realpath of dex location " << raw_location;
220 return false;
221 }
222
Calin Juravle87e2cb62017-06-13 21:48:45 -0700223 std::string error_msg;
224 // When opening the dex files from the context we expect their checksum to match their
225 // contents. So pass true to verify_checksum.
226 if (!DexFile::Open(location.c_str(),
227 location.c_str(),
228 /*verify_checksum*/ true,
229 &error_msg,
230 &info.opened_dex_files)) {
231 // If we fail to open the dex file because it's been stripped, try to open the dex file
232 // from its corresponding oat file.
233 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
234 // (for example, if the pre-build is only quicken and we want to re-compile it
235 // speed-profile).
236 // TODO(calin): Use the vdex directly instead of going through the oat file.
237 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
238 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
239 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
240 if (oat_file != nullptr &&
241 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
242 info.opened_oat_files.push_back(std::move(oat_file));
243 info.opened_dex_files.insert(info.opened_dex_files.end(),
244 std::make_move_iterator(oat_dex_files.begin()),
245 std::make_move_iterator(oat_dex_files.end()));
246 } else {
247 LOG(WARNING) << "Could not open dex files from location: " << location;
248 dex_files_open_result_ = false;
249 }
250 }
251 }
252 }
253
254 return dex_files_open_result_;
255}
256
257bool ClassLoaderContext::RemoveLocationsFromClassPaths(
258 const dchecked_vector<std::string>& locations) {
259 CHECK(!dex_files_open_attempted_)
260 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
261
262 std::set<std::string> canonical_locations;
263 for (const std::string& location : locations) {
264 canonical_locations.insert(DexFile::GetDexCanonicalLocation(location.c_str()));
265 }
266 bool removed_locations = false;
267 for (ClassLoaderInfo& info : class_loader_chain_) {
268 size_t initial_size = info.classpath.size();
269 auto kept_it = std::remove_if(
270 info.classpath.begin(),
271 info.classpath.end(),
272 [canonical_locations](const std::string& location) {
273 return ContainsElement(canonical_locations,
274 DexFile::GetDexCanonicalLocation(location.c_str()));
275 });
276 info.classpath.erase(kept_it, info.classpath.end());
277 if (initial_size != info.classpath.size()) {
278 removed_locations = true;
279 }
280 }
281 return removed_locations;
282}
283
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700284std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
285 return EncodeContext(base_dir, /*for_dex2oat*/ true);
286}
287
Calin Juravle87e2cb62017-06-13 21:48:45 -0700288std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700289 return EncodeContext(base_dir, /*for_dex2oat*/ false);
290}
291
292std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
293 bool for_dex2oat) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700294 CheckDexFilesOpened("EncodeContextForOatFile");
295 if (special_shared_library_) {
296 return OatFile::kSpecialSharedLibrary;
297 }
298
Calin Juravle7b0648a2017-07-07 18:40:50 -0700299 std::ostringstream out;
Calin Juravle1a509c82017-07-24 16:51:21 -0700300 if (class_loader_chain_.empty()) {
301 // We can get in this situation if the context was created with a class path containing the
302 // source dex files which were later removed (happens during run-tests).
303 out << GetClassLoaderTypeName(kPathClassLoader)
304 << kClassLoaderOpeningMark
305 << kClassLoaderClosingMark;
306 return out.str();
307 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700308
Calin Juravle7b0648a2017-07-07 18:40:50 -0700309 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
310 const ClassLoaderInfo& info = class_loader_chain_[i];
311 if (i > 0) {
312 out << kClassLoaderSeparator;
313 }
314 out << GetClassLoaderTypeName(info.type);
315 out << kClassLoaderOpeningMark;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700316 std::set<std::string> seen_locations;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700317 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
318 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700319 if (for_dex2oat) {
320 // dex2oat only needs the base location. It cannot accept multidex locations.
321 // So ensure we only add each file once.
322 bool new_insert = seen_locations.insert(dex_file->GetBaseLocation()).second;
323 if (!new_insert) {
324 continue;
325 }
326 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700327 const std::string& location = dex_file->GetLocation();
328 if (k > 0) {
329 out << kClasspathSeparator;
330 }
331 // Find paths that were relative and convert them back from absolute.
332 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
333 out << location.substr(base_dir.length() + 1).c_str();
334 } else {
335 out << dex_file->GetLocation().c_str();
336 }
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700337 // dex2oat does not need the checksums.
338 if (!for_dex2oat) {
339 out << kDexFileChecksumSeparator;
340 out << dex_file->GetLocationChecksum();
341 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700342 }
343 out << kClassLoaderClosingMark;
344 }
345 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700346}
347
348jobject ClassLoaderContext::CreateClassLoader(
349 const std::vector<const DexFile*>& compilation_sources) const {
350 CheckDexFilesOpened("CreateClassLoader");
351
352 Thread* self = Thread::Current();
353 ScopedObjectAccess soa(self);
354
Calin Juravlec79470d2017-07-12 17:37:42 -0700355 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700356
Calin Juravlec79470d2017-07-12 17:37:42 -0700357 if (class_loader_chain_.empty()) {
358 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700359 }
360
Calin Juravlec79470d2017-07-12 17:37:42 -0700361 // Create the class loaders starting from the top most parent (the one on the last position
362 // in the chain) but omit the first class loader which will contain the compilation_sources and
363 // needs special handling.
364 jobject current_parent = nullptr; // the starting parent is the BootClassLoader.
365 for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
366 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
367 class_loader_chain_[i].opened_dex_files);
368 current_parent = class_linker->CreateWellKnownClassLoader(
369 self,
370 class_path_files,
371 GetClassLoaderClass(class_loader_chain_[i].type),
372 current_parent);
373 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700374
Calin Juravlec79470d2017-07-12 17:37:42 -0700375 // We set up all the parents. Move on to create the first class loader.
376 // Its classpath comes first, followed by compilation sources. This ensures that whenever
377 // we need to resolve classes from it the classpath elements come first.
378
379 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
380 class_loader_chain_[0].opened_dex_files);
381 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
382 compilation_sources.begin(),
383 compilation_sources.end());
384
385 return class_linker->CreateWellKnownClassLoader(
386 self,
387 first_class_loader_classpath,
388 GetClassLoaderClass(class_loader_chain_[0].type),
389 current_parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700390}
391
392std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
393 CheckDexFilesOpened("FlattenOpenedDexFiles");
394
395 std::vector<const DexFile*> result;
396 for (const ClassLoaderInfo& info : class_loader_chain_) {
397 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
398 result.push_back(dex_file.get());
399 }
400 }
401 return result;
402}
403
404const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
405 switch (type) {
406 case kPathClassLoader: return kPathClassLoaderString;
407 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
408 default:
409 LOG(FATAL) << "Invalid class loader type " << type;
410 UNREACHABLE();
411 }
412}
413
414void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
415 CHECK(dex_files_open_attempted_)
416 << "Dex files were not successfully opened before the call to " << calling_method
417 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
418}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700419
Calin Juravle57d0acc2017-07-11 17:41:30 -0700420// Collects the dex files from the give Java dex_file object. Only the dex files with
421// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
422static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
423 ArtField* const cookie_field,
424 std::vector<const DexFile*>* out_dex_files)
425 REQUIRES_SHARED(Locks::mutator_lock_) {
426 if (java_dex_file == nullptr) {
427 return true;
428 }
429 // On the Java side, the dex files are stored in the cookie field.
430 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
431 if (long_array == nullptr) {
432 // This should never happen so log a warning.
433 LOG(ERROR) << "Unexpected null cookie";
434 return false;
435 }
436 int32_t long_array_size = long_array->GetLength();
437 // Index 0 from the long array stores the oat file. The dex files start at index 1.
438 for (int32_t j = 1; j < long_array_size; ++j) {
439 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
440 long_array->GetWithoutChecks(j)));
441 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
442 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
443 // cp_dex_file can be null.
444 out_dex_files->push_back(cp_dex_file);
445 }
446 }
447 return true;
448}
449
450// Collects all the dex files loaded by the given class loader.
451// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
452// a null list of dex elements or a null dex element).
453static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
454 Handle<mirror::ClassLoader> class_loader,
455 std::vector<const DexFile*>* out_dex_files)
456 REQUIRES_SHARED(Locks::mutator_lock_) {
457 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
458
459 // All supported class loaders inherit from BaseDexClassLoader.
460 // We need to get the DexPathList and loop through it.
461 ArtField* const cookie_field =
462 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
463 ArtField* const dex_file_field =
464 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
465 ObjPtr<mirror::Object> dex_path_list =
466 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
467 GetObject(class_loader.Get());
468 CHECK(cookie_field != nullptr);
469 CHECK(dex_file_field != nullptr);
470 if (dex_path_list == nullptr) {
471 // This may be null if the current class loader is under construction and it does not
472 // have its fields setup yet.
473 return true;
474 }
475 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
476 ObjPtr<mirror::Object> dex_elements_obj =
477 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
478 GetObject(dex_path_list);
479 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
480 // at the mCookie which is a DexFile vector.
481 if (dex_elements_obj == nullptr) {
482 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
483 // and assume we have no elements.
484 return true;
485 } else {
486 StackHandleScope<1> hs(soa.Self());
487 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
488 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
489 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
490 mirror::Object* element = dex_elements->GetWithoutChecks(i);
491 if (element == nullptr) {
492 // Should never happen, log an error and break.
493 // TODO(calin): It's unclear if we should just assert here.
494 // This code was propagated to oat_file_manager from the class linker where it would
495 // throw a NPE. For now, return false which will mark this class loader as unsupported.
496 LOG(ERROR) << "Unexpected null in the dex element list";
497 return false;
498 }
499 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
500 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
501 return false;
502 }
503 }
504 }
505
506 return true;
507}
508
509static bool GetDexFilesFromDexElementsArray(
510 ScopedObjectAccessAlreadyRunnable& soa,
511 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
512 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
513 DCHECK(dex_elements != nullptr);
514
515 ArtField* const cookie_field =
516 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
517 ArtField* const dex_file_field =
518 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
519 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
520 WellKnownClasses::dalvik_system_DexPathList__Element);
521 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
522 WellKnownClasses::dalvik_system_DexFile);
523
524 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
525 mirror::Object* element = dex_elements->GetWithoutChecks(i);
526 // We can hit a null element here because this is invoked with a partially filled dex_elements
527 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
528 // list of dex files which were opened before.
529 if (element == nullptr) {
530 continue;
531 }
532
533 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
534 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
535 // a historical glitch. All the java code opens dex files using an array of Elements.
536 ObjPtr<mirror::Object> dex_file;
537 if (element_class == element->GetClass()) {
538 dex_file = dex_file_field->GetObject(element);
539 } else if (dexfile_class == element->GetClass()) {
540 dex_file = element;
541 } else {
542 LOG(ERROR) << "Unsupported element in dex_elements: "
543 << mirror::Class::PrettyClass(element->GetClass());
544 return false;
545 }
546
547 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
548 return false;
549 }
550 }
551 return true;
552}
553
554// Adds the `class_loader` info to the `context`.
555// The dex file present in `dex_elements` array (if not null) will be added at the end of
556// the classpath.
557// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
558// BootClassLoader. Note that the class loader chain is expected to be short.
559bool ClassLoaderContext::AddInfoToContextFromClassLoader(
560 ScopedObjectAccessAlreadyRunnable& soa,
561 Handle<mirror::ClassLoader> class_loader,
562 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
563 REQUIRES_SHARED(Locks::mutator_lock_) {
564 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
565 // Nothing to do for the boot class loader as we don't add its dex files to the context.
566 return true;
567 }
568
569 ClassLoaderContext::ClassLoaderType type;
570 if (IsPathOrDexClassLoader(soa, class_loader)) {
571 type = kPathClassLoader;
572 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
573 type = kDelegateLastClassLoader;
574 } else {
575 LOG(WARNING) << "Unsupported class loader";
576 return false;
577 }
578
579 // Inspect the class loader for its dex files.
580 std::vector<const DexFile*> dex_files_loaded;
581 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
582
583 // If we have a dex_elements array extract its dex elements now.
584 // This is used in two situations:
585 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
586 // passing the list of already open dex files each time. This ensures that we see the
587 // correct context even if the ClassLoader under construction is not fully build.
588 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
589 // appending them to the current class loader. When the new code paths are loaded in
590 // BaseDexClassLoader, the paths already present in the class loader will be passed
591 // in the dex_elements array.
592 if (dex_elements != nullptr) {
593 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
594 }
595
596 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
597 ClassLoaderInfo& info = class_loader_chain_.back();
598 for (const DexFile* dex_file : dex_files_loaded) {
599 info.classpath.push_back(dex_file->GetLocation());
600 info.checksums.push_back(dex_file->GetLocationChecksum());
601 info.opened_dex_files.emplace_back(dex_file);
602 }
603
604 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
605
606 StackHandleScope<1> hs(Thread::Current());
607 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
608
609 // Note that dex_elements array is null here. The elements are considered to be part of the
610 // current class loader and are not passed to the parents.
611 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
612 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
613}
614
615std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
616 jobject class_loader,
617 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700618 CHECK(class_loader != nullptr);
619
Calin Juravle57d0acc2017-07-11 17:41:30 -0700620 ScopedObjectAccess soa(Thread::Current());
621 StackHandleScope<2> hs(soa.Self());
622 Handle<mirror::ClassLoader> h_class_loader =
623 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
624 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
625 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
626
Calin Juravle57d0acc2017-07-11 17:41:30 -0700627 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
628 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
629 return result;
630 } else {
631 return nullptr;
632 }
633}
634
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700635bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) const {
Calin Juravle3f918642017-07-11 19:04:20 -0700636 ClassLoaderContext expected_context;
637 if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
638 LOG(WARNING) << "Invalid class loader context: " << context_spec;
639 return false;
640 }
641
642 if (expected_context.special_shared_library_) {
643 return true;
644 }
645
646 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
647 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
648 << expected_context.class_loader_chain_.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700649 << ", actual=" << class_loader_chain_.size()
650 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700651 return false;
652 }
653
654 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
655 const ClassLoaderInfo& info = class_loader_chain_[i];
656 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
657 if (info.type != expected_info.type) {
658 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
659 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700660 << ", found=" << GetClassLoaderTypeName(info.type)
661 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700662 return false;
663 }
664 if (info.classpath.size() != expected_info.classpath.size()) {
665 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
666 << ". expected=" << expected_info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700667 << ", found=" << info.classpath.size()
668 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700669 return false;
670 }
671
672 DCHECK_EQ(info.classpath.size(), info.checksums.size());
673 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
674
675 for (size_t k = 0; k < info.classpath.size(); k++) {
676 if (info.classpath[k] != expected_info.classpath[k]) {
677 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
678 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700679 << ", found=" << info.classpath[k]
680 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700681 return false;
682 }
683 if (info.checksums[k] != expected_info.checksums[k]) {
684 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
685 << ". expected=" << expected_info.checksums[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700686 << ", found=" << info.checksums[k]
687 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700688 return false;
689 }
690 }
691 }
692 return true;
693}
694
Calin Juravlec79470d2017-07-12 17:37:42 -0700695jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
696 switch (type) {
697 case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
698 case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
699 case kInvalidClassLoader: break; // will fail after the switch.
700 }
701 LOG(FATAL) << "Invalid class loader type " << type;
702 UNREACHABLE();
703}
704
Calin Juravle87e2cb62017-06-13 21:48:45 -0700705} // namespace art
706