blob: 167533d68a796a52c8ec2b355152736241e577cd [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"
Mathieu Chartier79c87da2017-10-10 11:54:29 -070028#include "dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070029#include "handle_scope-inl.h"
30#include "jni_internal.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070031#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070032#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070033#include "runtime.h"
34#include "scoped_thread_state_change-inl.h"
35#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070036#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070037
38namespace art {
39
40static constexpr char kPathClassLoaderString[] = "PCL";
41static constexpr char kDelegateLastClassLoaderString[] = "DLC";
42static constexpr char kClassLoaderOpeningMark = '[';
43static constexpr char kClassLoaderClosingMark = ']';
Calin Juravle7b0648a2017-07-07 18:40:50 -070044static constexpr char kClassLoaderSeparator = ';';
45static constexpr char kClasspathSeparator = ':';
46static constexpr char kDexFileChecksumSeparator = '*';
Calin Juravle87e2cb62017-06-13 21:48:45 -070047
48ClassLoaderContext::ClassLoaderContext()
49 : special_shared_library_(false),
50 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070051 dex_files_open_result_(false),
Calin Juravle41acdc12017-07-18 17:45:32 -070052 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070053
54ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
55 : special_shared_library_(false),
56 dex_files_open_attempted_(true),
57 dex_files_open_result_(true),
58 owns_the_dex_files_(owns_the_dex_files) {}
59
60ClassLoaderContext::~ClassLoaderContext() {
61 if (!owns_the_dex_files_) {
62 // If the context does not own the dex/oat files release the unique pointers to
63 // make sure we do not de-allocate them.
64 for (ClassLoaderInfo& info : class_loader_chain_) {
65 for (std::unique_ptr<OatFile>& oat_file : info.opened_oat_files) {
66 oat_file.release();
67 }
68 for (std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
69 dex_file.release();
70 }
71 }
72 }
73}
Calin Juravle87e2cb62017-06-13 21:48:45 -070074
Calin Juravle19915892017-08-03 17:10:36 +000075std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
76 return Create("");
77}
78
Calin Juravle87e2cb62017-06-13 21:48:45 -070079std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
80 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
81 if (result->Parse(spec)) {
82 return result;
83 } else {
84 return nullptr;
85 }
86}
87
Calin Juravle7b0648a2017-07-07 18:40:50 -070088// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
89// The checksum part of the format is expected only if parse_cheksums is true.
Calin Juravle87e2cb62017-06-13 21:48:45 -070090bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
Calin Juravle7b0648a2017-07-07 18:40:50 -070091 ClassLoaderType class_loader_type,
92 bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -070093 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
94 size_t type_str_size = strlen(class_loader_type_str);
95
96 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
97
98 // Check the opening and closing markers.
99 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
100 return false;
101 }
102 if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
103 return false;
104 }
105
106 // At this point we know the format is ok; continue and extract the classpath.
107 // Note that class loaders with an empty class path are allowed.
108 std::string classpath = class_loader_spec.substr(type_str_size + 1,
109 class_loader_spec.length() - type_str_size - 2);
110
111 class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700112
113 if (!parse_checksums) {
114 Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
115 } else {
116 std::vector<std::string> classpath_elements;
117 Split(classpath, kClasspathSeparator, &classpath_elements);
118 for (const std::string& element : classpath_elements) {
119 std::vector<std::string> dex_file_with_checksum;
120 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
121 if (dex_file_with_checksum.size() != 2) {
122 return false;
123 }
124 uint32_t checksum = 0;
125 if (!ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
126 return false;
127 }
128 class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
129 class_loader_chain_.back().checksums.push_back(checksum);
130 }
131 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700132
133 return true;
134}
135
136// Extracts the class loader type from the given spec.
137// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
138// recognized.
139ClassLoaderContext::ClassLoaderType
140ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
141 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
142 for (const ClassLoaderType& type : kValidTypes) {
143 const char* type_str = GetClassLoaderTypeName(type);
144 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
145 return type;
146 }
147 }
148 return kInvalidClassLoader;
149}
150
151// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
152// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
153// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700154bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700155 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700156 // By default we load the dex files in a PathClassLoader.
157 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
158 // tests)
159 class_loader_chain_.push_back(ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700160 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700161 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700162
Calin Juravle87e2cb62017-06-13 21:48:45 -0700163 // Stop early if we detect the special shared library, which may be passed as the classpath
164 // for dex2oat when we want to skip the shared libraries check.
165 if (spec == OatFile::kSpecialSharedLibrary) {
166 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
167 special_shared_library_ = true;
168 return true;
169 }
170
171 std::vector<std::string> class_loaders;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700172 Split(spec, kClassLoaderSeparator, &class_loaders);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700173
174 for (const std::string& class_loader : class_loaders) {
175 ClassLoaderType type = ExtractClassLoaderType(class_loader);
176 if (type == kInvalidClassLoader) {
177 LOG(ERROR) << "Invalid class loader type: " << class_loader;
178 return false;
179 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700180 if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700181 LOG(ERROR) << "Invalid class loader spec: " << class_loader;
182 return false;
183 }
184 }
185 return true;
186}
187
188// Opens requested class path files and appends them to opened_dex_files. If the dex files have
189// been stripped, this opens them from their oat files (which get added to opened_oat_files).
190bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700191 if (dex_files_open_attempted_) {
192 // Do not attempt to re-open the files if we already tried.
193 return dex_files_open_result_;
194 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700195
196 dex_files_open_attempted_ = true;
197 // Assume we can open all dex files. If not, we will set this to false as we go.
198 dex_files_open_result_ = true;
199
200 if (special_shared_library_) {
201 // Nothing to open if the context is a special shared library.
202 return true;
203 }
204
205 // Note that we try to open all dex files even if some fail.
206 // We may get resource-only apks which we cannot load.
207 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
208 // no dex files. So that we can distinguish the real failures...
209 for (ClassLoaderInfo& info : class_loader_chain_) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700210 size_t opened_dex_files_index = info.opened_dex_files.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700211 for (const std::string& cp_elem : info.classpath) {
212 // If path is relative, append it to the provided base directory.
Calin Juravle821a2592017-08-11 14:33:38 -0700213 std::string raw_location = cp_elem;
Andreas Gampe72527382017-09-02 16:53:03 -0700214 if (raw_location[0] != '/' && !classpath_dir.empty()) {
Calin Juravle821a2592017-08-11 14:33:38 -0700215 raw_location = classpath_dir + '/' + raw_location;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700216 }
Calin Juravle821a2592017-08-11 14:33:38 -0700217
218 std::string location; // the real location of the class path element.
219
220 if (!android::base::Realpath(raw_location, &location)) {
221 // If we can't get the realpath of the location there might be something wrong with the
222 // classpath (maybe the file was deleted).
223 // Do not continue in this case and return false.
Alex Light91842ae2017-09-07 14:15:28 -0700224 PLOG(WARNING) << "Could not get the realpath of dex location " << raw_location;
Calin Juravle821a2592017-08-11 14:33:38 -0700225 return false;
226 }
227
Calin Juravle87e2cb62017-06-13 21:48:45 -0700228 std::string error_msg;
229 // When opening the dex files from the context we expect their checksum to match their
230 // contents. So pass true to verify_checksum.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700231 if (!DexFileLoader::Open(location.c_str(),
232 location.c_str(),
233 /*verify_checksum*/ true,
234 &error_msg,
235 &info.opened_dex_files)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700236 // If we fail to open the dex file because it's been stripped, try to open the dex file
237 // from its corresponding oat file.
238 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
239 // (for example, if the pre-build is only quicken and we want to re-compile it
240 // speed-profile).
241 // TODO(calin): Use the vdex directly instead of going through the oat file.
242 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
243 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
244 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
245 if (oat_file != nullptr &&
246 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
247 info.opened_oat_files.push_back(std::move(oat_file));
248 info.opened_dex_files.insert(info.opened_dex_files.end(),
249 std::make_move_iterator(oat_dex_files.begin()),
250 std::make_move_iterator(oat_dex_files.end()));
251 } else {
252 LOG(WARNING) << "Could not open dex files from location: " << location;
253 dex_files_open_result_ = false;
254 }
255 }
256 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700257
258 // We finished opening the dex files from the classpath.
259 // Now update the classpath and the checksum with the locations of the dex files.
260 //
261 // We do this because initially the classpath contains the paths of the dex files; and
262 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
263 // file paths with the actual dex locations being loaded.
264 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
265 // location in the class paths.
266 // Note that this will also remove the paths that could not be opened.
267 info.classpath.clear();
268 info.checksums.clear();
269 for (size_t k = opened_dex_files_index; k < info.opened_dex_files.size(); k++) {
270 std::unique_ptr<const DexFile>& dex = info.opened_dex_files[k];
271 info.classpath.push_back(dex->GetLocation());
272 info.checksums.push_back(dex->GetLocationChecksum());
273 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700274 }
275
276 return dex_files_open_result_;
277}
278
279bool ClassLoaderContext::RemoveLocationsFromClassPaths(
280 const dchecked_vector<std::string>& locations) {
281 CHECK(!dex_files_open_attempted_)
282 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
283
284 std::set<std::string> canonical_locations;
285 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700286 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700287 }
288 bool removed_locations = false;
289 for (ClassLoaderInfo& info : class_loader_chain_) {
290 size_t initial_size = info.classpath.size();
291 auto kept_it = std::remove_if(
292 info.classpath.begin(),
293 info.classpath.end(),
294 [canonical_locations](const std::string& location) {
295 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700296 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700297 });
298 info.classpath.erase(kept_it, info.classpath.end());
299 if (initial_size != info.classpath.size()) {
300 removed_locations = true;
301 }
302 }
303 return removed_locations;
304}
305
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700306std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
307 return EncodeContext(base_dir, /*for_dex2oat*/ true);
308}
309
Calin Juravle87e2cb62017-06-13 21:48:45 -0700310std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir) const {
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700311 return EncodeContext(base_dir, /*for_dex2oat*/ false);
312}
313
314std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
315 bool for_dex2oat) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700316 CheckDexFilesOpened("EncodeContextForOatFile");
317 if (special_shared_library_) {
318 return OatFile::kSpecialSharedLibrary;
319 }
320
Calin Juravle7b0648a2017-07-07 18:40:50 -0700321 std::ostringstream out;
Calin Juravle1a509c82017-07-24 16:51:21 -0700322 if (class_loader_chain_.empty()) {
323 // We can get in this situation if the context was created with a class path containing the
324 // source dex files which were later removed (happens during run-tests).
325 out << GetClassLoaderTypeName(kPathClassLoader)
326 << kClassLoaderOpeningMark
327 << kClassLoaderClosingMark;
328 return out.str();
329 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700330
Calin Juravle7b0648a2017-07-07 18:40:50 -0700331 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
332 const ClassLoaderInfo& info = class_loader_chain_[i];
333 if (i > 0) {
334 out << kClassLoaderSeparator;
335 }
336 out << GetClassLoaderTypeName(info.type);
337 out << kClassLoaderOpeningMark;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700338 std::set<std::string> seen_locations;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700339 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
340 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700341 if (for_dex2oat) {
342 // dex2oat only needs the base location. It cannot accept multidex locations.
343 // So ensure we only add each file once.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700344 bool new_insert = seen_locations.insert(
345 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700346 if (!new_insert) {
347 continue;
348 }
349 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700350 const std::string& location = dex_file->GetLocation();
351 if (k > 0) {
352 out << kClasspathSeparator;
353 }
354 // Find paths that were relative and convert them back from absolute.
355 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
356 out << location.substr(base_dir.length() + 1).c_str();
357 } else {
358 out << dex_file->GetLocation().c_str();
359 }
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700360 // dex2oat does not need the checksums.
361 if (!for_dex2oat) {
362 out << kDexFileChecksumSeparator;
363 out << dex_file->GetLocationChecksum();
364 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700365 }
366 out << kClassLoaderClosingMark;
367 }
368 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700369}
370
371jobject ClassLoaderContext::CreateClassLoader(
372 const std::vector<const DexFile*>& compilation_sources) const {
373 CheckDexFilesOpened("CreateClassLoader");
374
375 Thread* self = Thread::Current();
376 ScopedObjectAccess soa(self);
377
Calin Juravlec79470d2017-07-12 17:37:42 -0700378 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700379
Calin Juravlec79470d2017-07-12 17:37:42 -0700380 if (class_loader_chain_.empty()) {
381 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700382 }
383
Calin Juravlec79470d2017-07-12 17:37:42 -0700384 // Create the class loaders starting from the top most parent (the one on the last position
385 // in the chain) but omit the first class loader which will contain the compilation_sources and
386 // needs special handling.
387 jobject current_parent = nullptr; // the starting parent is the BootClassLoader.
388 for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
389 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
390 class_loader_chain_[i].opened_dex_files);
391 current_parent = class_linker->CreateWellKnownClassLoader(
392 self,
393 class_path_files,
394 GetClassLoaderClass(class_loader_chain_[i].type),
395 current_parent);
396 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700397
Calin Juravlec79470d2017-07-12 17:37:42 -0700398 // We set up all the parents. Move on to create the first class loader.
399 // Its classpath comes first, followed by compilation sources. This ensures that whenever
400 // we need to resolve classes from it the classpath elements come first.
401
402 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
403 class_loader_chain_[0].opened_dex_files);
404 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
405 compilation_sources.begin(),
406 compilation_sources.end());
407
408 return class_linker->CreateWellKnownClassLoader(
409 self,
410 first_class_loader_classpath,
411 GetClassLoaderClass(class_loader_chain_[0].type),
412 current_parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700413}
414
415std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
416 CheckDexFilesOpened("FlattenOpenedDexFiles");
417
418 std::vector<const DexFile*> result;
419 for (const ClassLoaderInfo& info : class_loader_chain_) {
420 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
421 result.push_back(dex_file.get());
422 }
423 }
424 return result;
425}
426
427const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
428 switch (type) {
429 case kPathClassLoader: return kPathClassLoaderString;
430 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
431 default:
432 LOG(FATAL) << "Invalid class loader type " << type;
433 UNREACHABLE();
434 }
435}
436
437void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
438 CHECK(dex_files_open_attempted_)
439 << "Dex files were not successfully opened before the call to " << calling_method
440 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
441}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700442
Calin Juravle57d0acc2017-07-11 17:41:30 -0700443// Collects the dex files from the give Java dex_file object. Only the dex files with
444// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
445static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
446 ArtField* const cookie_field,
447 std::vector<const DexFile*>* out_dex_files)
448 REQUIRES_SHARED(Locks::mutator_lock_) {
449 if (java_dex_file == nullptr) {
450 return true;
451 }
452 // On the Java side, the dex files are stored in the cookie field.
453 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
454 if (long_array == nullptr) {
455 // This should never happen so log a warning.
456 LOG(ERROR) << "Unexpected null cookie";
457 return false;
458 }
459 int32_t long_array_size = long_array->GetLength();
460 // Index 0 from the long array stores the oat file. The dex files start at index 1.
461 for (int32_t j = 1; j < long_array_size; ++j) {
462 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
463 long_array->GetWithoutChecks(j)));
464 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
465 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
466 // cp_dex_file can be null.
467 out_dex_files->push_back(cp_dex_file);
468 }
469 }
470 return true;
471}
472
473// Collects all the dex files loaded by the given class loader.
474// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
475// a null list of dex elements or a null dex element).
476static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
477 Handle<mirror::ClassLoader> class_loader,
478 std::vector<const DexFile*>* out_dex_files)
479 REQUIRES_SHARED(Locks::mutator_lock_) {
480 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
481
482 // All supported class loaders inherit from BaseDexClassLoader.
483 // We need to get the DexPathList and loop through it.
484 ArtField* const cookie_field =
485 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
486 ArtField* const dex_file_field =
487 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
488 ObjPtr<mirror::Object> dex_path_list =
489 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
490 GetObject(class_loader.Get());
491 CHECK(cookie_field != nullptr);
492 CHECK(dex_file_field != nullptr);
493 if (dex_path_list == nullptr) {
494 // This may be null if the current class loader is under construction and it does not
495 // have its fields setup yet.
496 return true;
497 }
498 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
499 ObjPtr<mirror::Object> dex_elements_obj =
500 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
501 GetObject(dex_path_list);
502 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
503 // at the mCookie which is a DexFile vector.
504 if (dex_elements_obj == nullptr) {
505 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
506 // and assume we have no elements.
507 return true;
508 } else {
509 StackHandleScope<1> hs(soa.Self());
510 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
511 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
512 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
513 mirror::Object* element = dex_elements->GetWithoutChecks(i);
514 if (element == nullptr) {
515 // Should never happen, log an error and break.
516 // TODO(calin): It's unclear if we should just assert here.
517 // This code was propagated to oat_file_manager from the class linker where it would
518 // throw a NPE. For now, return false which will mark this class loader as unsupported.
519 LOG(ERROR) << "Unexpected null in the dex element list";
520 return false;
521 }
522 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
523 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
524 return false;
525 }
526 }
527 }
528
529 return true;
530}
531
532static bool GetDexFilesFromDexElementsArray(
533 ScopedObjectAccessAlreadyRunnable& soa,
534 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
535 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
536 DCHECK(dex_elements != nullptr);
537
538 ArtField* const cookie_field =
539 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
540 ArtField* const dex_file_field =
541 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
542 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
543 WellKnownClasses::dalvik_system_DexPathList__Element);
544 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
545 WellKnownClasses::dalvik_system_DexFile);
546
547 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
548 mirror::Object* element = dex_elements->GetWithoutChecks(i);
549 // We can hit a null element here because this is invoked with a partially filled dex_elements
550 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
551 // list of dex files which were opened before.
552 if (element == nullptr) {
553 continue;
554 }
555
556 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
557 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
558 // a historical glitch. All the java code opens dex files using an array of Elements.
559 ObjPtr<mirror::Object> dex_file;
560 if (element_class == element->GetClass()) {
561 dex_file = dex_file_field->GetObject(element);
562 } else if (dexfile_class == element->GetClass()) {
563 dex_file = element;
564 } else {
565 LOG(ERROR) << "Unsupported element in dex_elements: "
566 << mirror::Class::PrettyClass(element->GetClass());
567 return false;
568 }
569
570 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
571 return false;
572 }
573 }
574 return true;
575}
576
577// Adds the `class_loader` info to the `context`.
578// The dex file present in `dex_elements` array (if not null) will be added at the end of
579// the classpath.
580// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
581// BootClassLoader. Note that the class loader chain is expected to be short.
582bool ClassLoaderContext::AddInfoToContextFromClassLoader(
583 ScopedObjectAccessAlreadyRunnable& soa,
584 Handle<mirror::ClassLoader> class_loader,
585 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
586 REQUIRES_SHARED(Locks::mutator_lock_) {
587 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
588 // Nothing to do for the boot class loader as we don't add its dex files to the context.
589 return true;
590 }
591
592 ClassLoaderContext::ClassLoaderType type;
593 if (IsPathOrDexClassLoader(soa, class_loader)) {
594 type = kPathClassLoader;
595 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
596 type = kDelegateLastClassLoader;
597 } else {
598 LOG(WARNING) << "Unsupported class loader";
599 return false;
600 }
601
602 // Inspect the class loader for its dex files.
603 std::vector<const DexFile*> dex_files_loaded;
604 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
605
606 // If we have a dex_elements array extract its dex elements now.
607 // This is used in two situations:
608 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
609 // passing the list of already open dex files each time. This ensures that we see the
610 // correct context even if the ClassLoader under construction is not fully build.
611 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
612 // appending them to the current class loader. When the new code paths are loaded in
613 // BaseDexClassLoader, the paths already present in the class loader will be passed
614 // in the dex_elements array.
615 if (dex_elements != nullptr) {
616 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
617 }
618
619 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
620 ClassLoaderInfo& info = class_loader_chain_.back();
621 for (const DexFile* dex_file : dex_files_loaded) {
622 info.classpath.push_back(dex_file->GetLocation());
623 info.checksums.push_back(dex_file->GetLocationChecksum());
624 info.opened_dex_files.emplace_back(dex_file);
625 }
626
627 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
628
629 StackHandleScope<1> hs(Thread::Current());
630 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
631
632 // Note that dex_elements array is null here. The elements are considered to be part of the
633 // current class loader and are not passed to the parents.
634 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
635 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
636}
637
638std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
639 jobject class_loader,
640 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700641 CHECK(class_loader != nullptr);
642
Calin Juravle57d0acc2017-07-11 17:41:30 -0700643 ScopedObjectAccess soa(Thread::Current());
644 StackHandleScope<2> hs(soa.Self());
645 Handle<mirror::ClassLoader> h_class_loader =
646 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
647 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
648 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
649
Calin Juravle57d0acc2017-07-11 17:41:30 -0700650 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
651 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
652 return result;
653 } else {
654 return nullptr;
655 }
656}
657
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700658static bool IsAbsoluteLocation(const std::string& location) {
659 return !location.empty() && location[0] == '/';
660}
661
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700662bool ClassLoaderContext::VerifyClassLoaderContextMatch(const std::string& context_spec) const {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700663 DCHECK(dex_files_open_attempted_);
664 DCHECK(dex_files_open_result_);
665
Calin Juravle3f918642017-07-11 19:04:20 -0700666 ClassLoaderContext expected_context;
667 if (!expected_context.Parse(context_spec, /*parse_checksums*/ true)) {
668 LOG(WARNING) << "Invalid class loader context: " << context_spec;
669 return false;
670 }
671
Calin Juravlec5b215f2017-09-12 14:49:37 -0700672 // Special shared library contexts always match. They essentially instruct the runtime
673 // to ignore the class path check because the oat file is known to be loaded in different
674 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
675 // collision check.
676 if (special_shared_library_ || expected_context.special_shared_library_) {
Calin Juravle3f918642017-07-11 19:04:20 -0700677 return true;
678 }
679
680 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
681 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
682 << expected_context.class_loader_chain_.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700683 << ", actual=" << class_loader_chain_.size()
684 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700685 return false;
686 }
687
688 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
689 const ClassLoaderInfo& info = class_loader_chain_[i];
690 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
691 if (info.type != expected_info.type) {
692 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
693 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700694 << ", found=" << GetClassLoaderTypeName(info.type)
695 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700696 return false;
697 }
698 if (info.classpath.size() != expected_info.classpath.size()) {
699 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
700 << ". expected=" << expected_info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700701 << ", found=" << info.classpath.size()
702 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700703 return false;
704 }
705
706 DCHECK_EQ(info.classpath.size(), info.checksums.size());
707 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
708
709 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700710 // Compute the dex location that must be compared.
711 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
712 // because even if they refer to the same file, one could be encoded as a relative location
713 // and the other as an absolute one.
714 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
715 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
716 std::string dex_name;
717 std::string expected_dex_name;
718
719 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
720 // If both locations are absolute or relative then compare them as they are.
721 // This is usually the case for: shared libraries and secondary dex files.
722 dex_name = info.classpath[k];
723 expected_dex_name = expected_info.classpath[k];
724 } else if (is_dex_name_absolute) {
725 // The runtime name is absolute but the compiled name (the expected one) is relative.
726 // This is the case for split apks which depend on base or on other splits.
727 dex_name = info.classpath[k];
728 expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
729 info.classpath[k].c_str(), expected_info.classpath[k]);
730 } else {
731 // The runtime name is relative but the compiled name is absolute.
732 // There is no expected use case that would end up here as dex files are always loaded
733 // with their absolute location. However, be tolerant and do the best effort (in case
734 // there are unexpected new use case...).
735 DCHECK(is_expected_dex_name_absolute);
736 dex_name = OatFile::ResolveRelativeEncodedDexLocation(
737 expected_info.classpath[k].c_str(), info.classpath[k]);
738 expected_dex_name = expected_info.classpath[k];
739 }
740
741 // Compare the locations.
742 if (dex_name != expected_dex_name) {
Calin Juravle3f918642017-07-11 19:04:20 -0700743 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
744 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700745 << ", found=" << info.classpath[k]
746 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700747 return false;
748 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700749
750 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -0700751 if (info.checksums[k] != expected_info.checksums[k]) {
752 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700753 << ". expected=" << expected_info.checksums[k]
754 << ", found=" << info.checksums[k]
755 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Calin Juravle3f918642017-07-11 19:04:20 -0700756 return false;
757 }
758 }
759 }
760 return true;
761}
762
Calin Juravlec79470d2017-07-12 17:37:42 -0700763jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
764 switch (type) {
765 case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
766 case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
767 case kInvalidClassLoader: break; // will fail after the switch.
768 }
769 LOG(FATAL) << "Invalid class loader type " << type;
770 UNREACHABLE();
771}
772
Calin Juravle87e2cb62017-06-13 21:48:45 -0700773} // namespace art
774