blob: 4da00918843575731b28e99d95aeb66b28c79323 [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"
Vladimir Marko78baed52018-10-11 10:44:58 +010022#include "base/casts.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"
David Sehr013fd802018-01-11 22:55:24 -080027#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080028#include "dex/dex_file.h"
29#include "dex/dex_file_loader.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070030#include "handle_scope-inl.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010031#include "jni/jni_internal.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070032#include "oat_file_assistant.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070033#include "obj_ptr-inl.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070034#include "runtime.h"
35#include "scoped_thread_state_change-inl.h"
36#include "thread.h"
Calin Juravle57d0acc2017-07-11 17:41:30 -070037#include "well_known_classes.h"
Calin Juravle87e2cb62017-06-13 21:48:45 -070038
39namespace art {
40
41static constexpr char kPathClassLoaderString[] = "PCL";
42static constexpr char kDelegateLastClassLoaderString[] = "DLC";
43static constexpr char kClassLoaderOpeningMark = '[';
44static constexpr char kClassLoaderClosingMark = ']';
Calin Juravle7b0648a2017-07-07 18:40:50 -070045static constexpr char kClassLoaderSeparator = ';';
46static constexpr char kClasspathSeparator = ':';
47static constexpr char kDexFileChecksumSeparator = '*';
Calin Juravle87e2cb62017-06-13 21:48:45 -070048
49ClassLoaderContext::ClassLoaderContext()
50 : special_shared_library_(false),
51 dex_files_open_attempted_(false),
Calin Juravle57d0acc2017-07-11 17:41:30 -070052 dex_files_open_result_(false),
Calin Juravle41acdc12017-07-18 17:45:32 -070053 owns_the_dex_files_(true) {}
Calin Juravle57d0acc2017-07-11 17:41:30 -070054
55ClassLoaderContext::ClassLoaderContext(bool owns_the_dex_files)
56 : special_shared_library_(false),
57 dex_files_open_attempted_(true),
58 dex_files_open_result_(true),
59 owns_the_dex_files_(owns_the_dex_files) {}
60
61ClassLoaderContext::~ClassLoaderContext() {
62 if (!owns_the_dex_files_) {
63 // If the context does not own the dex/oat files release the unique pointers to
64 // make sure we do not de-allocate them.
65 for (ClassLoaderInfo& info : class_loader_chain_) {
66 for (std::unique_ptr<OatFile>& oat_file : info.opened_oat_files) {
67 oat_file.release();
68 }
69 for (std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
70 dex_file.release();
71 }
72 }
73 }
74}
Calin Juravle87e2cb62017-06-13 21:48:45 -070075
Calin Juravle19915892017-08-03 17:10:36 +000076std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Default() {
77 return Create("");
78}
79
Calin Juravle87e2cb62017-06-13 21:48:45 -070080std::unique_ptr<ClassLoaderContext> ClassLoaderContext::Create(const std::string& spec) {
81 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext());
82 if (result->Parse(spec)) {
83 return result;
84 } else {
85 return nullptr;
86 }
87}
88
Calin Juravle7b0648a2017-07-07 18:40:50 -070089// The expected format is: "ClassLoaderType1[ClasspathElem1*Checksum1:ClasspathElem2*Checksum2...]".
90// The checksum part of the format is expected only if parse_cheksums is true.
Calin Juravle87e2cb62017-06-13 21:48:45 -070091bool ClassLoaderContext::ParseClassLoaderSpec(const std::string& class_loader_spec,
Calin Juravle7b0648a2017-07-07 18:40:50 -070092 ClassLoaderType class_loader_type,
93 bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -070094 const char* class_loader_type_str = GetClassLoaderTypeName(class_loader_type);
95 size_t type_str_size = strlen(class_loader_type_str);
96
97 CHECK_EQ(0, class_loader_spec.compare(0, type_str_size, class_loader_type_str));
98
99 // Check the opening and closing markers.
100 if (class_loader_spec[type_str_size] != kClassLoaderOpeningMark) {
101 return false;
102 }
103 if (class_loader_spec[class_loader_spec.length() - 1] != kClassLoaderClosingMark) {
104 return false;
105 }
106
107 // At this point we know the format is ok; continue and extract the classpath.
108 // Note that class loaders with an empty class path are allowed.
109 std::string classpath = class_loader_spec.substr(type_str_size + 1,
110 class_loader_spec.length() - type_str_size - 2);
111
112 class_loader_chain_.push_back(ClassLoaderInfo(class_loader_type));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700113
114 if (!parse_checksums) {
115 Split(classpath, kClasspathSeparator, &class_loader_chain_.back().classpath);
116 } else {
117 std::vector<std::string> classpath_elements;
118 Split(classpath, kClasspathSeparator, &classpath_elements);
119 for (const std::string& element : classpath_elements) {
120 std::vector<std::string> dex_file_with_checksum;
121 Split(element, kDexFileChecksumSeparator, &dex_file_with_checksum);
122 if (dex_file_with_checksum.size() != 2) {
123 return false;
124 }
125 uint32_t checksum = 0;
Tom Cherry7bc8e8f2018-10-05 14:34:13 -0700126 if (!android::base::ParseUint(dex_file_with_checksum[1].c_str(), &checksum)) {
Calin Juravle7b0648a2017-07-07 18:40:50 -0700127 return false;
128 }
129 class_loader_chain_.back().classpath.push_back(dex_file_with_checksum[0]);
130 class_loader_chain_.back().checksums.push_back(checksum);
131 }
132 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700133
134 return true;
135}
136
137// Extracts the class loader type from the given spec.
138// Return ClassLoaderContext::kInvalidClassLoader if the class loader type is not
139// recognized.
140ClassLoaderContext::ClassLoaderType
141ClassLoaderContext::ExtractClassLoaderType(const std::string& class_loader_spec) {
142 const ClassLoaderType kValidTypes[] = {kPathClassLoader, kDelegateLastClassLoader};
143 for (const ClassLoaderType& type : kValidTypes) {
144 const char* type_str = GetClassLoaderTypeName(type);
145 if (class_loader_spec.compare(0, strlen(type_str), type_str) == 0) {
146 return type;
147 }
148 }
149 return kInvalidClassLoader;
150}
151
152// The format: ClassLoaderType1[ClasspathElem1:ClasspathElem2...];ClassLoaderType2[...]...
153// ClassLoaderType is either "PCL" (PathClassLoader) or "DLC" (DelegateLastClassLoader).
154// ClasspathElem is the path of dex/jar/apk file.
Calin Juravle7b0648a2017-07-07 18:40:50 -0700155bool ClassLoaderContext::Parse(const std::string& spec, bool parse_checksums) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700156 if (spec.empty()) {
Calin Juravle1a509c82017-07-24 16:51:21 -0700157 // By default we load the dex files in a PathClassLoader.
158 // So an empty spec is equivalent to an empty PathClassLoader (this happens when running
159 // tests)
160 class_loader_chain_.push_back(ClassLoaderInfo(kPathClassLoader));
Calin Juravle7b0648a2017-07-07 18:40:50 -0700161 return true;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700162 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700163
Calin Juravle87e2cb62017-06-13 21:48:45 -0700164 // Stop early if we detect the special shared library, which may be passed as the classpath
165 // for dex2oat when we want to skip the shared libraries check.
166 if (spec == OatFile::kSpecialSharedLibrary) {
167 LOG(INFO) << "The ClassLoaderContext is a special shared library.";
168 special_shared_library_ = true;
169 return true;
170 }
171
172 std::vector<std::string> class_loaders;
Calin Juravle7b0648a2017-07-07 18:40:50 -0700173 Split(spec, kClassLoaderSeparator, &class_loaders);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700174
175 for (const std::string& class_loader : class_loaders) {
176 ClassLoaderType type = ExtractClassLoaderType(class_loader);
177 if (type == kInvalidClassLoader) {
178 LOG(ERROR) << "Invalid class loader type: " << class_loader;
179 return false;
180 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700181 if (!ParseClassLoaderSpec(class_loader, type, parse_checksums)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700182 LOG(ERROR) << "Invalid class loader spec: " << class_loader;
183 return false;
184 }
185 }
186 return true;
187}
188
189// Opens requested class path files and appends them to opened_dex_files. If the dex files have
190// been stripped, this opens them from their oat files (which get added to opened_oat_files).
191bool ClassLoaderContext::OpenDexFiles(InstructionSet isa, const std::string& classpath_dir) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700192 if (dex_files_open_attempted_) {
193 // Do not attempt to re-open the files if we already tried.
194 return dex_files_open_result_;
195 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700196
197 dex_files_open_attempted_ = true;
198 // Assume we can open all dex files. If not, we will set this to false as we go.
199 dex_files_open_result_ = true;
200
201 if (special_shared_library_) {
202 // Nothing to open if the context is a special shared library.
203 return true;
204 }
205
206 // Note that we try to open all dex files even if some fail.
207 // We may get resource-only apks which we cannot load.
208 // TODO(calin): Refine the dex opening interface to be able to tell if an archive contains
209 // no dex files. So that we can distinguish the real failures...
David Sehr013fd802018-01-11 22:55:24 -0800210 const ArtDexFileLoader dex_file_loader;
Calin Juravle87e2cb62017-06-13 21:48:45 -0700211 for (ClassLoaderInfo& info : class_loader_chain_) {
Calin Juravlec5b215f2017-09-12 14:49:37 -0700212 size_t opened_dex_files_index = info.opened_dex_files.size();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700213 for (const std::string& cp_elem : info.classpath) {
214 // If path is relative, append it to the provided base directory.
Calin Juravle92003fe2017-09-06 02:22:57 +0000215 std::string location = cp_elem;
216 if (location[0] != '/' && !classpath_dir.empty()) {
Nicolas Geoffray06ffecf2017-11-14 10:31:54 +0000217 location = classpath_dir + (classpath_dir.back() == '/' ? "" : "/") + location;
Calin Juravle821a2592017-08-11 14:33:38 -0700218 }
219
Calin Juravle87e2cb62017-06-13 21:48:45 -0700220 std::string error_msg;
221 // When opening the dex files from the context we expect their checksum to match their
222 // contents. So pass true to verify_checksum.
David Sehr013fd802018-01-11 22:55:24 -0800223 if (!dex_file_loader.Open(location.c_str(),
224 location.c_str(),
225 Runtime::Current()->IsVerificationEnabled(),
226 /*verify_checksum*/ true,
227 &error_msg,
228 &info.opened_dex_files)) {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700229 // If we fail to open the dex file because it's been stripped, try to open the dex file
230 // from its corresponding oat file.
231 // This could happen when we need to recompile a pre-build whose dex code has been stripped.
232 // (for example, if the pre-build is only quicken and we want to re-compile it
233 // speed-profile).
234 // TODO(calin): Use the vdex directly instead of going through the oat file.
235 OatFileAssistant oat_file_assistant(location.c_str(), isa, false);
236 std::unique_ptr<OatFile> oat_file(oat_file_assistant.GetBestOatFile());
237 std::vector<std::unique_ptr<const DexFile>> oat_dex_files;
238 if (oat_file != nullptr &&
239 OatFileAssistant::LoadDexFiles(*oat_file, location, &oat_dex_files)) {
240 info.opened_oat_files.push_back(std::move(oat_file));
241 info.opened_dex_files.insert(info.opened_dex_files.end(),
242 std::make_move_iterator(oat_dex_files.begin()),
243 std::make_move_iterator(oat_dex_files.end()));
244 } else {
245 LOG(WARNING) << "Could not open dex files from location: " << location;
246 dex_files_open_result_ = false;
247 }
248 }
249 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700250
251 // We finished opening the dex files from the classpath.
252 // Now update the classpath and the checksum with the locations of the dex files.
253 //
254 // We do this because initially the classpath contains the paths of the dex files; and
255 // some of them might be multi-dexes. So in order to have a consistent view we replace all the
256 // file paths with the actual dex locations being loaded.
257 // This will allow the context to VerifyClassLoaderContextMatch which expects or multidex
258 // location in the class paths.
259 // Note that this will also remove the paths that could not be opened.
Mathieu Chartierc4440772018-04-16 14:40:56 -0700260 info.original_classpath = std::move(info.classpath);
Calin Juravlec5b215f2017-09-12 14:49:37 -0700261 info.classpath.clear();
262 info.checksums.clear();
263 for (size_t k = opened_dex_files_index; k < info.opened_dex_files.size(); k++) {
264 std::unique_ptr<const DexFile>& dex = info.opened_dex_files[k];
265 info.classpath.push_back(dex->GetLocation());
266 info.checksums.push_back(dex->GetLocationChecksum());
267 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700268 }
269
270 return dex_files_open_result_;
271}
272
273bool ClassLoaderContext::RemoveLocationsFromClassPaths(
274 const dchecked_vector<std::string>& locations) {
275 CHECK(!dex_files_open_attempted_)
276 << "RemoveLocationsFromClasspaths cannot be call after OpenDexFiles";
277
278 std::set<std::string> canonical_locations;
279 for (const std::string& location : locations) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700280 canonical_locations.insert(DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700281 }
282 bool removed_locations = false;
283 for (ClassLoaderInfo& info : class_loader_chain_) {
284 size_t initial_size = info.classpath.size();
285 auto kept_it = std::remove_if(
286 info.classpath.begin(),
287 info.classpath.end(),
288 [canonical_locations](const std::string& location) {
289 return ContainsElement(canonical_locations,
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700290 DexFileLoader::GetDexCanonicalLocation(location.c_str()));
Calin Juravle87e2cb62017-06-13 21:48:45 -0700291 });
292 info.classpath.erase(kept_it, info.classpath.end());
293 if (initial_size != info.classpath.size()) {
294 removed_locations = true;
295 }
296 }
297 return removed_locations;
298}
299
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700300std::string ClassLoaderContext::EncodeContextForDex2oat(const std::string& base_dir) const {
Mathieu Chartierc4440772018-04-16 14:40:56 -0700301 return EncodeContext(base_dir, /*for_dex2oat*/ true, /*stored_context*/ nullptr);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700302}
303
Mathieu Chartierc4440772018-04-16 14:40:56 -0700304std::string ClassLoaderContext::EncodeContextForOatFile(const std::string& base_dir,
305 ClassLoaderContext* stored_context) const {
306 return EncodeContext(base_dir, /*for_dex2oat*/ false, stored_context);
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700307}
308
309std::string ClassLoaderContext::EncodeContext(const std::string& base_dir,
Mathieu Chartierc4440772018-04-16 14:40:56 -0700310 bool for_dex2oat,
311 ClassLoaderContext* stored_context) const {
Calin Juravle87e2cb62017-06-13 21:48:45 -0700312 CheckDexFilesOpened("EncodeContextForOatFile");
313 if (special_shared_library_) {
314 return OatFile::kSpecialSharedLibrary;
315 }
316
Mathieu Chartierc4440772018-04-16 14:40:56 -0700317 if (stored_context != nullptr) {
318 DCHECK_EQ(class_loader_chain_.size(), stored_context->class_loader_chain_.size());
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;
Mathieu Chartierc4440772018-04-16 14:40:56 -0700339 SafeMap<std::string, std::string> remap;
340 if (stored_context != nullptr) {
341 DCHECK_EQ(info.original_classpath.size(),
342 stored_context->class_loader_chain_[i].classpath.size());
343 for (size_t k = 0; k < info.original_classpath.size(); ++k) {
344 // Note that we don't care if the same name appears twice.
345 remap.Put(info.original_classpath[k], stored_context->class_loader_chain_[i].classpath[k]);
346 }
347 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700348 for (size_t k = 0; k < info.opened_dex_files.size(); k++) {
349 const std::unique_ptr<const DexFile>& dex_file = info.opened_dex_files[k];
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700350 if (for_dex2oat) {
351 // dex2oat only needs the base location. It cannot accept multidex locations.
352 // So ensure we only add each file once.
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700353 bool new_insert = seen_locations.insert(
354 DexFileLoader::GetBaseLocation(dex_file->GetLocation())).second;
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700355 if (!new_insert) {
356 continue;
357 }
358 }
Mathieu Chartierc4440772018-04-16 14:40:56 -0700359 std::string location = dex_file->GetLocation();
360 // If there is a stored class loader remap, fix up the multidex strings.
361 if (!remap.empty()) {
362 std::string base_dex_location = DexFileLoader::GetBaseLocation(location);
363 auto it = remap.find(base_dex_location);
364 CHECK(it != remap.end()) << base_dex_location;
365 location = it->second + DexFileLoader::GetMultiDexSuffix(location);
366 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700367 if (k > 0) {
368 out << kClasspathSeparator;
369 }
370 // Find paths that were relative and convert them back from absolute.
371 if (!base_dir.empty() && location.substr(0, base_dir.length()) == base_dir) {
372 out << location.substr(base_dir.length() + 1).c_str();
373 } else {
Mathieu Chartierc4440772018-04-16 14:40:56 -0700374 out << location.c_str();
Calin Juravle7b0648a2017-07-07 18:40:50 -0700375 }
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700376 // dex2oat does not need the checksums.
377 if (!for_dex2oat) {
378 out << kDexFileChecksumSeparator;
379 out << dex_file->GetLocationChecksum();
380 }
Calin Juravle7b0648a2017-07-07 18:40:50 -0700381 }
382 out << kClassLoaderClosingMark;
383 }
384 return out.str();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700385}
386
387jobject ClassLoaderContext::CreateClassLoader(
388 const std::vector<const DexFile*>& compilation_sources) const {
389 CheckDexFilesOpened("CreateClassLoader");
390
391 Thread* self = Thread::Current();
392 ScopedObjectAccess soa(self);
393
Calin Juravlec79470d2017-07-12 17:37:42 -0700394 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
Calin Juravle87e2cb62017-06-13 21:48:45 -0700395
Calin Juravlec79470d2017-07-12 17:37:42 -0700396 if (class_loader_chain_.empty()) {
397 return class_linker->CreatePathClassLoader(self, compilation_sources);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700398 }
399
Calin Juravlec79470d2017-07-12 17:37:42 -0700400 // Create the class loaders starting from the top most parent (the one on the last position
401 // in the chain) but omit the first class loader which will contain the compilation_sources and
402 // needs special handling.
403 jobject current_parent = nullptr; // the starting parent is the BootClassLoader.
404 for (size_t i = class_loader_chain_.size() - 1; i > 0; i--) {
405 std::vector<const DexFile*> class_path_files = MakeNonOwningPointerVector(
406 class_loader_chain_[i].opened_dex_files);
407 current_parent = class_linker->CreateWellKnownClassLoader(
408 self,
409 class_path_files,
410 GetClassLoaderClass(class_loader_chain_[i].type),
411 current_parent);
412 }
Calin Juravle87e2cb62017-06-13 21:48:45 -0700413
Calin Juravlec79470d2017-07-12 17:37:42 -0700414 // We set up all the parents. Move on to create the first class loader.
415 // Its classpath comes first, followed by compilation sources. This ensures that whenever
416 // we need to resolve classes from it the classpath elements come first.
417
418 std::vector<const DexFile*> first_class_loader_classpath = MakeNonOwningPointerVector(
419 class_loader_chain_[0].opened_dex_files);
420 first_class_loader_classpath.insert(first_class_loader_classpath.end(),
421 compilation_sources.begin(),
422 compilation_sources.end());
423
424 return class_linker->CreateWellKnownClassLoader(
425 self,
426 first_class_loader_classpath,
427 GetClassLoaderClass(class_loader_chain_[0].type),
428 current_parent);
Calin Juravle87e2cb62017-06-13 21:48:45 -0700429}
430
431std::vector<const DexFile*> ClassLoaderContext::FlattenOpenedDexFiles() const {
432 CheckDexFilesOpened("FlattenOpenedDexFiles");
433
434 std::vector<const DexFile*> result;
435 for (const ClassLoaderInfo& info : class_loader_chain_) {
436 for (const std::unique_ptr<const DexFile>& dex_file : info.opened_dex_files) {
437 result.push_back(dex_file.get());
438 }
439 }
440 return result;
441}
442
443const char* ClassLoaderContext::GetClassLoaderTypeName(ClassLoaderType type) {
444 switch (type) {
445 case kPathClassLoader: return kPathClassLoaderString;
446 case kDelegateLastClassLoader: return kDelegateLastClassLoaderString;
447 default:
448 LOG(FATAL) << "Invalid class loader type " << type;
449 UNREACHABLE();
450 }
451}
452
453void ClassLoaderContext::CheckDexFilesOpened(const std::string& calling_method) const {
454 CHECK(dex_files_open_attempted_)
455 << "Dex files were not successfully opened before the call to " << calling_method
456 << "attempt=" << dex_files_open_attempted_ << ", result=" << dex_files_open_result_;
457}
Calin Juravle7b0648a2017-07-07 18:40:50 -0700458
Calin Juravle57d0acc2017-07-11 17:41:30 -0700459// Collects the dex files from the give Java dex_file object. Only the dex files with
460// at least 1 class are collected. If a null java_dex_file is passed this method does nothing.
461static bool CollectDexFilesFromJavaDexFile(ObjPtr<mirror::Object> java_dex_file,
462 ArtField* const cookie_field,
463 std::vector<const DexFile*>* out_dex_files)
464 REQUIRES_SHARED(Locks::mutator_lock_) {
465 if (java_dex_file == nullptr) {
466 return true;
467 }
468 // On the Java side, the dex files are stored in the cookie field.
469 mirror::LongArray* long_array = cookie_field->GetObject(java_dex_file)->AsLongArray();
470 if (long_array == nullptr) {
471 // This should never happen so log a warning.
472 LOG(ERROR) << "Unexpected null cookie";
473 return false;
474 }
475 int32_t long_array_size = long_array->GetLength();
476 // Index 0 from the long array stores the oat file. The dex files start at index 1.
477 for (int32_t j = 1; j < long_array_size; ++j) {
Vladimir Marko78baed52018-10-11 10:44:58 +0100478 const DexFile* cp_dex_file =
479 reinterpret_cast64<const DexFile*>(long_array->GetWithoutChecks(j));
Calin Juravle57d0acc2017-07-11 17:41:30 -0700480 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
481 // TODO(calin): It's unclear why the dex files with no classes are skipped here and when
482 // cp_dex_file can be null.
483 out_dex_files->push_back(cp_dex_file);
484 }
485 }
486 return true;
487}
488
489// Collects all the dex files loaded by the given class loader.
490// Returns true for success or false if an unexpected state is discovered (e.g. a null dex cookie,
491// a null list of dex elements or a null dex element).
492static bool CollectDexFilesFromSupportedClassLoader(ScopedObjectAccessAlreadyRunnable& soa,
493 Handle<mirror::ClassLoader> class_loader,
494 std::vector<const DexFile*>* out_dex_files)
495 REQUIRES_SHARED(Locks::mutator_lock_) {
496 CHECK(IsPathOrDexClassLoader(soa, class_loader) || IsDelegateLastClassLoader(soa, class_loader));
497
498 // All supported class loaders inherit from BaseDexClassLoader.
499 // We need to get the DexPathList and loop through it.
500 ArtField* const cookie_field =
501 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
502 ArtField* const dex_file_field =
503 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
504 ObjPtr<mirror::Object> dex_path_list =
505 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
506 GetObject(class_loader.Get());
507 CHECK(cookie_field != nullptr);
508 CHECK(dex_file_field != nullptr);
509 if (dex_path_list == nullptr) {
510 // This may be null if the current class loader is under construction and it does not
511 // have its fields setup yet.
512 return true;
513 }
514 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
515 ObjPtr<mirror::Object> dex_elements_obj =
516 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
517 GetObject(dex_path_list);
518 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
519 // at the mCookie which is a DexFile vector.
520 if (dex_elements_obj == nullptr) {
521 // TODO(calin): It's unclear if we should just assert here. For now be prepared for the worse
522 // and assume we have no elements.
523 return true;
524 } else {
525 StackHandleScope<1> hs(soa.Self());
526 Handle<mirror::ObjectArray<mirror::Object>> dex_elements(
527 hs.NewHandle(dex_elements_obj->AsObjectArray<mirror::Object>()));
528 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
529 mirror::Object* element = dex_elements->GetWithoutChecks(i);
530 if (element == nullptr) {
531 // Should never happen, log an error and break.
532 // TODO(calin): It's unclear if we should just assert here.
533 // This code was propagated to oat_file_manager from the class linker where it would
534 // throw a NPE. For now, return false which will mark this class loader as unsupported.
535 LOG(ERROR) << "Unexpected null in the dex element list";
536 return false;
537 }
538 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
539 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
540 return false;
541 }
542 }
543 }
544
545 return true;
546}
547
548static bool GetDexFilesFromDexElementsArray(
549 ScopedObjectAccessAlreadyRunnable& soa,
550 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
551 std::vector<const DexFile*>* out_dex_files) REQUIRES_SHARED(Locks::mutator_lock_) {
552 DCHECK(dex_elements != nullptr);
553
554 ArtField* const cookie_field =
555 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
556 ArtField* const dex_file_field =
557 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
558 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
559 WellKnownClasses::dalvik_system_DexPathList__Element);
560 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
561 WellKnownClasses::dalvik_system_DexFile);
562
563 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
564 mirror::Object* element = dex_elements->GetWithoutChecks(i);
565 // We can hit a null element here because this is invoked with a partially filled dex_elements
566 // array from DexPathList. DexPathList will open each dex sequentially, each time passing the
567 // list of dex files which were opened before.
568 if (element == nullptr) {
569 continue;
570 }
571
572 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
573 // TODO(calin): Code caried over oat_file_manager: supporting both classes seem to be
574 // a historical glitch. All the java code opens dex files using an array of Elements.
575 ObjPtr<mirror::Object> dex_file;
576 if (element_class == element->GetClass()) {
577 dex_file = dex_file_field->GetObject(element);
578 } else if (dexfile_class == element->GetClass()) {
579 dex_file = element;
580 } else {
581 LOG(ERROR) << "Unsupported element in dex_elements: "
582 << mirror::Class::PrettyClass(element->GetClass());
583 return false;
584 }
585
586 if (!CollectDexFilesFromJavaDexFile(dex_file, cookie_field, out_dex_files)) {
587 return false;
588 }
589 }
590 return true;
591}
592
593// Adds the `class_loader` info to the `context`.
594// The dex file present in `dex_elements` array (if not null) will be added at the end of
595// the classpath.
596// This method is recursive (w.r.t. the class loader parent) and will stop once it reaches the
597// BootClassLoader. Note that the class loader chain is expected to be short.
598bool ClassLoaderContext::AddInfoToContextFromClassLoader(
599 ScopedObjectAccessAlreadyRunnable& soa,
600 Handle<mirror::ClassLoader> class_loader,
601 Handle<mirror::ObjectArray<mirror::Object>> dex_elements)
602 REQUIRES_SHARED(Locks::mutator_lock_) {
603 if (ClassLinker::IsBootClassLoader(soa, class_loader.Get())) {
604 // Nothing to do for the boot class loader as we don't add its dex files to the context.
605 return true;
606 }
607
608 ClassLoaderContext::ClassLoaderType type;
609 if (IsPathOrDexClassLoader(soa, class_loader)) {
610 type = kPathClassLoader;
611 } else if (IsDelegateLastClassLoader(soa, class_loader)) {
612 type = kDelegateLastClassLoader;
613 } else {
614 LOG(WARNING) << "Unsupported class loader";
615 return false;
616 }
617
618 // Inspect the class loader for its dex files.
619 std::vector<const DexFile*> dex_files_loaded;
620 CollectDexFilesFromSupportedClassLoader(soa, class_loader, &dex_files_loaded);
621
622 // If we have a dex_elements array extract its dex elements now.
623 // This is used in two situations:
624 // 1) when a new ClassLoader is created DexPathList will open each dex file sequentially
625 // passing the list of already open dex files each time. This ensures that we see the
626 // correct context even if the ClassLoader under construction is not fully build.
627 // 2) when apk splits are loaded on the fly, the framework will load their dex files by
628 // appending them to the current class loader. When the new code paths are loaded in
629 // BaseDexClassLoader, the paths already present in the class loader will be passed
630 // in the dex_elements array.
631 if (dex_elements != nullptr) {
632 GetDexFilesFromDexElementsArray(soa, dex_elements, &dex_files_loaded);
633 }
634
635 class_loader_chain_.push_back(ClassLoaderContext::ClassLoaderInfo(type));
636 ClassLoaderInfo& info = class_loader_chain_.back();
637 for (const DexFile* dex_file : dex_files_loaded) {
638 info.classpath.push_back(dex_file->GetLocation());
639 info.checksums.push_back(dex_file->GetLocationChecksum());
640 info.opened_dex_files.emplace_back(dex_file);
641 }
642
643 // We created the ClassLoaderInfo for the current loader. Move on to its parent.
644
645 StackHandleScope<1> hs(Thread::Current());
646 Handle<mirror::ClassLoader> parent = hs.NewHandle(class_loader->GetParent());
647
648 // Note that dex_elements array is null here. The elements are considered to be part of the
649 // current class loader and are not passed to the parents.
650 ScopedNullHandle<mirror::ObjectArray<mirror::Object>> null_dex_elements;
651 return AddInfoToContextFromClassLoader(soa, parent, null_dex_elements);
652}
653
654std::unique_ptr<ClassLoaderContext> ClassLoaderContext::CreateContextForClassLoader(
655 jobject class_loader,
656 jobjectArray dex_elements) {
Calin Juravle3f918642017-07-11 19:04:20 -0700657 CHECK(class_loader != nullptr);
658
Calin Juravle57d0acc2017-07-11 17:41:30 -0700659 ScopedObjectAccess soa(Thread::Current());
660 StackHandleScope<2> hs(soa.Self());
661 Handle<mirror::ClassLoader> h_class_loader =
662 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
663 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
664 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
665
Calin Juravle57d0acc2017-07-11 17:41:30 -0700666 std::unique_ptr<ClassLoaderContext> result(new ClassLoaderContext(/*owns_the_dex_files*/ false));
667 if (result->AddInfoToContextFromClassLoader(soa, h_class_loader, h_dex_elements)) {
668 return result;
669 } else {
670 return nullptr;
671 }
672}
673
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700674static bool IsAbsoluteLocation(const std::string& location) {
675 return !location.empty() && location[0] == '/';
676}
677
Mathieu Chartieradc90862018-05-11 13:03:06 -0700678ClassLoaderContext::VerificationResult ClassLoaderContext::VerifyClassLoaderContextMatch(
679 const std::string& context_spec,
680 bool verify_names,
681 bool verify_checksums) const {
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700682 if (verify_names || verify_checksums) {
683 DCHECK(dex_files_open_attempted_);
684 DCHECK(dex_files_open_result_);
685 }
Calin Juravlec5b215f2017-09-12 14:49:37 -0700686
Calin Juravle3f918642017-07-11 19:04:20 -0700687 ClassLoaderContext expected_context;
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700688 if (!expected_context.Parse(context_spec, verify_checksums)) {
Calin Juravle3f918642017-07-11 19:04:20 -0700689 LOG(WARNING) << "Invalid class loader context: " << context_spec;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700690 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700691 }
692
Calin Juravlec5b215f2017-09-12 14:49:37 -0700693 // Special shared library contexts always match. They essentially instruct the runtime
694 // to ignore the class path check because the oat file is known to be loaded in different
695 // contexts. OatFileManager will further verify if the oat file can be loaded based on the
696 // collision check.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700697 if (expected_context.special_shared_library_) {
698 // Special case where we are the only entry in the class path.
699 if (class_loader_chain_.size() == 1 && class_loader_chain_[0].classpath.size() == 0) {
700 return VerificationResult::kVerifies;
701 }
702 return VerificationResult::kForcedToSkipChecks;
703 } else if (special_shared_library_) {
704 return VerificationResult::kForcedToSkipChecks;
Calin Juravle3f918642017-07-11 19:04:20 -0700705 }
706
707 if (expected_context.class_loader_chain_.size() != class_loader_chain_.size()) {
708 LOG(WARNING) << "ClassLoaderContext size mismatch. expected="
709 << expected_context.class_loader_chain_.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700710 << ", actual=" << class_loader_chain_.size()
711 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700712 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700713 }
714
715 for (size_t i = 0; i < class_loader_chain_.size(); i++) {
716 const ClassLoaderInfo& info = class_loader_chain_[i];
717 const ClassLoaderInfo& expected_info = expected_context.class_loader_chain_[i];
718 if (info.type != expected_info.type) {
719 LOG(WARNING) << "ClassLoaderContext type mismatch for position " << i
720 << ". expected=" << GetClassLoaderTypeName(expected_info.type)
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700721 << ", found=" << GetClassLoaderTypeName(info.type)
722 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700723 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700724 }
725 if (info.classpath.size() != expected_info.classpath.size()) {
726 LOG(WARNING) << "ClassLoaderContext classpath size mismatch for position " << i
727 << ". expected=" << expected_info.classpath.size()
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700728 << ", found=" << info.classpath.size()
729 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700730 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700731 }
732
Mathieu Chartierf5abfc42018-03-23 21:51:54 -0700733 if (verify_checksums) {
734 DCHECK_EQ(info.classpath.size(), info.checksums.size());
735 DCHECK_EQ(expected_info.classpath.size(), expected_info.checksums.size());
736 }
737
738 if (!verify_names) {
739 continue;
740 }
Calin Juravle3f918642017-07-11 19:04:20 -0700741
742 for (size_t k = 0; k < info.classpath.size(); k++) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700743 // Compute the dex location that must be compared.
744 // We shouldn't do a naive comparison `info.classpath[k] == expected_info.classpath[k]`
745 // because even if they refer to the same file, one could be encoded as a relative location
746 // and the other as an absolute one.
747 bool is_dex_name_absolute = IsAbsoluteLocation(info.classpath[k]);
748 bool is_expected_dex_name_absolute = IsAbsoluteLocation(expected_info.classpath[k]);
749 std::string dex_name;
750 std::string expected_dex_name;
751
752 if (is_dex_name_absolute == is_expected_dex_name_absolute) {
753 // If both locations are absolute or relative then compare them as they are.
754 // This is usually the case for: shared libraries and secondary dex files.
755 dex_name = info.classpath[k];
756 expected_dex_name = expected_info.classpath[k];
757 } else if (is_dex_name_absolute) {
758 // The runtime name is absolute but the compiled name (the expected one) is relative.
759 // This is the case for split apks which depend on base or on other splits.
760 dex_name = info.classpath[k];
761 expected_dex_name = OatFile::ResolveRelativeEncodedDexLocation(
762 info.classpath[k].c_str(), expected_info.classpath[k]);
Calin Juravle92003fe2017-09-06 02:22:57 +0000763 } else if (is_expected_dex_name_absolute) {
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700764 // The runtime name is relative but the compiled name is absolute.
765 // There is no expected use case that would end up here as dex files are always loaded
766 // with their absolute location. However, be tolerant and do the best effort (in case
767 // there are unexpected new use case...).
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700768 dex_name = OatFile::ResolveRelativeEncodedDexLocation(
769 expected_info.classpath[k].c_str(), info.classpath[k]);
770 expected_dex_name = expected_info.classpath[k];
Calin Juravle92003fe2017-09-06 02:22:57 +0000771 } else {
772 // Both locations are relative. In this case there's not much we can be sure about
773 // except that the names are the same. The checksum will ensure that the files are
774 // are same. This should not happen outside testing and manual invocations.
775 dex_name = info.classpath[k];
776 expected_dex_name = expected_info.classpath[k];
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700777 }
778
779 // Compare the locations.
780 if (dex_name != expected_dex_name) {
Calin Juravle3f918642017-07-11 19:04:20 -0700781 LOG(WARNING) << "ClassLoaderContext classpath element mismatch for position " << i
782 << ". expected=" << expected_info.classpath[k]
Andreas Gampe7d0f81c2017-07-25 18:25:41 -0700783 << ", found=" << info.classpath[k]
784 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700785 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700786 }
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700787
788 // Compare the checksums.
Calin Juravle3f918642017-07-11 19:04:20 -0700789 if (info.checksums[k] != expected_info.checksums[k]) {
790 LOG(WARNING) << "ClassLoaderContext classpath element checksum mismatch for position " << i
Calin Juravle1e96a5d2017-09-05 17:10:48 -0700791 << ". expected=" << expected_info.checksums[k]
792 << ", found=" << info.checksums[k]
793 << " (" << context_spec << " | " << EncodeContextForOatFile("") << ")";
Mathieu Chartieradc90862018-05-11 13:03:06 -0700794 return VerificationResult::kMismatch;
Calin Juravle3f918642017-07-11 19:04:20 -0700795 }
796 }
797 }
Mathieu Chartieradc90862018-05-11 13:03:06 -0700798 return VerificationResult::kVerifies;
Calin Juravle3f918642017-07-11 19:04:20 -0700799}
800
Calin Juravlec79470d2017-07-12 17:37:42 -0700801jclass ClassLoaderContext::GetClassLoaderClass(ClassLoaderType type) {
802 switch (type) {
803 case kPathClassLoader: return WellKnownClasses::dalvik_system_PathClassLoader;
804 case kDelegateLastClassLoader: return WellKnownClasses::dalvik_system_DelegateLastClassLoader;
805 case kInvalidClassLoader: break; // will fail after the switch.
806 }
807 LOG(FATAL) << "Invalid class loader type " << type;
808 UNREACHABLE();
809}
810
Calin Juravle87e2cb62017-06-13 21:48:45 -0700811} // namespace art