blob: 054364429a0a8ca3d76d6f282c5dd13dfdac703a [file] [log] [blame]
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001/*
2 * Copyright (C) 2015 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 "oat_file_manager.h"
18
19#include <memory>
20#include <queue>
21#include <vector>
David Brazdil35a3f6a2019-03-04 15:59:06 +000022#include <sys/stat.h>
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070023
Andreas Gampe46ee31b2016-12-14 10:11:49 -080024#include "android-base/stringprintf.h"
Nicolas Geoffray68bf3902017-09-07 14:40:48 +010025#include "android-base/strings.h"
Andreas Gampe46ee31b2016-12-14 10:11:49 -080026
Andreas Gampe90b936d2017-01-31 08:58:55 -080027#include "art_field-inl.h"
Jeff Hao8ec0a202017-03-07 21:56:31 -080028#include "base/bit_vector-inl.h"
David Sehr891a50e2017-10-27 17:01:07 -070029#include "base/file_utils.h"
Andreas Gampe57943812017-12-06 21:39:13 -080030#include "base/logging.h" // For VLOG.
Andreas Gampe7fbc4a52018-11-28 08:26:47 -080031#include "base/mutex-inl.h"
David Brazdil527072e2019-04-03 15:15:40 +010032#include "base/sdk_version.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070033#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080034#include "base/systrace.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080035#include "class_linker.h"
Calin Juravle7b0648a2017-07-07 18:40:50 -070036#include "class_loader_context.h"
David Sehr013fd802018-01-11 22:55:24 -080037#include "dex/art_dex_file_loader.h"
David Sehr9e734c72018-01-04 17:56:19 -080038#include "dex/dex_file-inl.h"
39#include "dex/dex_file_loader.h"
40#include "dex/dex_file_tracking_registrar.h"
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -080041#include "gc/scoped_gc_critical_section.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070042#include "gc/space/image_space.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080043#include "handle_scope-inl.h"
David Brazdil331a5e12019-04-01 22:46:16 +000044#include "jni/java_vm_ext.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010045#include "jni/jni_internal.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080046#include "mirror/class_loader.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -080047#include "mirror/object-inl.h"
Alex Light2ce6fc82017-12-18 16:42:36 -080048#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070049#include "oat_file_assistant.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070050#include "obj_ptr-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070051#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070052#include "thread-current-inl.h"
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -080053#include "thread_list.h"
David Brazdil331a5e12019-04-01 22:46:16 +000054#include "thread_pool.h"
David Brazdil35a3f6a2019-03-04 15:59:06 +000055#include "vdex_file.h"
56#include "verifier/verifier_deps.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -080057#include "well_known_classes.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070058
59namespace art {
60
Andreas Gampe46ee31b2016-12-14 10:11:49 -080061using android::base::StringPrintf;
62
Mathieu Chartier120aa282017-08-05 16:03:03 -070063// If true, we attempt to load the application image if it exists.
Mathieu Chartierfbc31082016-01-24 11:59:56 -080064static constexpr bool kEnableAppImage = true;
65
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070066const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070067 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Nicolas Geoffray29742602017-12-14 10:09:03 +000068 CHECK(!only_use_system_oat_files_ ||
69 LocationIsOnSystem(oat_file->GetLocation().c_str()) ||
70 !oat_file->IsExecutable())
Nicolas Geoffray68bf3902017-09-07 14:40:48 +010071 << "Registering a non /system oat file: " << oat_file->GetLocation();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070072 DCHECK(oat_file != nullptr);
73 if (kIsDebugBuild) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070074 CHECK(oat_files_.find(oat_file) == oat_files_.end());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070075 for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
76 CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
77 // Check that we don't have an oat file with the same address. Copies of the same oat file
78 // should be loaded at different addresses.
79 CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
80 }
81 }
Mathieu Chartiere58991b2015-10-13 07:59:34 -070082 const OatFile* ret = oat_file.get();
83 oat_files_.insert(std::move(oat_file));
84 return ret;
85}
86
87void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
88 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
89 DCHECK(oat_file != nullptr);
90 std::unique_ptr<const OatFile> compare(oat_file);
91 auto it = oat_files_.find(compare);
92 CHECK(it != oat_files_.end());
93 oat_files_.erase(it);
Andreas Gampeafaf7f82018-10-16 11:32:38 -070094 compare.release(); // NOLINT b/117926937
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070095}
96
Calin Juravle0b791272016-04-18 16:38:27 +010097const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
98 const std::string& dex_base_location) const {
99 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
100 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
101 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
102 for (const OatDexFile* oat_dex_file : oat_dex_files) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700103 if (DexFileLoader::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
Calin Juravle0b791272016-04-18 16:38:27 +0100104 return oat_file.get();
105 }
106 }
107 }
108 return nullptr;
109}
110
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700111const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
112 const {
113 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700114 return FindOpenedOatFileFromOatLocationLocked(oat_location);
115}
116
117const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
118 const std::string& oat_location) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700119 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
120 if (oat_file->GetLocation() == oat_location) {
121 return oat_file.get();
122 }
123 }
124 return nullptr;
125}
126
Jeff Haodcdc85b2015-12-04 14:06:18 -0800127std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800128 std::vector<gc::space::ImageSpace*> image_spaces =
129 Runtime::Current()->GetHeap()->GetBootImageSpaces();
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800130 std::vector<const OatFile*> oat_files;
131 oat_files.reserve(image_spaces.size());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800132 for (gc::space::ImageSpace* image_space : image_spaces) {
133 oat_files.push_back(image_space->GetOatFile());
134 }
135 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700136}
137
138const OatFile* OatFileManager::GetPrimaryOatFile() const {
139 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800140 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
141 if (!boot_oat_files.empty()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700142 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800143 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
144 boot_oat_files.end()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700145 return oat_file.get();
146 }
147 }
148 }
149 return nullptr;
150}
151
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000152OatFileManager::OatFileManager()
Vladimir Markoe0669322018-09-03 15:44:54 +0100153 : only_use_system_oat_files_(false) {}
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000154
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700155OatFileManager::~OatFileManager() {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700156 // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
157 // UnRegisterOatFileLocation.
158 oat_files_.clear();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700159}
160
Jeff Haodcdc85b2015-12-04 14:06:18 -0800161std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
Stephen Hines48ba1972018-09-24 13:35:54 -0700162 const std::vector<gc::space::ImageSpace*>& spaces) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800163 std::vector<const OatFile*> oat_files;
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800164 oat_files.reserve(spaces.size());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800165 for (gc::space::ImageSpace* space : spaces) {
166 oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
167 }
168 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700169}
170
Jeff Hao8ec0a202017-03-07 21:56:31 -0800171class TypeIndexInfo {
172 public:
173 explicit TypeIndexInfo(const DexFile* dex_file)
174 : type_indexes_(GenerateTypeIndexes(dex_file)),
175 iter_(type_indexes_.Indexes().begin()),
176 end_(type_indexes_.Indexes().end()) { }
177
178 BitVector& GetTypeIndexes() {
179 return type_indexes_;
180 }
181 BitVector::IndexIterator& GetIterator() {
182 return iter_;
183 }
184 BitVector::IndexIterator& GetIteratorEnd() {
185 return end_;
186 }
187 void AdvanceIterator() {
188 iter_++;
189 }
190
191 private:
192 static BitVector GenerateTypeIndexes(const DexFile* dex_file) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700193 BitVector type_indexes(/*start_bits=*/0, /*expandable=*/true, Allocator::GetMallocAllocator());
Jeff Hao8ec0a202017-03-07 21:56:31 -0800194 for (uint16_t i = 0; i < dex_file->NumClassDefs(); ++i) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800195 const dex::ClassDef& class_def = dex_file->GetClassDef(i);
Jeff Hao8ec0a202017-03-07 21:56:31 -0800196 uint16_t type_idx = class_def.class_idx_.index_;
197 type_indexes.SetBit(type_idx);
198 }
199 return type_indexes;
200 }
201
202 // BitVector with bits set for the type indexes of all classes in the input dex file.
203 BitVector type_indexes_;
204 BitVector::IndexIterator iter_;
205 BitVector::IndexIterator end_;
206};
207
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700208class DexFileAndClassPair : ValueObject {
209 public:
Jeff Hao8ec0a202017-03-07 21:56:31 -0800210 DexFileAndClassPair(const DexFile* dex_file, TypeIndexInfo* type_info, bool from_loaded_oat)
211 : type_info_(type_info),
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700212 dex_file_(dex_file),
Jeff Hao8ec0a202017-03-07 21:56:31 -0800213 cached_descriptor_(dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info->GetIterator()))),
214 from_loaded_oat_(from_loaded_oat) {
215 type_info_->AdvanceIterator();
216 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700217
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700218 DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700219
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700220 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700221
222 const char* GetCachedDescriptor() const {
223 return cached_descriptor_;
224 }
225
226 bool operator<(const DexFileAndClassPair& rhs) const {
227 const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
228 if (cmp != 0) {
229 // Note that the order must be reversed. We want to iterate over the classes in dex files.
230 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
231 return cmp > 0;
232 }
233 return dex_file_ < rhs.dex_file_;
234 }
235
236 bool DexFileHasMoreClasses() const {
Jeff Hao8ec0a202017-03-07 21:56:31 -0800237 return type_info_->GetIterator() != type_info_->GetIteratorEnd();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700238 }
239
240 void Next() {
Jeff Hao8ec0a202017-03-07 21:56:31 -0800241 cached_descriptor_ = dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info_->GetIterator()));
242 type_info_->AdvanceIterator();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700243 }
244
245 bool FromLoadedOat() const {
246 return from_loaded_oat_;
247 }
248
249 const DexFile* GetDexFile() const {
Jeff Haof0192c82016-03-28 20:39:50 -0700250 return dex_file_;
251 }
252
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700253 private:
Jeff Hao8ec0a202017-03-07 21:56:31 -0800254 TypeIndexInfo* type_info_;
Jeff Haof0192c82016-03-28 20:39:50 -0700255 const DexFile* dex_file_;
Jeff Hao8ec0a202017-03-07 21:56:31 -0800256 const char* cached_descriptor_;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700257 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
258 // and what was loaded before. Any old duplicates must have been
259 // OK, and any new "internal" duplicates are as well (they must
260 // be from multidex, which resolves correctly).
261};
262
Jeff Hao8ec0a202017-03-07 21:56:31 -0800263static void AddDexFilesFromOat(
264 const OatFile* oat_file,
265 /*out*/std::vector<const DexFile*>* dex_files,
266 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700267 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
268 std::string error;
269 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
270 if (dex_file == nullptr) {
271 LOG(WARNING) << "Could not create dex file from oat file: " << error;
272 } else if (dex_file->NumClassDefs() > 0U) {
Jeff Hao8ec0a202017-03-07 21:56:31 -0800273 dex_files->push_back(dex_file.get());
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700274 opened_dex_files->push_back(std::move(dex_file));
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700275 }
276 }
277}
278
Jeff Hao8ec0a202017-03-07 21:56:31 -0800279static void AddNext(/*inout*/DexFileAndClassPair& original,
280 /*inout*/std::priority_queue<DexFileAndClassPair>& heap) {
281 if (original.DexFileHasMoreClasses()) {
282 original.Next();
283 heap.push(std::move(original));
Jeff Haof0192c82016-03-28 20:39:50 -0700284 }
285}
286
Mathieu Chartieradc90862018-05-11 13:03:06 -0700287static bool CheckClassCollision(const OatFile* oat_file,
288 const ClassLoaderContext* context,
289 std::string* error_msg /*out*/) {
290 std::vector<const DexFile*> dex_files_loaded = context->FlattenOpenedDexFiles();
291
292 // Vector that holds the newly opened dex files live, this is done to prevent leaks.
293 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
294
295 ScopedTrace st("Collision check");
296 // Add dex files from the oat file to check.
297 std::vector<const DexFile*> dex_files_unloaded;
298 AddDexFilesFromOat(oat_file, &dex_files_unloaded, &opened_dex_files);
299
Jeff Hao8ec0a202017-03-07 21:56:31 -0800300 // Generate type index information for each dex file.
301 std::vector<TypeIndexInfo> loaded_types;
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800302 loaded_types.reserve(dex_files_loaded.size());
Jeff Hao8ec0a202017-03-07 21:56:31 -0800303 for (const DexFile* dex_file : dex_files_loaded) {
304 loaded_types.push_back(TypeIndexInfo(dex_file));
305 }
306 std::vector<TypeIndexInfo> unloaded_types;
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800307 unloaded_types.reserve(dex_files_unloaded.size());
Jeff Hao8ec0a202017-03-07 21:56:31 -0800308 for (const DexFile* dex_file : dex_files_unloaded) {
309 unloaded_types.push_back(TypeIndexInfo(dex_file));
310 }
311
312 // Populate the queue of dex file and class pairs with the loaded and unloaded dex files.
313 std::priority_queue<DexFileAndClassPair> queue;
314 for (size_t i = 0; i < dex_files_loaded.size(); ++i) {
315 if (loaded_types[i].GetIterator() != loaded_types[i].GetIteratorEnd()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700316 queue.emplace(dex_files_loaded[i], &loaded_types[i], /*from_loaded_oat=*/true);
Jeff Hao8ec0a202017-03-07 21:56:31 -0800317 }
318 }
319 for (size_t i = 0; i < dex_files_unloaded.size(); ++i) {
320 if (unloaded_types[i].GetIterator() != unloaded_types[i].GetIteratorEnd()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700321 queue.emplace(dex_files_unloaded[i], &unloaded_types[i], /*from_loaded_oat=*/false);
Jeff Hao8ec0a202017-03-07 21:56:31 -0800322 }
323 }
324
325 // Now drain the queue.
Jeff Hao0471ece2017-04-07 16:28:12 -0700326 bool has_duplicates = false;
327 error_msg->clear();
Jeff Hao8ec0a202017-03-07 21:56:31 -0800328 while (!queue.empty()) {
329 // Modifying the top element is only safe if we pop right after.
330 DexFileAndClassPair compare_pop(queue.top());
331 queue.pop();
332
333 // Compare against the following elements.
334 while (!queue.empty()) {
335 DexFileAndClassPair top(queue.top());
336 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
337 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
338 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
Jeff Hao0471ece2017-04-07 16:28:12 -0700339 error_msg->append(
340 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s\n",
Jeff Hao8ec0a202017-03-07 21:56:31 -0800341 compare_pop.GetCachedDescriptor(),
342 compare_pop.GetDexFile()->GetLocation().c_str(),
Jeff Hao0471ece2017-04-07 16:28:12 -0700343 top.GetDexFile()->GetLocation().c_str()));
344 if (!VLOG_IS_ON(oat)) {
345 return true;
346 }
347 has_duplicates = true;
Jeff Hao8ec0a202017-03-07 21:56:31 -0800348 }
349 queue.pop();
350 AddNext(top, queue);
351 } else {
352 // Something else. Done here.
353 break;
354 }
355 }
356 AddNext(compare_pop, queue);
357 }
358
Jeff Hao0471ece2017-04-07 16:28:12 -0700359 return has_duplicates;
Jeff Haof0192c82016-03-28 20:39:50 -0700360}
361
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700362// Check for class-def collisions in dex files.
363//
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700364// This first walks the class loader chain present in the given context, getting all the dex files
365// from the class loader.
Jeff Haof0192c82016-03-28 20:39:50 -0700366//
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700367// If the context is null (which means the initial class loader was null or unsupported)
368// this returns false. b/37777332.
369//
370// This first checks whether all class loaders in the context have the same type and
371// classpath. If so, we exit early. Otherwise, we do the collision check.
Jeff Haof0192c82016-03-28 20:39:50 -0700372//
373// The collision check works by maintaining a heap with one class from each dex file, sorted by the
374// class descriptor. Then a dex-file/class pair is continually removed from the heap and compared
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700375// against the following top element. If the descriptor is the same, it is now checked whether
376// the two elements agree on whether their dex file was from an already-loaded oat-file or the
377// new oat file. Any disagreement indicates a collision.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700378OatFileManager::CheckCollisionResult OatFileManager::CheckCollision(
379 const OatFile* oat_file,
380 const ClassLoaderContext* context,
381 /*out*/ std::string* error_msg) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700382 DCHECK(oat_file != nullptr);
383 DCHECK(error_msg != nullptr);
Jeff Haof0192c82016-03-28 20:39:50 -0700384
Calin Juravle3f918642017-07-11 19:04:20 -0700385 // The context might be null if there are unrecognized class loaders in the chain or they
386 // don't meet sensible sanity conditions. In this case we assume that the app knows what it's
387 // doing and accept the oat file.
388 // Note that this has correctness implications as we cannot guarantee that the class resolution
389 // used during compilation is OK (b/37777332).
390 if (context == nullptr) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700391 LOG(WARNING) << "Skipping duplicate class check due to unsupported classloader";
392 return CheckCollisionResult::kSkippedUnsupportedClassLoader;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700393 }
394
Mathieu Chartieradc90862018-05-11 13:03:06 -0700395 // If the oat file loading context matches the context used during compilation then we accept
Calin Juravle3f918642017-07-11 19:04:20 -0700396 // the oat file without addition checks
Mathieu Chartieradc90862018-05-11 13:03:06 -0700397 ClassLoaderContext::VerificationResult result = context->VerifyClassLoaderContextMatch(
398 oat_file->GetClassLoaderContext(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700399 /*verify_names=*/ true,
400 /*verify_checksums=*/ true);
Mathieu Chartieradc90862018-05-11 13:03:06 -0700401 switch (result) {
402 case ClassLoaderContext::VerificationResult::kForcedToSkipChecks:
403 return CheckCollisionResult::kSkippedClassLoaderContextSharedLibrary;
404 case ClassLoaderContext::VerificationResult::kMismatch:
405 // Mismatched context, do the actual collision check.
406 break;
407 case ClassLoaderContext::VerificationResult::kVerifies:
408 return CheckCollisionResult::kNoCollisions;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700409 }
410
Calin Juravle3f918642017-07-11 19:04:20 -0700411 // The class loader context does not match. Perform a full duplicate classes check.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700412 return CheckClassCollision(oat_file, context, error_msg)
413 ? CheckCollisionResult::kPerformedHasCollisions : CheckCollisionResult::kNoCollisions;
414}
Calin Juravle3f918642017-07-11 19:04:20 -0700415
Mathieu Chartieradc90862018-05-11 13:03:06 -0700416bool OatFileManager::AcceptOatFile(CheckCollisionResult result) const {
417 // Take the file only if it has no collisions, or we must take it because of preopting.
418 // Also accept oat files for shared libraries and unsupported class loaders.
419 return result != CheckCollisionResult::kPerformedHasCollisions;
420}
Calin Juravle3f918642017-07-11 19:04:20 -0700421
Mathieu Chartieradc90862018-05-11 13:03:06 -0700422bool OatFileManager::ShouldLoadAppImage(CheckCollisionResult check_collision_result,
423 const OatFile* source_oat_file,
424 ClassLoaderContext* context,
425 std::string* error_msg) {
426 Runtime* const runtime = Runtime::Current();
427 if (kEnableAppImage && (!runtime->IsJavaDebuggable() || source_oat_file->IsDebuggable())) {
428 // If we verified the class loader context (skipping due to the special marker doesn't
429 // count), then also avoid the collision check.
430 bool load_image = check_collision_result == CheckCollisionResult::kNoCollisions;
431 // If we skipped the collision check, we need to reverify to be sure its OK to load the
432 // image.
433 if (!load_image &&
434 check_collision_result ==
435 CheckCollisionResult::kSkippedClassLoaderContextSharedLibrary) {
436 // We can load the app image only if there are no collisions. If we know the
437 // class loader but didn't do the full collision check in HasCollisions(),
438 // do it now. b/77342775
439 load_image = !CheckClassCollision(source_oat_file, context, error_msg);
440 }
441 return load_image;
442 }
443 return false;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700444}
445
446std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
447 const char* dex_location,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800448 jobject class_loader,
449 jobjectArray dex_elements,
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700450 const OatFile** out_oat_file,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700451 std::vector<std::string>* error_msgs) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800452 ScopedTrace trace(__FUNCTION__);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700453 CHECK(dex_location != nullptr);
454 CHECK(error_msgs != nullptr);
455
456 // Verify we aren't holding the mutator lock, which could starve GC if we
457 // have to generate or relocate an oat file.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800458 Thread* const self = Thread::Current();
459 Locks::mutator_lock_->AssertNotHeld(self);
460 Runtime* const runtime = Runtime::Current();
Calin Juravleb077e152016-02-18 18:47:37 +0000461
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700462 std::unique_ptr<ClassLoaderContext> context;
463 // If the class_loader is null there's not much we can do. This happens if a dex files is loaded
464 // directly with DexFile APIs instead of using class loaders.
465 if (class_loader == nullptr) {
466 LOG(WARNING) << "Opening an oat file without a class loader. "
467 << "Are you using the deprecated DexFile APIs?";
468 context = nullptr;
469 } else {
470 context = ClassLoaderContext::CreateContextForClassLoader(class_loader, dex_elements);
471 }
472
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700473 OatFileAssistant oat_file_assistant(dex_location,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700474 kRuntimeISA,
Nicolas Geoffray29742602017-12-14 10:09:03 +0000475 !runtime->IsAotCompiler(),
476 only_use_system_oat_files_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700477
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700478 // Get the oat file on disk.
479 std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
Andreas Gampe9ea84d02018-03-02 09:32:03 -0800480 VLOG(oat) << "OatFileAssistant(" << dex_location << ").GetBestOatFile()="
481 << reinterpret_cast<uintptr_t>(oat_file.get())
482 << " (executable=" << (oat_file != nullptr ? oat_file->IsExecutable() : false) << ")";
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800483
Nicolas Geoffray3d8a78a2018-08-29 21:10:16 +0000484 const OatFile* source_oat_file = nullptr;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700485 CheckCollisionResult check_collision_result = CheckCollisionResult::kPerformedHasCollisions;
Nicolas Geoffray3d8a78a2018-08-29 21:10:16 +0000486 std::string error_msg;
Nicolas Geoffray29742602017-12-14 10:09:03 +0000487 if ((class_loader != nullptr || dex_elements != nullptr) && oat_file != nullptr) {
Nicolas Geoffray68bf3902017-09-07 14:40:48 +0100488 // Prevent oat files from being loaded if no class_loader or dex_elements are provided.
489 // This can happen when the deprecated DexFile.<init>(String) is called directly, and it
490 // could load oat files without checking the classpath, which would be incorrect.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700491 // Take the file only if it has no collisions, or we must take it because of preopting.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700492 check_collision_result = CheckCollision(oat_file.get(), context.get(), /*out*/ &error_msg);
493 bool accept_oat_file = AcceptOatFile(check_collision_result);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700494 if (!accept_oat_file) {
495 // Failed the collision check. Print warning.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700496 if (runtime->IsDexFileFallbackEnabled()) {
Narayan Kamath5c525742017-04-28 10:19:29 +0100497 if (!oat_file_assistant.HasOriginalDexFiles()) {
498 // We need to fallback but don't have original dex files. We have to
499 // fallback to opening the existing oat file. This is potentially
500 // unsafe so we warn about it.
501 accept_oat_file = true;
502
503 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
504 << "Allow oat file use. This is potentially dangerous.";
505 } else {
506 // We have to fallback and found original dex files - extract them from an APK.
507 // Also warn about this operation because it's potentially wasteful.
508 LOG(WARNING) << "Found duplicate classes, falling back to extracting from APK : "
509 << dex_location;
510 LOG(WARNING) << "NOTE: This wastes RAM and hurts startup performance.";
511 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700512 } else {
Narayan Kamath5c525742017-04-28 10:19:29 +0100513 // TODO: We should remove this. The fact that we're here implies -Xno-dex-file-fallback
514 // was set, which means that we should never fallback. If we don't have original dex
515 // files, we should just fail resolution as the flag intended.
516 if (!oat_file_assistant.HasOriginalDexFiles()) {
517 accept_oat_file = true;
518 }
519
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700520 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
521 " load classes for " << dex_location;
522 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700523
Narayan Kamath5c525742017-04-28 10:19:29 +0100524 LOG(WARNING) << error_msg;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700525 }
526
527 if (accept_oat_file) {
528 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
529 source_oat_file = RegisterOatFile(std::move(oat_file));
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700530 *out_oat_file = source_oat_file;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700531 }
532 }
533
534 std::vector<std::unique_ptr<const DexFile>> dex_files;
535
536 // Load the dex files from the oat file.
537 if (source_oat_file != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800538 bool added_image_space = false;
539 if (source_oat_file->IsExecutable()) {
Chris Wailes23866362018-08-22 16:16:58 -0700540 ScopedTrace app_image_timing("AppImage:Loading");
541
Alex Light2ce6fc82017-12-18 16:42:36 -0800542 // We need to throw away the image space if we are debuggable but the oat-file source of the
543 // image is not otherwise we might get classes with inlined methods or other such things.
544 std::unique_ptr<gc::space::ImageSpace> image_space;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700545 if (ShouldLoadAppImage(check_collision_result,
546 source_oat_file,
547 context.get(),
548 &error_msg)) {
Alex Light2ce6fc82017-12-18 16:42:36 -0800549 image_space = oat_file_assistant.OpenImageSpace(source_oat_file);
Alex Light2ce6fc82017-12-18 16:42:36 -0800550 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800551 if (image_space != nullptr) {
552 ScopedObjectAccess soa(self);
553 StackHandleScope<1> hs(self);
554 Handle<mirror::ClassLoader> h_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700555 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800556 // Can not load app image without class loader.
Andreas Gampefa4333d2017-02-14 11:10:34 -0800557 if (h_loader != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800558 std::string temp_error_msg;
559 // Add image space has a race condition since other threads could be reading from the
560 // spaces array.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800561 {
562 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800563 gc::ScopedGCCriticalSection gcs(self,
564 gc::kGcCauseAddRemoveAppImageSpace,
565 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800566 ScopedSuspendAll ssa("Add image space");
567 runtime->GetHeap()->AddSpace(image_space.get());
568 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800569 {
570 ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
571 added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
572 h_loader,
573 dex_elements,
574 dex_location,
575 /*out*/&dex_files,
576 /*out*/&temp_error_msg);
577 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800578 if (added_image_space) {
Mathieu Chartierbd064ea2016-02-11 16:27:18 -0800579 // Successfully added image space to heap, release the map so that it does not get
580 // freed.
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700581 image_space.release(); // NOLINT b/117926937
Bharadwaj Kalandhabhatta0bb40312017-06-01 10:47:00 -0700582
583 // Register for tracking.
584 for (const auto& dex_file : dex_files) {
585 dex::tracking::RegisterDexFile(dex_file.get());
586 }
Mathieu Chartierbd064ea2016-02-11 16:27:18 -0800587 } else {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800588 LOG(INFO) << "Failed to add image file " << temp_error_msg;
589 dex_files.clear();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800590 {
591 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800592 gc::ScopedGCCriticalSection gcs(self,
593 gc::kGcCauseAddRemoveAppImageSpace,
594 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800595 ScopedSuspendAll ssa("Remove image space");
596 runtime->GetHeap()->RemoveSpace(image_space.get());
597 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800598 // Non-fatal, don't update error_msg.
599 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800600 }
601 }
602 }
603 if (!added_image_space) {
604 DCHECK(dex_files.empty());
605 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
Bharadwaj Kalandhabhatta0bb40312017-06-01 10:47:00 -0700606
607 // Register for tracking.
608 for (const auto& dex_file : dex_files) {
609 dex::tracking::RegisterDexFile(dex_file.get());
610 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800611 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700612 if (dex_files.empty()) {
613 error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
Mathieu Chartierbe8303d2017-08-17 17:39:39 -0700614 } else {
Mathieu Chartier120aa282017-08-05 16:03:03 -0700615 // Opened dex files from an oat file, madvise them to their loaded state.
616 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
617 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
618 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700619 }
620 }
621
622 // Fall back to running out of the original dex file if we couldn't load any
623 // dex_files from the oat file.
624 if (dex_files.empty()) {
625 if (oat_file_assistant.HasOriginalDexFiles()) {
626 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700627 static constexpr bool kVerifyChecksum = true;
David Sehr013fd802018-01-11 22:55:24 -0800628 const ArtDexFileLoader dex_file_loader;
629 if (!dex_file_loader.Open(dex_location,
630 dex_location,
631 Runtime::Current()->IsVerificationEnabled(),
632 kVerifyChecksum,
633 /*out*/ &error_msg,
634 &dex_files)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700635 LOG(WARNING) << error_msg;
Alex Light3045b662016-04-20 14:26:34 -0700636 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
637 + " because: " + error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700638 }
639 } else {
640 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
641 }
642 } else {
643 error_msgs->push_back("No original dex files found for dex location "
644 + std::string(dex_location));
645 }
646 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000647
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700648 return dex_files;
649}
650
David Brazdil7126c5b2019-03-05 00:02:51 +0000651static std::vector<const DexFile::Header*> GetDexFileHeaders(const std::vector<MemMap>& maps) {
652 std::vector<const DexFile::Header*> headers;
653 headers.reserve(maps.size());
654 for (const MemMap& map : maps) {
655 DCHECK(map.IsValid());
656 headers.push_back(reinterpret_cast<const DexFile::Header*>(map.Begin()));
657 }
658 return headers;
659}
660
David Brazdil35a3f6a2019-03-04 15:59:06 +0000661static std::vector<const DexFile::Header*> GetDexFileHeaders(
662 const std::vector<const DexFile*>& dex_files) {
663 std::vector<const DexFile::Header*> headers;
664 headers.reserve(dex_files.size());
665 for (const DexFile* dex_file : dex_files) {
666 headers.push_back(&dex_file->GetHeader());
667 }
668 return headers;
669}
670
David Brazdil7126c5b2019-03-05 00:02:51 +0000671std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
672 std::vector<MemMap>&& dex_mem_maps,
673 jobject class_loader,
674 jobjectArray dex_elements,
675 const OatFile** out_oat_file,
676 std::vector<std::string>* error_msgs) {
677 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenDexFilesFromOat_Impl(
678 std::move(dex_mem_maps),
679 class_loader,
680 dex_elements,
681 out_oat_file,
682 error_msgs);
683
684 if (error_msgs->empty()) {
685 // Remove write permission from DexFile pages. We do this at the end because
686 // OatFile assigns OatDexFile pointer in the DexFile objects.
687 for (std::unique_ptr<const DexFile>& dex_file : dex_files) {
688 if (!dex_file->DisableWrite()) {
689 error_msgs->push_back("Failed to make dex file " + dex_file->GetLocation() + " read-only");
690 }
691 }
692 }
693
694 if (!error_msgs->empty()) {
695 return std::vector<std::unique_ptr<const DexFile>>();
696 }
697
698 return dex_files;
699}
700
701std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat_Impl(
702 std::vector<MemMap>&& dex_mem_maps,
703 jobject class_loader,
704 jobjectArray dex_elements,
705 const OatFile** out_oat_file,
706 std::vector<std::string>* error_msgs) {
707 ScopedTrace trace(__FUNCTION__);
708 std::string error_msg;
709 DCHECK(error_msgs != nullptr);
710
711 // Extract dex file headers from `dex_mem_maps`.
712 const std::vector<const DexFile::Header*> dex_headers = GetDexFileHeaders(dex_mem_maps);
713
714 // Determine dex/vdex locations and the combined location checksum.
715 uint32_t location_checksum;
716 std::string dex_location;
717 std::string vdex_path;
718 bool has_vdex = OatFileAssistant::AnonymousDexVdexLocation(dex_headers,
719 kRuntimeISA,
720 &location_checksum,
721 &dex_location,
722 &vdex_path);
723
724 // Attempt to open an existing vdex and check dex file checksums match.
725 std::unique_ptr<VdexFile> vdex_file = nullptr;
726 if (has_vdex && OS::FileExists(vdex_path.c_str())) {
727 vdex_file = VdexFile::Open(vdex_path,
728 /* writable= */ false,
729 /* low_4gb= */ false,
730 /* unquicken= */ false,
731 &error_msg);
732 if (vdex_file == nullptr) {
733 LOG(WARNING) << "Failed to open vdex " << vdex_path << ": " << error_msg;
734 } else if (!vdex_file->MatchesDexFileChecksums(dex_headers)) {
735 LOG(WARNING) << "Failed to open vdex " << vdex_path << ": dex file checksum mismatch";
736 vdex_file.reset(nullptr);
737 }
738 }
739
740 // Load dex files. Skip structural dex file verification if vdex was found
741 // and dex checksums matched.
742 std::vector<std::unique_ptr<const DexFile>> dex_files;
743 for (size_t i = 0; i < dex_mem_maps.size(); ++i) {
744 static constexpr bool kVerifyChecksum = true;
745 const ArtDexFileLoader dex_file_loader;
746 std::unique_ptr<const DexFile> dex_file(dex_file_loader.Open(
747 DexFileLoader::GetMultiDexLocation(i, dex_location.c_str()),
748 location_checksum,
749 std::move(dex_mem_maps[i]),
750 /* verify= */ (vdex_file == nullptr) && Runtime::Current()->IsVerificationEnabled(),
751 kVerifyChecksum,
752 &error_msg));
753 if (dex_file != nullptr) {
754 dex::tracking::RegisterDexFile(dex_file.get()); // Register for tracking.
755 dex_files.push_back(std::move(dex_file));
756 } else {
757 error_msgs->push_back("Failed to open dex files from memory: " + error_msg);
758 }
759 }
760
761 // Check if we should proceed to creating an OatFile instance backed by the vdex.
762 // We need: (a) an existing vdex, (b) class loader (can be null if invoked via reflection),
763 // and (c) no errors during dex file loading.
764 if (vdex_file == nullptr || class_loader == nullptr || !error_msgs->empty()) {
765 return dex_files;
766 }
767
768 // Attempt to create a class loader context, check OpenDexFiles succeeds (prerequisite
769 // for using the context later).
770 std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::CreateContextForClassLoader(
771 class_loader,
772 dex_elements);
773 if (context == nullptr) {
774 LOG(ERROR) << "Could not create class loader context for " << vdex_path;
775 return dex_files;
776 }
777 DCHECK(context->OpenDexFiles(kRuntimeISA, ""))
778 << "Context created from already opened dex files should not attempt to open again";
779
780 // Check that we can use the vdex against this boot class path and in this class loader context.
781 // Note 1: We do not need a class loader collision check because there is no compiled code.
782 // Note 2: If these checks fail, we cannot fast-verify because the vdex does not contain
783 // full VerifierDeps.
784 if (!vdex_file->MatchesBootClassPathChecksums() ||
785 !vdex_file->MatchesClassLoaderContext(*context.get())) {
786 return dex_files;
787 }
788
789 // Initialize an OatFile instance backed by the loaded vdex.
790 std::unique_ptr<OatFile> oat_file(OatFile::OpenFromVdex(MakeNonOwningPointerVector(dex_files),
791 std::move(vdex_file),
792 dex_location));
793 DCHECK(oat_file != nullptr);
794 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
795 *out_oat_file = RegisterOatFile(std::move(oat_file));
796 return dex_files;
797}
798
David Brazdil35a3f6a2019-03-04 15:59:06 +0000799// Check how many vdex files exist in the same directory as the vdex file we are about
800// to write. If more than or equal to kAnonymousVdexCacheSize, unlink the least
801// recently used one(s) (according to stat-reported atime).
802static bool UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string& vdex_path_to_add,
803 std::string* error_msg) {
804 if (OS::FileExists(vdex_path_to_add.c_str())) {
805 // File already exists and will be overwritten.
806 // This will not change the number of entries in the cache.
807 return true;
808 }
809
810 auto last_slash = vdex_path_to_add.rfind('/');
811 CHECK(last_slash != std::string::npos);
812 std::string vdex_dir = vdex_path_to_add.substr(0, last_slash + 1);
813
814 if (!OS::DirectoryExists(vdex_dir.c_str())) {
815 // Folder does not exist yet. Cache has zero entries.
816 return true;
817 }
818
819 std::vector<std::pair<time_t, std::string>> cache;
820
821 DIR* c_dir = opendir(vdex_dir.c_str());
822 if (c_dir == nullptr) {
823 *error_msg = "Unable to open " + vdex_dir + " to delete unused vdex files";
824 return false;
825 }
826 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
827 if (de->d_type != DT_REG) {
828 continue;
829 }
830 std::string basename = de->d_name;
831 if (!OatFileAssistant::IsAnonymousVdexBasename(basename)) {
832 continue;
833 }
834 std::string fullname = vdex_dir + basename;
835
836 struct stat s;
837 int rc = TEMP_FAILURE_RETRY(stat(fullname.c_str(), &s));
838 if (rc == -1) {
839 *error_msg = "Failed to stat() anonymous vdex file " + fullname;
840 return false;
841 }
842
843 cache.push_back(std::make_pair(s.st_atime, fullname));
844 }
845 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
846
847 if (cache.size() < OatFileManager::kAnonymousVdexCacheSize) {
848 return true;
849 }
850
851 std::sort(cache.begin(),
852 cache.end(),
853 [](const auto& a, const auto& b) { return a.first < b.first; });
854 for (size_t i = OatFileManager::kAnonymousVdexCacheSize - 1; i < cache.size(); ++i) {
855 if (unlink(cache[i].second.c_str()) != 0) {
856 *error_msg = "Could not unlink anonymous vdex file " + cache[i].second;
857 return false;
858 }
859 }
860
861 return true;
862}
863
David Brazdil331a5e12019-04-01 22:46:16 +0000864class BackgroundVerificationTask final : public Task {
865 public:
David Brazdil35a3f6a2019-03-04 15:59:06 +0000866 BackgroundVerificationTask(const std::vector<const DexFile*>& dex_files,
867 jobject class_loader,
868 const char* class_loader_context,
869 const std::string& vdex_path)
870 : dex_files_(dex_files),
871 class_loader_context_(class_loader_context),
872 vdex_path_(vdex_path) {
David Brazdil331a5e12019-04-01 22:46:16 +0000873 Thread* const self = Thread::Current();
874 ScopedObjectAccess soa(self);
875 // Create a global ref for `class_loader` because it will be accessed from a different thread.
876 class_loader_ = soa.Vm()->AddGlobalRef(self, soa.Decode<mirror::ClassLoader>(class_loader));
877 CHECK(class_loader_ != nullptr);
878 }
879
880 ~BackgroundVerificationTask() {
881 Thread* const self = Thread::Current();
882 ScopedObjectAccess soa(self);
883 soa.Vm()->DeleteGlobalRef(self, class_loader_);
884 }
885
886 void Run(Thread* self) override {
David Brazdil35a3f6a2019-03-04 15:59:06 +0000887 std::string error_msg;
David Brazdil331a5e12019-04-01 22:46:16 +0000888 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
David Brazdil35a3f6a2019-03-04 15:59:06 +0000889 verifier::VerifierDeps verifier_deps(dex_files_);
David Brazdil331a5e12019-04-01 22:46:16 +0000890
891 // Iterate over all classes and verify them.
892 for (const DexFile* dex_file : dex_files_) {
893 for (uint32_t cdef_idx = 0; cdef_idx < dex_file->NumClassDefs(); cdef_idx++) {
David Brazdil35a3f6a2019-03-04 15:59:06 +0000894 const dex::ClassDef& class_def = dex_file->GetClassDef(cdef_idx);
895
David Brazdil331a5e12019-04-01 22:46:16 +0000896 // Take handles inside the loop. The background verification is low priority
897 // and we want to minimize the risk of blocking anyone else.
898 ScopedObjectAccess soa(self);
899 StackHandleScope<2> hs(self);
900 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
901 soa.Decode<mirror::ClassLoader>(class_loader_)));
902 Handle<mirror::Class> h_class(hs.NewHandle<mirror::Class>(class_linker->FindClass(
903 self,
David Brazdil35a3f6a2019-03-04 15:59:06 +0000904 dex_file->GetClassDescriptor(class_def),
David Brazdil331a5e12019-04-01 22:46:16 +0000905 h_loader)));
906
907 if (h_class == nullptr) {
908 CHECK(self->IsExceptionPending());
909 self->ClearException();
910 continue;
911 }
912
913 if (&h_class->GetDexFile() != dex_file) {
914 // There is a different class in the class path or a parent class loader
915 // with the same descriptor. This `h_class` is not resolvable, skip it.
916 continue;
917 }
918
919 CHECK(h_class->IsResolved()) << h_class->PrettyDescriptor();
920 class_linker->VerifyClass(self, h_class);
921 if (h_class->IsErroneous()) {
922 // ClassLinker::VerifyClass throws, which isn't useful here.
923 CHECK(soa.Self()->IsExceptionPending());
924 soa.Self()->ClearException();
925 }
926
927 CHECK(h_class->IsVerified() || h_class->IsErroneous())
928 << h_class->PrettyDescriptor() << ": state=" << h_class->GetStatus();
David Brazdil35a3f6a2019-03-04 15:59:06 +0000929
930 if (h_class->IsVerified()) {
931 verifier_deps.RecordClassVerified(*dex_file, class_def);
932 }
David Brazdil331a5e12019-04-01 22:46:16 +0000933 }
934 }
David Brazdil35a3f6a2019-03-04 15:59:06 +0000935
936 // Delete old vdex files if there are too many in the folder.
937 if (!UnlinkLeastRecentlyUsedVdexIfNeeded(vdex_path_, &error_msg)) {
938 LOG(ERROR) << "Could not unlink old vdex files " << vdex_path_ << ": " << error_msg;
939 return;
940 }
941
942 // Construct a vdex file and write `verifier_deps` into it.
943 if (!VdexFile::WriteToDisk(vdex_path_,
944 dex_files_,
945 verifier_deps,
946 class_loader_context_,
947 &error_msg)) {
948 LOG(ERROR) << "Could not write anonymous vdex " << vdex_path_ << ": " << error_msg;
949 return;
950 }
David Brazdil331a5e12019-04-01 22:46:16 +0000951 }
952
953 void Finalize() override {
954 delete this;
955 }
956
957 private:
958 const std::vector<const DexFile*> dex_files_;
959 jobject class_loader_;
David Brazdil35a3f6a2019-03-04 15:59:06 +0000960 const std::string class_loader_context_;
961 const std::string vdex_path_;
David Brazdil331a5e12019-04-01 22:46:16 +0000962
963 DISALLOW_COPY_AND_ASSIGN(BackgroundVerificationTask);
964};
965
966void OatFileManager::RunBackgroundVerification(const std::vector<const DexFile*>& dex_files,
David Brazdil35a3f6a2019-03-04 15:59:06 +0000967 jobject class_loader,
968 const char* class_loader_context) {
David Brazdil527072e2019-04-03 15:15:40 +0100969 Runtime* const runtime = Runtime::Current();
970 Thread* const self = Thread::Current();
971
972 if (runtime->IsJavaDebuggable()) {
David Brazdil331a5e12019-04-01 22:46:16 +0000973 // Threads created by ThreadPool ("runtime threads") are not allowed to load
974 // classes when debuggable to match class-initialization semantics
975 // expectations. Do not verify in the background.
976 return;
977 }
978
David Brazdil527072e2019-04-03 15:15:40 +0100979 if (!IsSdkVersionSetAndAtLeast(runtime->GetTargetSdkVersion(), SdkVersion::kQ)) {
980 // Do not run for legacy apps as they may depend on the previous class loader behaviour.
981 return;
982 }
983
984 if (runtime->IsShuttingDown(self)) {
David Brazdil331a5e12019-04-01 22:46:16 +0000985 // Not allowed to create new threads during runtime shutdown.
986 return;
987 }
988
David Brazdil35a3f6a2019-03-04 15:59:06 +0000989 uint32_t location_checksum;
990 std::string dex_location;
991 std::string vdex_path;
992 if (OatFileAssistant::AnonymousDexVdexLocation(GetDexFileHeaders(dex_files),
993 kRuntimeISA,
994 &location_checksum,
995 &dex_location,
996 &vdex_path)) {
997 if (verification_thread_pool_ == nullptr) {
998 verification_thread_pool_.reset(
999 new ThreadPool("Verification thread pool", /* num_threads= */ 1));
1000 verification_thread_pool_->StartWorkers(self);
1001 }
1002 verification_thread_pool_->AddTask(self, new BackgroundVerificationTask(
1003 dex_files,
1004 class_loader,
1005 class_loader_context,
1006 vdex_path));
David Brazdil331a5e12019-04-01 22:46:16 +00001007 }
David Brazdil331a5e12019-04-01 22:46:16 +00001008}
1009
1010void OatFileManager::WaitForWorkersToBeCreated() {
1011 DCHECK(!Runtime::Current()->IsShuttingDown(Thread::Current()))
1012 << "Cannot create new threads during runtime shutdown";
1013 if (verification_thread_pool_ != nullptr) {
1014 verification_thread_pool_->WaitForWorkersToBeCreated();
1015 }
1016}
1017
1018void OatFileManager::DeleteThreadPool() {
1019 verification_thread_pool_.reset(nullptr);
1020}
1021
1022void OatFileManager::WaitForBackgroundVerificationTasks() {
1023 if (verification_thread_pool_ != nullptr) {
1024 Thread* const self = Thread::Current();
1025 verification_thread_pool_->WaitForWorkersToBeCreated();
1026 verification_thread_pool_->Wait(self, /* do_work= */ true, /* may_hold_locks= */ false);
1027 }
1028}
1029
Andreas Gampe9ef308d2019-03-28 11:06:26 -07001030void OatFileManager::SetOnlyUseSystemOatFiles(bool enforce, bool assert_no_files_loaded) {
Nicolas Geoffray68bf3902017-09-07 14:40:48 +01001031 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Andreas Gampe9ef308d2019-03-28 11:06:26 -07001032 if (!only_use_system_oat_files_ && enforce && assert_no_files_loaded) {
Andreas Gampe99c07952019-03-30 17:43:55 +00001033 // Make sure all files that were loaded up to this point are on /system. Skip the image
1034 // files.
1035 std::vector<const OatFile*> boot_vector = GetBootOatFiles();
1036 std::unordered_set<const OatFile*> boot_set(boot_vector.begin(), boot_vector.end());
1037
1038 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
1039 if (boot_set.find(oat_file.get()) == boot_set.end()) {
1040 CHECK(LocationIsOnSystem(oat_file->GetLocation().c_str())) << oat_file->GetLocation();
1041 }
1042 }
Andreas Gampe3383f9c2019-03-15 11:46:08 -07001043 }
Andreas Gampe9ef308d2019-03-28 11:06:26 -07001044 only_use_system_oat_files_ = enforce;
Nicolas Geoffray68bf3902017-09-07 14:40:48 +01001045}
1046
Nicolas Geoffray04680f32016-03-17 11:56:54 +00001047void OatFileManager::DumpForSigQuit(std::ostream& os) {
1048 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
1049 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
1050 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
1051 if (ContainsElement(boot_oat_files, oat_file.get())) {
1052 continue;
1053 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001054 os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
Nicolas Geoffray04680f32016-03-17 11:56:54 +00001055 }
1056}
1057
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001058} // namespace art