blob: f6b764ddc01e527c007c0a61f0a627ce79839590 [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
Andreas Gampef9411702018-09-06 17:16:57 -070019#include <android-base/parseint.h>
20
Calin Juravle57d0acc2017-07-11 17:41:30 -070021#include "art_field-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070022#include "base/dchecked_vector.h"
23#include "base/stl_util.h"
24#include "class_linker.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070025#include "class_loader_utils.h"
David Sehr013fd802018-01-11 22:55:24 -080026#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080027#include "dex/dex_file.h"
28#include "dex/dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070029#include "handle_scope-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010030#include "jni/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;
Andreas Gampef9411702018-09-06 17:16:57 -0700125 if (!android::base::ParseInt(dex_file_with_checksum[1].c_str(), &checksum)) {
Calin Juravle7b0648a2017-07-07 18:40:50 -0700126 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...
David Sehr013fd802018-01-11 22:55:24 -0800209 const ArtDexFileLoader dex_file_loader;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700210 for (ClassLoaderInfo& info : class_loader_chain_) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700211 size_t opened_dex_files_index = info.opened_dex_files.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700212 for (const std::string& cp_elem : info.classpath) {
213 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000214 std::string location = cp_elem;
215 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000216 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700217 }
218
Calin Juravle87e2cb62017-06-13 21:48:45 -0700219 std::string error_msg;
220 // When opening the dex files from the context we expect their checksum to match their
221 // contents. So pass true to verify_checksum.
David Sehr013fd802018-01-11 22:55:24 -0800222 if (!dex_file_loader.Open(location.c_str(),
223 location.c_str(),
224 Runtime::Current()->IsVerificationEnabled(),
225 /*verify_checksum*/ true,
226 &error_msg,
227 &info.opened_dex_files)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700228 // If we fail to open the dex file because it's been stripped, try to open the dex file
229 // from its corresponding oat file.
230 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
231 // (for example, if the pre-build is only quicken and we want to re-compile it
232 // speed-profile).
233 // TODO(calin): Use the vdex directly instead of going through the oat file.
234 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
235 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
236 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
237 if (oat_file != nullptr &&
238 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
239 info.opened_oat_files.push_back(std::move(oat_file));
240 info.opened_dex_files.insert(info.opened_dex_files.end(),
241 std::make_move_iterator(oat_dex_files.begin()),
242 std::make_move_iterator(oat_dex_files.end()));
243 } else {
244 LOG(WARNING) << "Could not open dex files from location: " << location;
245 dex_files_open_result_ = false;
246 }
247 }
248 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700249
250 // We finished opening the dex files from the classpath.
251 // Now update the classpath and the checksum with the locations of the dex files.
252 //
253 // We do this because initially the classpath contains the paths of the dex files; and
254 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
255 // file paths with the actual dex locations being loaded.
256 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
257 // location in the class paths.
258 // Note that this will also remove the paths that could not be opened.
Mathieu Chartierc4440772018-04-16 14:40:56 -0700259 info.original_classpath = std::move(info.classpath);
Calin Juravlec5b215f2017-09-12 14:49:37 -0700260 info.classpath.clear();
261 info.checksums.clear();
262 for (size_t k = opened_dex_files_index; k < info.opened_dex_files.size(); k++) {
263 std::unique_ptr<const DexFile>& dex = info.opened_dex_files[k];
264 info.classpath.push_back(dex->GetLocation());
265 info.checksums.push_back(dex->GetLocationChecksum());
266 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700267 }
268
269 return dex_files_open_result_;
270}
271
272bool ClassLoaderContext::RemoveLocationsFromClassPaths(
273 const dchecked_vector<std::string>& locations) {
274 CHECK(!dex_files_open_attempted_)
275 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
276
277 std::set<std::string> canonical_locations;
278 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700279 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700280 }
281 bool removed_locations = false;
282 for (ClassLoaderInfo& info : class_loader_chain_) {
283 size_t initial_size = info.classpath.size();
284 auto kept_it = std::remove_if(
285 info.classpath.begin(),
286 info.classpath.end(),
287 [canonical_locations](const std::string& location) {
288 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700289 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700290 });
291 info.classpath.erase(kept_it, info.classpath.end());
292 if (initial_size != info.classpath.size()) {
293 removed_locations = true;
294 }
295 }
296 return removed_locations;
297}
298
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700299std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Mathieu Chartierc4440772018-04-16 14:40:56 -0700300 return EncodeContext(base_dir, /*for_dex2oat*/ true, /*stored_context*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700301}
302
Mathieu Chartierc4440772018-04-16 14:40:56 -0700303std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
304 ClassLoaderContext* stored_context) const {
305 return EncodeContext(base_dir, /*for_dex2oat*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700306}
307
308std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700309 bool for_dex2oat,
310 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700311 CheckDexFilesOpened("EncodeContextForOatFile");
312 if (special_shared_library_) {
313 return OatFile::kSpecialSharedLibrary;
314 }
315
Mathieu Chartierc4440772018-04-16 14:40:56 -0700316 if (stored_context != nullptr) {
317 DCHECK_EQ(class_loader_chain_.size(), stored_context->class_loader_chain_.size());
318 }
319
Calin Juravle7b0648a2017-07-07 18:40:50 -0700320 std::ostringstream out;
Calin Juravle1a509c82017-07-24 16:51:21 -0700321 if (class_loader_chain_.empty()) {
322 // We can get in this situation if the context was created with a class path containing the
323 // source dex files which were later removed (happens during run-tests).
324 out << GetClassLoaderTypeName(kPathClassLoader)
325 << kClassLoaderOpeningMark
326 << kClassLoaderClosingMark;
327 return out.str();
328 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700329
Calin Juravle7b0648a2017-07-07 18:40:50 -0700330 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
331 const ClassLoaderInfo& info = class_loader_chain_[i];
332 if (i > 0) {
333 out << kClassLoaderSeparator;
334 }
335 out << GetClassLoaderTypeName(info.type);
336 out << kClassLoaderOpeningMark;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700337 std::set<std::string> seen_locations;
Mathieu Chartierc4440772018-04-16 14:40:56 -0700338 SafeMap<std::string, std::string> remap;
339 if (stored_context != nullptr) {
340 DCHECK_EQ(info.original_classpath.size(),
341 stored_context->class_loader_chain_[i].classpath.size());
342 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
343 // Note that we don't care if the same name appears twice.
344 remap.Put(info.original_classpath[k], stored_context->class_loader_chain_[i].classpath[k]);
345 }
346 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700347 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
348 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700349 if (for_dex2oat) {
350 // dex2oat only needs the base location. It cannot accept multidex locations.
351 // So ensure we only add each file once.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700352 bool new_insert = seen_locations.insert(
353 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700354 if (!new_insert) {
355 continue;
356 }
357 }
Mathieu Chartierc4440772018-04-16 14:40:56 -0700358 std::string location = dex_file->GetLocation();
359 // If there is a stored class loader remap, fix up the multidex strings.
360 if (!remap.empty()) {
361 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
362 auto it = remap.find(base_dex_location);
363 CHECK(it != remap.end()) << base_dex_location;
364 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
365 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700366 if (k > 0) {
367 out << kClasspathSeparator;
368 }
369 // Find paths that were relative and convert them back from absolute.
370 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
371 out << location.substr(base_dir.length() + 1).c_str();
372 } else {
Mathieu Chartierc4440772018-04-16 14:40:56 -0700373 out << location.c_str();
Calin Juravle7b0648a2017-07-07 18:40:50 -0700374 }
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700375 // dex2oat does not need the checksums.
376 if (!for_dex2oat) {
377 out << kDexFileChecksumSeparator;
378 out << dex_file->GetLocationChecksum();
379 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700380 }
381 out << kClassLoaderClosingMark;
382 }
383 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700384}
385
386jobject ClassLoaderContext::CreateClassLoader(
387 const std::vector<const DexFile*>& compilation_sources) const {
388 CheckDexFilesOpened("CreateClassLoader");
389
390 Thread* self = Thread::Current();
391 ScopedObjectAccess soa(self);
392
Calin Juravlec79470d2017-07-12 17:37:42 -0700393 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700394
Calin Juravlec79470d2017-07-12 17:37:42 -0700395 if (class_loader_chain_.empty()) {
396 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700397 }
398
Calin Juravlec79470d2017-07-12 17:37:42 -0700399 // Create the class loaders starting from the top most parent (the one on the last position
400 // in the chain) but omit the first class loader which will contain the compilation_sources and
401 // needs special handling.
402 jobject current_parent = nullptr; // the starting parent is the BootClassLoader.
403 for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
404 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
405 class_loader_chain_[i].opened_dex_files);
406 current_parent = class_linker->CreateWellKnownClassLoader(
407 self,
408 class_path_files,
409 GetClassLoaderClass(class_loader_chain_[i].type),
410 current_parent);
411 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700412
Calin Juravlec79470d2017-07-12 17:37:42 -0700413 // We set up all the parents. Move on to create the first class loader.
414 // Its classpath comes first, followed by compilation sources. This ensures that whenever
415 // we need to resolve classes from it the classpath elements come first.
416
417 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
418 class_loader_chain_[0].opened_dex_files);
419 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
420 compilation_sources.begin(),
421 compilation_sources.end());
422
423 return class_linker->CreateWellKnownClassLoader(
424 self,
425 first_class_loader_classpath,
426 GetClassLoaderClass(class_loader_chain_[0].type),
427 current_parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700428}
429
430std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
431 CheckDexFilesOpened("FlattenOpenedDexFiles");
432
433 std::vector<const DexFile*> result;
434 for (const ClassLoaderInfo& info : class_loader_chain_) {
435 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
436 result.push_back(dex_file.get());
437 }
438 }
439 return result;
440}
441
442const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
443 switch (type) {
444 case kPathClassLoader: return kPathClassLoaderString;
445 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
446 default:
447 LOG(FATAL) << "Invalid class loader type " << type;
448 UNREACHABLE();
449 }
450}
451
452void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
453 CHECK(dex_files_open_attempted_)
454 << "Dex files were not successfully opened before the call to " << calling_method
455 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
456}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700457
Calin Juravle57d0acc2017-07-11 17:41:30 -0700458// Collects the dex files from the give Java dex_file object. Only the dex files with
459// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
460static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
461 ArtField* const cookie_field,
462 std::vector<const DexFile*>* out_dex_files)
463 REQUIRES_SHARED(Locks::mutator_lock_) {
464 if (java_dex_file == nullptr) {
465 return true;
466 }
467 // On the Java side, the dex files are stored in the cookie field.
468 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
469 if (long_array == nullptr) {
470 // This should never happen so log a warning.
471 LOG(ERROR) << "Unexpected null cookie";
472 return false;
473 }
474 int32_t long_array_size = long_array->GetLength();
475 // Index 0 from the long array stores the oat file. The dex files start at index 1.
476 for (int32_t j = 1; j < long_array_size; ++j) {
477 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
478 long_array->GetWithoutChecks(j)));
479 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
480 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
481 // cp_dex_file can be null.
482 out_dex_files->push_back(cp_dex_file);
483 }
484 }
485 return true;
486}
487
488// Collects all the dex files loaded by the given class loader.
489// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
490// a null list of dex elements or a null dex element).
491static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
492 Handle<mirror::ClassLoader> class_loader,
493 std::vector<const DexFile*>* out_dex_files)
494 REQUIRES_SHARED(Locks::mutator_lock_) {
495 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
496
497 // All supported class loaders inherit from BaseDexClassLoader.
498 // We need to get the DexPathList and loop through it.
499 ArtField* const cookie_field =
500 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
501 ArtField* const dex_file_field =
502 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
503 ObjPtr<mirror::Object> dex_path_list =
504 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
505 GetObject(class_loader.Get());
506 CHECK(cookie_field != nullptr);
507 CHECK(dex_file_field != nullptr);
508 if (dex_path_list == nullptr) {
509 // This may be null if the current class loader is under construction and it does not
510 // have its fields setup yet.
511 return true;
512 }
513 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
514 ObjPtr<mirror::Object> dex_elements_obj =
515 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
516 GetObject(dex_path_list);
517 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
518 // at the mCookie which is a DexFile vector.
519 if (dex_elements_obj == nullptr) {
520 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
521 // and assume we have no elements.
522 return true;
523 } else {
524 StackHandleScope<1> hs(soa.Self());
525 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
526 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
527 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
528 mirror::Object* element = dex_elements->GetWithoutChecks(i);
529 if (element == nullptr) {
530 // Should never happen, log an error and break.
531 // TODO(calin): It's unclear if we should just assert here.
532 // This code was propagated to oat_file_manager from the class linker where it would
533 // throw a NPE. For now, return false which will mark this class loader as unsupported.
534 LOG(ERROR) << "Unexpected null in the dex element list";
535 return false;
536 }
537 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
538 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
539 return false;
540 }
541 }
542 }
543
544 return true;
545}
546
547static bool GetDexFilesFromDexElementsArray(
548 ScopedObjectAccessAlreadyRunnable& soa,
549 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
550 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
551 DCHECK(dex_elements != nullptr);
552
553 ArtField* const cookie_field =
554 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
555 ArtField* const dex_file_field =
556 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
557 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
558 WellKnownClasses::dalvik_system_DexPathList__Element);
559 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
560 WellKnownClasses::dalvik_system_DexFile);
561
562 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
563 mirror::Object* element = dex_elements->GetWithoutChecks(i);
564 // We can hit a null element here because this is invoked with a partially filled dex_elements
565 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
566 // list of dex files which were opened before.
567 if (element == nullptr) {
568 continue;
569 }
570
571 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
572 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
573 // a historical glitch. All the java code opens dex files using an array of Elements.
574 ObjPtr<mirror::Object> dex_file;
575 if (element_class == element->GetClass()) {
576 dex_file = dex_file_field->GetObject(element);
577 } else if (dexfile_class == element->GetClass()) {
578 dex_file = element;
579 } else {
580 LOG(ERROR) << "Unsupported element in dex_elements: "
581 << mirror::Class::PrettyClass(element->GetClass());
582 return false;
583 }
584
585 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
586 return false;
587 }
588 }
589 return true;
590}
591
592// Adds the `class_loader` info to the `context`.
593// The dex file present in `dex_elements` array (if not null) will be added at the end of
594// the classpath.
595// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
596// BootClassLoader. Note that the class loader chain is expected to be short.
597bool ClassLoaderContext::AddInfoToContextFromClassLoader(
598 ScopedObjectAccessAlreadyRunnable& soa,
599 Handle<mirror::ClassLoader> class_loader,
600 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
601 REQUIRES_SHARED(Locks::mutator_lock_) {
602 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
603 // Nothing to do for the boot class loader as we don't add its dex files to the context.
604 return true;
605 }
606
607 ClassLoaderContext::ClassLoaderType type;
608 if (IsPathOrDexClassLoader(soa, class_loader)) {
609 type = kPathClassLoader;
610 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
611 type = kDelegateLastClassLoader;
612 } else {
613 LOG(WARNING) << "Unsupported class loader";
614 return false;
615 }
616
617 // Inspect the class loader for its dex files.
618 std::vector<const DexFile*> dex_files_loaded;
619 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
620
621 // If we have a dex_elements array extract its dex elements now.
622 // This is used in two situations:
623 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
624 // passing the list of already open dex files each time. This ensures that we see the
625 // correct context even if the ClassLoader under construction is not fully build.
626 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
627 // appending them to the current class loader. When the new code paths are loaded in
628 // BaseDexClassLoader, the paths already present in the class loader will be passed
629 // in the dex_elements array.
630 if (dex_elements != nullptr) {
631 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
632 }
633
634 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
635 ClassLoaderInfo& info = class_loader_chain_.back();
636 for (const DexFile* dex_file : dex_files_loaded) {
637 info.classpath.push_back(dex_file->GetLocation());
638 info.checksums.push_back(dex_file->GetLocationChecksum());
639 info.opened_dex_files.emplace_back(dex_file);
640 }
641
642 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
643
644 StackHandleScope<1> hs(Thread::Current());
645 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
646
647 // Note that dex_elements array is null here. The elements are considered to be part of the
648 // current class loader and are not passed to the parents.
649 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
650 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
651}
652
653std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
654 jobject class_loader,
655 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700656 CHECK(class_loader != nullptr);
657
Calin Juravle57d0acc2017-07-11 17:41:30 -0700658 ScopedObjectAccess soa(Thread::Current());
659 StackHandleScope<2> hs(soa.Self());
660 Handle<mirror::ClassLoader> h_class_loader =
661 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
662 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
663 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
664
Calin Juravle57d0acc2017-07-11 17:41:30 -0700665 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
666 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
667 return result;
668 } else {
669 return nullptr;
670 }
671}
672
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700673static bool IsAbsoluteLocation(const std::string& location) {
674 return !location.empty() && location[0] == '/';
675}
676
Mathieu Chartieradc90862018-05-11 13:03:06 -0700677ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
678 const std::string& context_spec,
679 bool verify_names,
680 bool verify_checksums) const {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700681 if (verify_names || verify_checksums) {
682 DCHECK(dex_files_open_attempted_);
683 DCHECK(dex_files_open_result_);
684 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700685
Calin Juravle3f918642017-07-11 19:04:20 -0700686 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700687 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -0700688 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700689 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700690 }
691
Calin Juravlec5b215f2017-09-12 14:49:37 -0700692 // Special shared library contexts always match. They essentially instruct the runtime
693 // to ignore the class path check because the oat file is known to be loaded in different
694 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
695 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700696 if (expected_context.special_shared_library_) {
697 // Special case where we are the only entry in the class path.
698 if (class_loader_chain_.size() == 1 && class_loader_chain_[0].classpath.size() == 0) {
699 return VerificationResult::kVerifies;
700 }
701 return VerificationResult::kForcedToSkipChecks;
702 } else if (special_shared_library_) {
703 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -0700704 }
705
706 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
707 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
708 << expected_context.class_loader_chain_.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700709 << ", actual=" << class_loader_chain_.size()
710 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700711 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700712 }
713
714 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
715 const ClassLoaderInfo& info = class_loader_chain_[i];
716 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
717 if (info.type != expected_info.type) {
718 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
719 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700720 << ", found=" << GetClassLoaderTypeName(info.type)
721 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700722 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700723 }
724 if (info.classpath.size() != expected_info.classpath.size()) {
725 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
726 << ". expected=" << expected_info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700727 << ", found=" << info.classpath.size()
728 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700729 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700730 }
731
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700732 if (verify_checksums) {
733 DCHECK_EQ(info.classpath.size(), info.checksums.size());
734 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
735 }
736
737 if (!verify_names) {
738 continue;
739 }
Calin Juravle3f918642017-07-11 19:04:20 -0700740
741 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700742 // Compute the dex location that must be compared.
743 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
744 // because even if they refer to the same file, one could be encoded as a relative location
745 // and the other as an absolute one.
746 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
747 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
748 std::string dex_name;
749 std::string expected_dex_name;
750
751 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
752 // If both locations are absolute or relative then compare them as they are.
753 // This is usually the case for: shared libraries and secondary dex files.
754 dex_name = info.classpath[k];
755 expected_dex_name = expected_info.classpath[k];
756 } else if (is_dex_name_absolute) {
757 // The runtime name is absolute but the compiled name (the expected one) is relative.
758 // This is the case for split apks which depend on base or on other splits.
759 dex_name = info.classpath[k];
760 expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
761 info.classpath[k].c_str(), expected_info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +0000762 } else if (is_expected_dex_name_absolute) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700763 // The runtime name is relative but the compiled name is absolute.
764 // There is no expected use case that would end up here as dex files are always loaded
765 // with their absolute location. However, be tolerant and do the best effort (in case
766 // there are unexpected new use case...).
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700767 dex_name = OatFile::ResolveRelativeEncodedDexLocation(
768 expected_info.classpath[k].c_str(), info.classpath[k]);
769 expected_dex_name = expected_info.classpath[k];
Calin Juravle92003fe2017-09-06 02:22:57 +0000770 } else {
771 // Both locations are relative. In this case there's not much we can be sure about
772 // except that the names are the same. The checksum will ensure that the files are
773 // are same. This should not happen outside testing and manual invocations.
774 dex_name = info.classpath[k];
775 expected_dex_name = expected_info.classpath[k];
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700776 }
777
778 // Compare the locations.
779 if (dex_name != expected_dex_name) {
Calin Juravle3f918642017-07-11 19:04:20 -0700780 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
781 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700782 << ", found=" << info.classpath[k]
783 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700784 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700785 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700786
787 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -0700788 if (info.checksums[k] != expected_info.checksums[k]) {
789 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700790 << ". expected=" << expected_info.checksums[k]
791 << ", found=" << info.checksums[k]
792 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700793 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700794 }
795 }
796 }
Mathieu Chartieradc90862018-05-11 13:03:06 -0700797 return VerificationResult::kVerifies;
Calin Juravle3f918642017-07-11 19:04:20 -0700798}
799
Calin Juravlec79470d2017-07-12 17:37:42 -0700800jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
801 switch (type) {
802 case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
803 case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
804 case kInvalidClassLoader: break; // will fail after the switch.
805 }
806 LOG(FATAL) << "Invalid class loader type " << type;
807 UNREACHABLE();
808}
809
Calin Juravle87e2cb62017-06-13 21:48:45 -0700810} // namespace art