blob: e4c7dc30819661a8d285b84c8be7864a1913ec3f [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"
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +010044#include "jit/jit.h"
David Brazdil331a5e12019-04-01 22:46:16 +000045#include "jni/java_vm_ext.h"
Vladimir Markoa3ad0cd2018-05-04 10:06:38 +010046#include "jni/jni_internal.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080047#include "mirror/class_loader.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -080048#include "mirror/object-inl.h"
Alex Light2ce6fc82017-12-18 16:42:36 -080049#include "oat_file.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070050#include "oat_file_assistant.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070051#include "obj_ptr-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070052#include "scoped_thread_state_change-inl.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070053#include "thread-current-inl.h"
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -080054#include "thread_list.h"
David Brazdil331a5e12019-04-01 22:46:16 +000055#include "thread_pool.h"
David Brazdil35a3f6a2019-03-04 15:59:06 +000056#include "vdex_file.h"
57#include "verifier/verifier_deps.h"
Andreas Gampe90b936d2017-01-31 08:58:55 -080058#include "well_known_classes.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070059
60namespace art {
61
Andreas Gampe46ee31b2016-12-14 10:11:49 -080062using android::base::StringPrintf;
63
Mathieu Chartier120aa282017-08-05 16:03:03 -070064// If true, we attempt to load the application image if it exists.
Mathieu Chartierfbc31082016-01-24 11:59:56 -080065static constexpr bool kEnableAppImage = true;
66
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070067const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070068 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Nicolas Geoffray29742602017-12-14 10:09:03 +000069 CHECK(!only_use_system_oat_files_ ||
70 LocationIsOnSystem(oat_file->GetLocation().c_str()) ||
71 !oat_file->IsExecutable())
Nicolas Geoffray68bf3902017-09-07 14:40:48 +010072 << "Registering a non /system oat file: " << oat_file->GetLocation();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070073 DCHECK(oat_file != nullptr);
74 if (kIsDebugBuild) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070075 CHECK(oat_files_.find(oat_file) == oat_files_.end());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070076 for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
77 CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
78 // Check that we don't have an oat file with the same address. Copies of the same oat file
79 // should be loaded at different addresses.
80 CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
81 }
82 }
Mathieu Chartiere58991b2015-10-13 07:59:34 -070083 const OatFile* ret = oat_file.get();
84 oat_files_.insert(std::move(oat_file));
85 return ret;
86}
87
88void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
89 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
90 DCHECK(oat_file != nullptr);
91 std::unique_ptr<const OatFile> compare(oat_file);
92 auto it = oat_files_.find(compare);
93 CHECK(it != oat_files_.end());
94 oat_files_.erase(it);
Andreas Gampeafaf7f82018-10-16 11:32:38 -070095 compare.release(); // NOLINT b/117926937
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070096}
97
Calin Juravle0b791272016-04-18 16:38:27 +010098const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
99 const std::string& dex_base_location) const {
100 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
101 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
102 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
103 for (const OatDexFile* oat_dex_file : oat_dex_files) {
Mathieu Chartier79c87da2017-10-10 11:54:29 -0700104 if (DexFileLoader::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
Calin Juravle0b791272016-04-18 16:38:27 +0100105 return oat_file.get();
106 }
107 }
108 }
109 return nullptr;
110}
111
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700112const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
113 const {
114 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700115 return FindOpenedOatFileFromOatLocationLocked(oat_location);
116}
117
118const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
119 const std::string& oat_location) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700120 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
121 if (oat_file->GetLocation() == oat_location) {
122 return oat_file.get();
123 }
124 }
125 return nullptr;
126}
127
Jeff Haodcdc85b2015-12-04 14:06:18 -0800128std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800129 std::vector<gc::space::ImageSpace*> image_spaces =
130 Runtime::Current()->GetHeap()->GetBootImageSpaces();
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800131 std::vector<const OatFile*> oat_files;
132 oat_files.reserve(image_spaces.size());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800133 for (gc::space::ImageSpace* image_space : image_spaces) {
134 oat_files.push_back(image_space->GetOatFile());
135 }
136 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700137}
138
139const OatFile* OatFileManager::GetPrimaryOatFile() const {
140 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800141 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
142 if (!boot_oat_files.empty()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700143 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800144 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
145 boot_oat_files.end()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700146 return oat_file.get();
147 }
148 }
149 }
150 return nullptr;
151}
152
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000153OatFileManager::OatFileManager()
Vladimir Markoe0669322018-09-03 15:44:54 +0100154 : only_use_system_oat_files_(false) {}
Vladimir Markob0b68cf2017-11-14 18:11:50 +0000155
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700156OatFileManager::~OatFileManager() {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700157 // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
158 // UnRegisterOatFileLocation.
159 oat_files_.clear();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700160}
161
Jeff Haodcdc85b2015-12-04 14:06:18 -0800162std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
Stephen Hines48ba1972018-09-24 13:35:54 -0700163 const std::vector<gc::space::ImageSpace*>& spaces) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800164 std::vector<const OatFile*> oat_files;
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800165 oat_files.reserve(spaces.size());
Jeff Haodcdc85b2015-12-04 14:06:18 -0800166 for (gc::space::ImageSpace* space : spaces) {
167 oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
168 }
169 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700170}
171
Jeff Hao8ec0a202017-03-07 21:56:31 -0800172class TypeIndexInfo {
173 public:
174 explicit TypeIndexInfo(const DexFile* dex_file)
175 : type_indexes_(GenerateTypeIndexes(dex_file)),
176 iter_(type_indexes_.Indexes().begin()),
177 end_(type_indexes_.Indexes().end()) { }
178
179 BitVector& GetTypeIndexes() {
180 return type_indexes_;
181 }
182 BitVector::IndexIterator& GetIterator() {
183 return iter_;
184 }
185 BitVector::IndexIterator& GetIteratorEnd() {
186 return end_;
187 }
188 void AdvanceIterator() {
189 iter_++;
190 }
191
192 private:
193 static BitVector GenerateTypeIndexes(const DexFile* dex_file) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700194 BitVector type_indexes(/*start_bits=*/0, /*expandable=*/true, Allocator::GetMallocAllocator());
Jeff Hao8ec0a202017-03-07 21:56:31 -0800195 for (uint16_t i = 0; i < dex_file->NumClassDefs(); ++i) {
Andreas Gampe3f1dcd32018-12-28 09:39:56 -0800196 const dex::ClassDef& class_def = dex_file->GetClassDef(i);
Jeff Hao8ec0a202017-03-07 21:56:31 -0800197 uint16_t type_idx = class_def.class_idx_.index_;
198 type_indexes.SetBit(type_idx);
199 }
200 return type_indexes;
201 }
202
203 // BitVector with bits set for the type indexes of all classes in the input dex file.
204 BitVector type_indexes_;
205 BitVector::IndexIterator iter_;
206 BitVector::IndexIterator end_;
207};
208
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700209class DexFileAndClassPair : ValueObject {
210 public:
Jeff Hao8ec0a202017-03-07 21:56:31 -0800211 DexFileAndClassPair(const DexFile* dex_file, TypeIndexInfo* type_info, bool from_loaded_oat)
212 : type_info_(type_info),
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700213 dex_file_(dex_file),
Jeff Hao8ec0a202017-03-07 21:56:31 -0800214 cached_descriptor_(dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info->GetIterator()))),
215 from_loaded_oat_(from_loaded_oat) {
216 type_info_->AdvanceIterator();
217 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700218
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700219 DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700220
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700221 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700222
223 const char* GetCachedDescriptor() const {
224 return cached_descriptor_;
225 }
226
227 bool operator<(const DexFileAndClassPair& rhs) const {
228 const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
229 if (cmp != 0) {
230 // Note that the order must be reversed. We want to iterate over the classes in dex files.
231 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
232 return cmp > 0;
233 }
234 return dex_file_ < rhs.dex_file_;
235 }
236
237 bool DexFileHasMoreClasses() const {
Jeff Hao8ec0a202017-03-07 21:56:31 -0800238 return type_info_->GetIterator() != type_info_->GetIteratorEnd();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700239 }
240
241 void Next() {
Jeff Hao8ec0a202017-03-07 21:56:31 -0800242 cached_descriptor_ = dex_file_->StringByTypeIdx(dex::TypeIndex(*type_info_->GetIterator()));
243 type_info_->AdvanceIterator();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700244 }
245
246 bool FromLoadedOat() const {
247 return from_loaded_oat_;
248 }
249
250 const DexFile* GetDexFile() const {
Jeff Haof0192c82016-03-28 20:39:50 -0700251 return dex_file_;
252 }
253
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700254 private:
Jeff Hao8ec0a202017-03-07 21:56:31 -0800255 TypeIndexInfo* type_info_;
Jeff Haof0192c82016-03-28 20:39:50 -0700256 const DexFile* dex_file_;
Jeff Hao8ec0a202017-03-07 21:56:31 -0800257 const char* cached_descriptor_;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700258 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
259 // and what was loaded before. Any old duplicates must have been
260 // OK, and any new "internal" duplicates are as well (they must
261 // be from multidex, which resolves correctly).
262};
263
Jeff Hao8ec0a202017-03-07 21:56:31 -0800264static void AddDexFilesFromOat(
265 const OatFile* oat_file,
266 /*out*/std::vector<const DexFile*>* dex_files,
267 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700268 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
269 std::string error;
270 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
271 if (dex_file == nullptr) {
272 LOG(WARNING) << "Could not create dex file from oat file: " << error;
273 } else if (dex_file->NumClassDefs() > 0U) {
Jeff Hao8ec0a202017-03-07 21:56:31 -0800274 dex_files->push_back(dex_file.get());
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700275 opened_dex_files->push_back(std::move(dex_file));
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700276 }
277 }
278}
279
Jeff Hao8ec0a202017-03-07 21:56:31 -0800280static void AddNext(/*inout*/DexFileAndClassPair& original,
281 /*inout*/std::priority_queue<DexFileAndClassPair>& heap) {
282 if (original.DexFileHasMoreClasses()) {
283 original.Next();
284 heap.push(std::move(original));
Jeff Haof0192c82016-03-28 20:39:50 -0700285 }
286}
287
Mathieu Chartieradc90862018-05-11 13:03:06 -0700288static bool CheckClassCollision(const OatFile* oat_file,
289 const ClassLoaderContext* context,
290 std::string* error_msg /*out*/) {
291 std::vector<const DexFile*> dex_files_loaded = context->FlattenOpenedDexFiles();
292
293 // Vector that holds the newly opened dex files live, this is done to prevent leaks.
294 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
295
296 ScopedTrace st("Collision check");
297 // Add dex files from the oat file to check.
298 std::vector<const DexFile*> dex_files_unloaded;
299 AddDexFilesFromOat(oat_file, &dex_files_unloaded, &opened_dex_files);
300
Jeff Hao8ec0a202017-03-07 21:56:31 -0800301 // Generate type index information for each dex file.
302 std::vector<TypeIndexInfo> loaded_types;
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800303 loaded_types.reserve(dex_files_loaded.size());
Jeff Hao8ec0a202017-03-07 21:56:31 -0800304 for (const DexFile* dex_file : dex_files_loaded) {
305 loaded_types.push_back(TypeIndexInfo(dex_file));
306 }
307 std::vector<TypeIndexInfo> unloaded_types;
Andreas Gampe2a487eb2018-11-19 11:41:22 -0800308 unloaded_types.reserve(dex_files_unloaded.size());
Jeff Hao8ec0a202017-03-07 21:56:31 -0800309 for (const DexFile* dex_file : dex_files_unloaded) {
310 unloaded_types.push_back(TypeIndexInfo(dex_file));
311 }
312
313 // Populate the queue of dex file and class pairs with the loaded and unloaded dex files.
314 std::priority_queue<DexFileAndClassPair> queue;
315 for (size_t i = 0; i < dex_files_loaded.size(); ++i) {
316 if (loaded_types[i].GetIterator() != loaded_types[i].GetIteratorEnd()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700317 queue.emplace(dex_files_loaded[i], &loaded_types[i], /*from_loaded_oat=*/true);
Jeff Hao8ec0a202017-03-07 21:56:31 -0800318 }
319 }
320 for (size_t i = 0; i < dex_files_unloaded.size(); ++i) {
321 if (unloaded_types[i].GetIterator() != unloaded_types[i].GetIteratorEnd()) {
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700322 queue.emplace(dex_files_unloaded[i], &unloaded_types[i], /*from_loaded_oat=*/false);
Jeff Hao8ec0a202017-03-07 21:56:31 -0800323 }
324 }
325
326 // Now drain the queue.
Jeff Hao0471ece2017-04-07 16:28:12 -0700327 bool has_duplicates = false;
328 error_msg->clear();
Jeff Hao8ec0a202017-03-07 21:56:31 -0800329 while (!queue.empty()) {
330 // Modifying the top element is only safe if we pop right after.
331 DexFileAndClassPair compare_pop(queue.top());
332 queue.pop();
333
334 // Compare against the following elements.
335 while (!queue.empty()) {
336 DexFileAndClassPair top(queue.top());
337 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
338 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
339 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
Jeff Hao0471ece2017-04-07 16:28:12 -0700340 error_msg->append(
341 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s\n",
Jeff Hao8ec0a202017-03-07 21:56:31 -0800342 compare_pop.GetCachedDescriptor(),
343 compare_pop.GetDexFile()->GetLocation().c_str(),
Jeff Hao0471ece2017-04-07 16:28:12 -0700344 top.GetDexFile()->GetLocation().c_str()));
345 if (!VLOG_IS_ON(oat)) {
346 return true;
347 }
348 has_duplicates = true;
Jeff Hao8ec0a202017-03-07 21:56:31 -0800349 }
350 queue.pop();
351 AddNext(top, queue);
352 } else {
353 // Something else. Done here.
354 break;
355 }
356 }
357 AddNext(compare_pop, queue);
358 }
359
Jeff Hao0471ece2017-04-07 16:28:12 -0700360 return has_duplicates;
Jeff Haof0192c82016-03-28 20:39:50 -0700361}
362
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700363// Check for class-def collisions in dex files.
364//
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700365// This first walks the class loader chain present in the given context, getting all the dex files
366// from the class loader.
Jeff Haof0192c82016-03-28 20:39:50 -0700367//
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700368// If the context is null (which means the initial class loader was null or unsupported)
369// this returns false. b/37777332.
370//
371// This first checks whether all class loaders in the context have the same type and
372// classpath. If so, we exit early. Otherwise, we do the collision check.
Jeff Haof0192c82016-03-28 20:39:50 -0700373//
374// The collision check works by maintaining a heap with one class from each dex file, sorted by the
375// class descriptor. Then a dex-file/class pair is continually removed from the heap and compared
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700376// against the following top element. If the descriptor is the same, it is now checked whether
377// the two elements agree on whether their dex file was from an already-loaded oat-file or the
378// new oat file. Any disagreement indicates a collision.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700379OatFileManager::CheckCollisionResult OatFileManager::CheckCollision(
380 const OatFile* oat_file,
381 const ClassLoaderContext* context,
382 /*out*/ std::string* error_msg) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700383 DCHECK(oat_file != nullptr);
384 DCHECK(error_msg != nullptr);
Jeff Haof0192c82016-03-28 20:39:50 -0700385
Calin Juravle3f918642017-07-11 19:04:20 -0700386 // The context might be null if there are unrecognized class loaders in the chain or they
387 // don't meet sensible sanity conditions. In this case we assume that the app knows what it's
388 // doing and accept the oat file.
389 // Note that this has correctness implications as we cannot guarantee that the class resolution
390 // used during compilation is OK (b/37777332).
391 if (context == nullptr) {
Mathieu Chartieradc90862018-05-11 13:03:06 -0700392 LOG(WARNING) << "Skipping duplicate class check due to unsupported classloader";
393 return CheckCollisionResult::kSkippedUnsupportedClassLoader;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700394 }
395
Mathieu Chartieradc90862018-05-11 13:03:06 -0700396 // If the oat file loading context matches the context used during compilation then we accept
Calin Juravle3f918642017-07-11 19:04:20 -0700397 // the oat file without addition checks
Mathieu Chartieradc90862018-05-11 13:03:06 -0700398 ClassLoaderContext::VerificationResult result = context->VerifyClassLoaderContextMatch(
399 oat_file->GetClassLoaderContext(),
Andreas Gampe98ea9d92018-10-19 14:06:15 -0700400 /*verify_names=*/ true,
401 /*verify_checksums=*/ true);
Mathieu Chartieradc90862018-05-11 13:03:06 -0700402 switch (result) {
403 case ClassLoaderContext::VerificationResult::kForcedToSkipChecks:
404 return CheckCollisionResult::kSkippedClassLoaderContextSharedLibrary;
405 case ClassLoaderContext::VerificationResult::kMismatch:
406 // Mismatched context, do the actual collision check.
407 break;
408 case ClassLoaderContext::VerificationResult::kVerifies:
409 return CheckCollisionResult::kNoCollisions;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700410 }
411
Calin Juravle3f918642017-07-11 19:04:20 -0700412 // The class loader context does not match. Perform a full duplicate classes check.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700413 return CheckClassCollision(oat_file, context, error_msg)
414 ? CheckCollisionResult::kPerformedHasCollisions : CheckCollisionResult::kNoCollisions;
415}
Calin Juravle3f918642017-07-11 19:04:20 -0700416
Mathieu Chartieradc90862018-05-11 13:03:06 -0700417bool OatFileManager::AcceptOatFile(CheckCollisionResult result) const {
418 // Take the file only if it has no collisions, or we must take it because of preopting.
419 // Also accept oat files for shared libraries and unsupported class loaders.
420 return result != CheckCollisionResult::kPerformedHasCollisions;
421}
Calin Juravle3f918642017-07-11 19:04:20 -0700422
Mathieu Chartieradc90862018-05-11 13:03:06 -0700423bool OatFileManager::ShouldLoadAppImage(CheckCollisionResult check_collision_result,
424 const OatFile* source_oat_file,
425 ClassLoaderContext* context,
426 std::string* error_msg) {
427 Runtime* const runtime = Runtime::Current();
428 if (kEnableAppImage && (!runtime->IsJavaDebuggable() || source_oat_file->IsDebuggable())) {
429 // If we verified the class loader context (skipping due to the special marker doesn't
430 // count), then also avoid the collision check.
431 bool load_image = check_collision_result == CheckCollisionResult::kNoCollisions;
432 // If we skipped the collision check, we need to reverify to be sure its OK to load the
433 // image.
434 if (!load_image &&
435 check_collision_result ==
436 CheckCollisionResult::kSkippedClassLoaderContextSharedLibrary) {
437 // We can load the app image only if there are no collisions. If we know the
438 // class loader but didn't do the full collision check in HasCollisions(),
439 // do it now. b/77342775
440 load_image = !CheckClassCollision(source_oat_file, context, error_msg);
441 }
442 return load_image;
443 }
444 return false;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700445}
446
447std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
448 const char* dex_location,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800449 jobject class_loader,
450 jobjectArray dex_elements,
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700451 const OatFile** out_oat_file,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700452 std::vector<std::string>* error_msgs) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800453 ScopedTrace trace(__FUNCTION__);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700454 CHECK(dex_location != nullptr);
455 CHECK(error_msgs != nullptr);
456
457 // Verify we aren't holding the mutator lock, which could starve GC if we
458 // have to generate or relocate an oat file.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800459 Thread* const self = Thread::Current();
460 Locks::mutator_lock_->AssertNotHeld(self);
461 Runtime* const runtime = Runtime::Current();
Calin Juravleb077e152016-02-18 18:47:37 +0000462
Calin Juravle27e0d1f2017-07-26 00:16:07 -0700463 std::unique_ptr<ClassLoaderContext> context;
464 // If the class_loader is null there's not much we can do. This happens if a dex files is loaded
465 // directly with DexFile APIs instead of using class loaders.
466 if (class_loader == nullptr) {
467 LOG(WARNING) << "Opening an oat file without a class loader. "
468 << "Are you using the deprecated DexFile APIs?";
469 context = nullptr;
470 } else {
471 context = ClassLoaderContext::CreateContextForClassLoader(class_loader, dex_elements);
472 }
473
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700474 OatFileAssistant oat_file_assistant(dex_location,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700475 kRuntimeISA,
Nicolas Geoffray29742602017-12-14 10:09:03 +0000476 !runtime->IsAotCompiler(),
477 only_use_system_oat_files_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700478
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700479 // Get the oat file on disk.
480 std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
Andreas Gampe9ea84d02018-03-02 09:32:03 -0800481 VLOG(oat) << "OatFileAssistant(" << dex_location << ").GetBestOatFile()="
482 << reinterpret_cast<uintptr_t>(oat_file.get())
483 << " (executable=" << (oat_file != nullptr ? oat_file->IsExecutable() : false) << ")";
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800484
Nicolas Geoffray3d8a78a2018-08-29 21:10:16 +0000485 const OatFile* source_oat_file = nullptr;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700486 CheckCollisionResult check_collision_result = CheckCollisionResult::kPerformedHasCollisions;
Nicolas Geoffray3d8a78a2018-08-29 21:10:16 +0000487 std::string error_msg;
Nicolas Geoffray29742602017-12-14 10:09:03 +0000488 if ((class_loader != nullptr || dex_elements != nullptr) && oat_file != nullptr) {
Nicolas Geoffray68bf3902017-09-07 14:40:48 +0100489 // Prevent oat files from being loaded if no class_loader or dex_elements are provided.
490 // This can happen when the deprecated DexFile.<init>(String) is called directly, and it
491 // could load oat files without checking the classpath, which would be incorrect.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700492 // Take the file only if it has no collisions, or we must take it because of preopting.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700493 check_collision_result = CheckCollision(oat_file.get(), context.get(), /*out*/ &error_msg);
494 bool accept_oat_file = AcceptOatFile(check_collision_result);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700495 if (!accept_oat_file) {
496 // Failed the collision check. Print warning.
Mathieu Chartieradc90862018-05-11 13:03:06 -0700497 if (runtime->IsDexFileFallbackEnabled()) {
Narayan Kamath5c525742017-04-28 10:19:29 +0100498 if (!oat_file_assistant.HasOriginalDexFiles()) {
499 // We need to fallback but don't have original dex files. We have to
500 // fallback to opening the existing oat file. This is potentially
501 // unsafe so we warn about it.
502 accept_oat_file = true;
503
504 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
505 << "Allow oat file use. This is potentially dangerous.";
506 } else {
507 // We have to fallback and found original dex files - extract them from an APK.
508 // Also warn about this operation because it's potentially wasteful.
509 LOG(WARNING) << "Found duplicate classes, falling back to extracting from APK : "
510 << dex_location;
511 LOG(WARNING) << "NOTE: This wastes RAM and hurts startup performance.";
512 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700513 } else {
Narayan Kamath5c525742017-04-28 10:19:29 +0100514 // TODO: We should remove this. The fact that we're here implies -Xno-dex-file-fallback
515 // was set, which means that we should never fallback. If we don't have original dex
516 // files, we should just fail resolution as the flag intended.
517 if (!oat_file_assistant.HasOriginalDexFiles()) {
518 accept_oat_file = true;
519 }
520
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700521 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
522 " load classes for " << dex_location;
523 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700524
Narayan Kamath5c525742017-04-28 10:19:29 +0100525 LOG(WARNING) << error_msg;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700526 }
527
528 if (accept_oat_file) {
529 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
530 source_oat_file = RegisterOatFile(std::move(oat_file));
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700531 *out_oat_file = source_oat_file;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700532 }
533 }
534
535 std::vector<std::unique_ptr<const DexFile>> dex_files;
536
537 // Load the dex files from the oat file.
538 if (source_oat_file != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800539 bool added_image_space = false;
540 if (source_oat_file->IsExecutable()) {
Chris Wailes23866362018-08-22 16:16:58 -0700541 ScopedTrace app_image_timing("AppImage:Loading");
542
Alex Light2ce6fc82017-12-18 16:42:36 -0800543 // We need to throw away the image space if we are debuggable but the oat-file source of the
544 // image is not otherwise we might get classes with inlined methods or other such things.
545 std::unique_ptr<gc::space::ImageSpace> image_space;
Mathieu Chartieradc90862018-05-11 13:03:06 -0700546 if (ShouldLoadAppImage(check_collision_result,
547 source_oat_file,
548 context.get(),
549 &error_msg)) {
Alex Light2ce6fc82017-12-18 16:42:36 -0800550 image_space = oat_file_assistant.OpenImageSpace(source_oat_file);
Alex Light2ce6fc82017-12-18 16:42:36 -0800551 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800552 if (image_space != nullptr) {
553 ScopedObjectAccess soa(self);
554 StackHandleScope<1> hs(self);
555 Handle<mirror::ClassLoader> h_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700556 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800557 // Can not load app image without class loader.
Andreas Gampefa4333d2017-02-14 11:10:34 -0800558 if (h_loader != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800559 std::string temp_error_msg;
560 // Add image space has a race condition since other threads could be reading from the
561 // spaces array.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800562 {
563 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800564 gc::ScopedGCCriticalSection gcs(self,
565 gc::kGcCauseAddRemoveAppImageSpace,
566 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800567 ScopedSuspendAll ssa("Add image space");
568 runtime->GetHeap()->AddSpace(image_space.get());
569 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800570 {
571 ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
572 added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
573 h_loader,
574 dex_elements,
575 dex_location,
576 /*out*/&dex_files,
577 /*out*/&temp_error_msg);
578 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800579 if (added_image_space) {
Mathieu Chartierbd064ea2016-02-11 16:27:18 -0800580 // Successfully added image space to heap, release the map so that it does not get
581 // freed.
Andreas Gampeafaf7f82018-10-16 11:32:38 -0700582 image_space.release(); // NOLINT b/117926937
Bharadwaj Kalandhabhatta0bb40312017-06-01 10:47:00 -0700583
584 // Register for tracking.
585 for (const auto& dex_file : dex_files) {
586 dex::tracking::RegisterDexFile(dex_file.get());
587 }
Mathieu Chartierbd064ea2016-02-11 16:27:18 -0800588 } else {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800589 LOG(INFO) << "Failed to add image file " << temp_error_msg;
590 dex_files.clear();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800591 {
592 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800593 gc::ScopedGCCriticalSection gcs(self,
594 gc::kGcCauseAddRemoveAppImageSpace,
595 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800596 ScopedSuspendAll ssa("Remove image space");
597 runtime->GetHeap()->RemoveSpace(image_space.get());
598 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800599 // Non-fatal, don't update error_msg.
600 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800601 }
602 }
603 }
604 if (!added_image_space) {
605 DCHECK(dex_files.empty());
606 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
Bharadwaj Kalandhabhatta0bb40312017-06-01 10:47:00 -0700607
608 // Register for tracking.
609 for (const auto& dex_file : dex_files) {
610 dex::tracking::RegisterDexFile(dex_file.get());
611 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800612 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700613 if (dex_files.empty()) {
614 error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
Mathieu Chartierbe8303d2017-08-17 17:39:39 -0700615 } else {
Mathieu Chartier120aa282017-08-05 16:03:03 -0700616 // Opened dex files from an oat file, madvise them to their loaded state.
617 for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
618 OatDexFile::MadviseDexFile(*dex_file, MadviseState::kMadviseStateAtLoad);
619 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700620 }
621 }
622
623 // Fall back to running out of the original dex file if we couldn't load any
624 // dex_files from the oat file.
625 if (dex_files.empty()) {
626 if (oat_file_assistant.HasOriginalDexFiles()) {
627 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700628 static constexpr bool kVerifyChecksum = true;
David Sehr013fd802018-01-11 22:55:24 -0800629 const ArtDexFileLoader dex_file_loader;
630 if (!dex_file_loader.Open(dex_location,
631 dex_location,
632 Runtime::Current()->IsVerificationEnabled(),
633 kVerifyChecksum,
634 /*out*/ &error_msg,
635 &dex_files)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700636 LOG(WARNING) << error_msg;
Alex Light3045b662016-04-20 14:26:34 -0700637 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
638 + " because: " + error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700639 }
640 } else {
641 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
642 }
643 } else {
randy.jeonge8e2d002019-05-24 13:37:34 +0900644 std::string msg = StringPrintf("No original dex files found for dex location (%s) %s",
645 GetInstructionSetString(kRuntimeISA), dex_location);
646 error_msgs->push_back(msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700647 }
648 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000649
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100650 if (Runtime::Current()->GetJit() != nullptr) {
Nicolas Geoffray741a0702019-06-10 11:18:11 +0100651 Runtime::Current()->GetJit()->RegisterDexFiles(dex_files, class_loader);
Nicolas Geoffray9ac09ee2019-05-08 23:38:27 +0100652 }
653
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700654 return dex_files;
655}
656
David Brazdil7126c5b2019-03-05 00:02:51 +0000657static std::vector<const DexFile::Header*> GetDexFileHeaders(const std::vector<MemMap>& maps) {
658 std::vector<const DexFile::Header*> headers;
659 headers.reserve(maps.size());
660 for (const MemMap& map : maps) {
661 DCHECK(map.IsValid());
662 headers.push_back(reinterpret_cast<const DexFile::Header*>(map.Begin()));
663 }
664 return headers;
665}
666
David Brazdil35a3f6a2019-03-04 15:59:06 +0000667static std::vector<const DexFile::Header*> GetDexFileHeaders(
668 const std::vector<const DexFile*>& dex_files) {
669 std::vector<const DexFile::Header*> headers;
670 headers.reserve(dex_files.size());
671 for (const DexFile* dex_file : dex_files) {
672 headers.push_back(&dex_file->GetHeader());
673 }
674 return headers;
675}
676
David Brazdil7126c5b2019-03-05 00:02:51 +0000677std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
678 std::vector<MemMap>&& dex_mem_maps,
679 jobject class_loader,
680 jobjectArray dex_elements,
681 const OatFile** out_oat_file,
682 std::vector<std::string>* error_msgs) {
683 std::vector<std::unique_ptr<const DexFile>> dex_files = OpenDexFilesFromOat_Impl(
684 std::move(dex_mem_maps),
685 class_loader,
686 dex_elements,
687 out_oat_file,
688 error_msgs);
689
690 if (error_msgs->empty()) {
691 // Remove write permission from DexFile pages. We do this at the end because
692 // OatFile assigns OatDexFile pointer in the DexFile objects.
693 for (std::unique_ptr<const DexFile>& dex_file : dex_files) {
694 if (!dex_file->DisableWrite()) {
695 error_msgs->push_back("Failed to make dex file " + dex_file->GetLocation() + " read-only");
696 }
697 }
698 }
699
700 if (!error_msgs->empty()) {
701 return std::vector<std::unique_ptr<const DexFile>>();
702 }
703
704 return dex_files;
705}
706
707std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat_Impl(
708 std::vector<MemMap>&& dex_mem_maps,
709 jobject class_loader,
710 jobjectArray dex_elements,
711 const OatFile** out_oat_file,
712 std::vector<std::string>* error_msgs) {
713 ScopedTrace trace(__FUNCTION__);
714 std::string error_msg;
715 DCHECK(error_msgs != nullptr);
716
717 // Extract dex file headers from `dex_mem_maps`.
718 const std::vector<const DexFile::Header*> dex_headers = GetDexFileHeaders(dex_mem_maps);
719
720 // Determine dex/vdex locations and the combined location checksum.
721 uint32_t location_checksum;
722 std::string dex_location;
723 std::string vdex_path;
724 bool has_vdex = OatFileAssistant::AnonymousDexVdexLocation(dex_headers,
725 kRuntimeISA,
726 &location_checksum,
727 &dex_location,
728 &vdex_path);
729
730 // Attempt to open an existing vdex and check dex file checksums match.
731 std::unique_ptr<VdexFile> vdex_file = nullptr;
732 if (has_vdex && OS::FileExists(vdex_path.c_str())) {
733 vdex_file = VdexFile::Open(vdex_path,
734 /* writable= */ false,
735 /* low_4gb= */ false,
736 /* unquicken= */ false,
737 &error_msg);
738 if (vdex_file == nullptr) {
739 LOG(WARNING) << "Failed to open vdex " << vdex_path << ": " << error_msg;
740 } else if (!vdex_file->MatchesDexFileChecksums(dex_headers)) {
741 LOG(WARNING) << "Failed to open vdex " << vdex_path << ": dex file checksum mismatch";
742 vdex_file.reset(nullptr);
743 }
744 }
745
746 // Load dex files. Skip structural dex file verification if vdex was found
747 // and dex checksums matched.
748 std::vector<std::unique_ptr<const DexFile>> dex_files;
749 for (size_t i = 0; i < dex_mem_maps.size(); ++i) {
750 static constexpr bool kVerifyChecksum = true;
751 const ArtDexFileLoader dex_file_loader;
752 std::unique_ptr<const DexFile> dex_file(dex_file_loader.Open(
753 DexFileLoader::GetMultiDexLocation(i, dex_location.c_str()),
754 location_checksum,
755 std::move(dex_mem_maps[i]),
756 /* verify= */ (vdex_file == nullptr) && Runtime::Current()->IsVerificationEnabled(),
757 kVerifyChecksum,
758 &error_msg));
759 if (dex_file != nullptr) {
760 dex::tracking::RegisterDexFile(dex_file.get()); // Register for tracking.
761 dex_files.push_back(std::move(dex_file));
762 } else {
763 error_msgs->push_back("Failed to open dex files from memory: " + error_msg);
764 }
765 }
766
767 // Check if we should proceed to creating an OatFile instance backed by the vdex.
768 // We need: (a) an existing vdex, (b) class loader (can be null if invoked via reflection),
769 // and (c) no errors during dex file loading.
770 if (vdex_file == nullptr || class_loader == nullptr || !error_msgs->empty()) {
771 return dex_files;
772 }
773
774 // Attempt to create a class loader context, check OpenDexFiles succeeds (prerequisite
775 // for using the context later).
776 std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::CreateContextForClassLoader(
777 class_loader,
778 dex_elements);
779 if (context == nullptr) {
780 LOG(ERROR) << "Could not create class loader context for " << vdex_path;
781 return dex_files;
782 }
783 DCHECK(context->OpenDexFiles(kRuntimeISA, ""))
784 << "Context created from already opened dex files should not attempt to open again";
785
786 // Check that we can use the vdex against this boot class path and in this class loader context.
787 // Note 1: We do not need a class loader collision check because there is no compiled code.
788 // Note 2: If these checks fail, we cannot fast-verify because the vdex does not contain
789 // full VerifierDeps.
790 if (!vdex_file->MatchesBootClassPathChecksums() ||
791 !vdex_file->MatchesClassLoaderContext(*context.get())) {
792 return dex_files;
793 }
794
795 // Initialize an OatFile instance backed by the loaded vdex.
796 std::unique_ptr<OatFile> oat_file(OatFile::OpenFromVdex(MakeNonOwningPointerVector(dex_files),
797 std::move(vdex_file),
798 dex_location));
799 DCHECK(oat_file != nullptr);
800 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
801 *out_oat_file = RegisterOatFile(std::move(oat_file));
802 return dex_files;
803}
804
David Brazdil35a3f6a2019-03-04 15:59:06 +0000805// Check how many vdex files exist in the same directory as the vdex file we are about
806// to write. If more than or equal to kAnonymousVdexCacheSize, unlink the least
807// recently used one(s) (according to stat-reported atime).
808static bool UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string& vdex_path_to_add,
809 std::string* error_msg) {
810 if (OS::FileExists(vdex_path_to_add.c_str())) {
811 // File already exists and will be overwritten.
812 // This will not change the number of entries in the cache.
813 return true;
814 }
815
816 auto last_slash = vdex_path_to_add.rfind('/');
817 CHECK(last_slash != std::string::npos);
818 std::string vdex_dir = vdex_path_to_add.substr(0, last_slash + 1);
819
820 if (!OS::DirectoryExists(vdex_dir.c_str())) {
821 // Folder does not exist yet. Cache has zero entries.
822 return true;
823 }
824
825 std::vector<std::pair<time_t, std::string>> cache;
826
827 DIR* c_dir = opendir(vdex_dir.c_str());
828 if (c_dir == nullptr) {
829 *error_msg = "Unable to open " + vdex_dir + " to delete unused vdex files";
830 return false;
831 }
832 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
833 if (de->d_type != DT_REG) {
834 continue;
835 }
836 std::string basename = de->d_name;
837 if (!OatFileAssistant::IsAnonymousVdexBasename(basename)) {
838 continue;
839 }
840 std::string fullname = vdex_dir + basename;
841
842 struct stat s;
843 int rc = TEMP_FAILURE_RETRY(stat(fullname.c_str(), &s));
844 if (rc == -1) {
845 *error_msg = "Failed to stat() anonymous vdex file " + fullname;
846 return false;
847 }
848
849 cache.push_back(std::make_pair(s.st_atime, fullname));
850 }
851 CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
852
853 if (cache.size() < OatFileManager::kAnonymousVdexCacheSize) {
854 return true;
855 }
856
857 std::sort(cache.begin(),
858 cache.end(),
859 [](const auto& a, const auto& b) { return a.first < b.first; });
860 for (size_t i = OatFileManager::kAnonymousVdexCacheSize - 1; i < cache.size(); ++i) {
861 if (unlink(cache[i].second.c_str()) != 0) {
862 *error_msg = "Could not unlink anonymous vdex file " + cache[i].second;
863 return false;
864 }
865 }
866
867 return true;
868}
869
David Brazdil331a5e12019-04-01 22:46:16 +0000870class BackgroundVerificationTask final : public Task {
871 public:
David Brazdil35a3f6a2019-03-04 15:59:06 +0000872 BackgroundVerificationTask(const std::vector<const DexFile*>& dex_files,
873 jobject class_loader,
874 const char* class_loader_context,
875 const std::string& vdex_path)
876 : dex_files_(dex_files),
877 class_loader_context_(class_loader_context),
878 vdex_path_(vdex_path) {
David Brazdil331a5e12019-04-01 22:46:16 +0000879 Thread* const self = Thread::Current();
880 ScopedObjectAccess soa(self);
881 // Create a global ref for `class_loader` because it will be accessed from a different thread.
882 class_loader_ = soa.Vm()->AddGlobalRef(self, soa.Decode<mirror::ClassLoader>(class_loader));
883 CHECK(class_loader_ != nullptr);
884 }
885
886 ~BackgroundVerificationTask() {
887 Thread* const self = Thread::Current();
888 ScopedObjectAccess soa(self);
889 soa.Vm()->DeleteGlobalRef(self, class_loader_);
890 }
891
892 void Run(Thread* self) override {
David Brazdil35a3f6a2019-03-04 15:59:06 +0000893 std::string error_msg;
David Brazdil331a5e12019-04-01 22:46:16 +0000894 ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
David Brazdil35a3f6a2019-03-04 15:59:06 +0000895 verifier::VerifierDeps verifier_deps(dex_files_);
David Brazdil331a5e12019-04-01 22:46:16 +0000896
897 // Iterate over all classes and verify them.
898 for (const DexFile* dex_file : dex_files_) {
899 for (uint32_t cdef_idx = 0; cdef_idx < dex_file->NumClassDefs(); cdef_idx++) {
David Brazdil35a3f6a2019-03-04 15:59:06 +0000900 const dex::ClassDef& class_def = dex_file->GetClassDef(cdef_idx);
901
David Brazdil331a5e12019-04-01 22:46:16 +0000902 // Take handles inside the loop. The background verification is low priority
903 // and we want to minimize the risk of blocking anyone else.
904 ScopedObjectAccess soa(self);
905 StackHandleScope<2> hs(self);
906 Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
907 soa.Decode<mirror::ClassLoader>(class_loader_)));
908 Handle<mirror::Class> h_class(hs.NewHandle<mirror::Class>(class_linker->FindClass(
909 self,
David Brazdil35a3f6a2019-03-04 15:59:06 +0000910 dex_file->GetClassDescriptor(class_def),
David Brazdil331a5e12019-04-01 22:46:16 +0000911 h_loader)));
912
913 if (h_class == nullptr) {
914 CHECK(self->IsExceptionPending());
915 self->ClearException();
916 continue;
917 }
918
919 if (&h_class->GetDexFile() != dex_file) {
920 // There is a different class in the class path or a parent class loader
921 // with the same descriptor. This `h_class` is not resolvable, skip it.
922 continue;
923 }
924
925 CHECK(h_class->IsResolved()) << h_class->PrettyDescriptor();
926 class_linker->VerifyClass(self, h_class);
927 if (h_class->IsErroneous()) {
928 // ClassLinker::VerifyClass throws, which isn't useful here.
929 CHECK(soa.Self()->IsExceptionPending());
930 soa.Self()->ClearException();
931 }
932
933 CHECK(h_class->IsVerified() || h_class->IsErroneous())
934 << h_class->PrettyDescriptor() << ": state=" << h_class->GetStatus();
David Brazdil35a3f6a2019-03-04 15:59:06 +0000935
936 if (h_class->IsVerified()) {
937 verifier_deps.RecordClassVerified(*dex_file, class_def);
938 }
David Brazdil331a5e12019-04-01 22:46:16 +0000939 }
940 }
David Brazdil35a3f6a2019-03-04 15:59:06 +0000941
942 // Delete old vdex files if there are too many in the folder.
943 if (!UnlinkLeastRecentlyUsedVdexIfNeeded(vdex_path_, &error_msg)) {
944 LOG(ERROR) << "Could not unlink old vdex files " << vdex_path_ << ": " << error_msg;
945 return;
946 }
947
948 // Construct a vdex file and write `verifier_deps` into it.
949 if (!VdexFile::WriteToDisk(vdex_path_,
950 dex_files_,
951 verifier_deps,
952 class_loader_context_,
953 &error_msg)) {
954 LOG(ERROR) << "Could not write anonymous vdex " << vdex_path_ << ": " << error_msg;
955 return;
956 }
David Brazdil331a5e12019-04-01 22:46:16 +0000957 }
958
959 void Finalize() override {
960 delete this;
961 }
962
963 private:
964 const std::vector<const DexFile*> dex_files_;
965 jobject class_loader_;
David Brazdil35a3f6a2019-03-04 15:59:06 +0000966 const std::string class_loader_context_;
967 const std::string vdex_path_;
David Brazdil331a5e12019-04-01 22:46:16 +0000968
969 DISALLOW_COPY_AND_ASSIGN(BackgroundVerificationTask);
970};
971
972void OatFileManager::RunBackgroundVerification(const std::vector<const DexFile*>& dex_files,
David Brazdil35a3f6a2019-03-04 15:59:06 +0000973 jobject class_loader,
974 const char* class_loader_context) {
David Brazdil527072e2019-04-03 15:15:40 +0100975 Runtime* const runtime = Runtime::Current();
976 Thread* const self = Thread::Current();
977
978 if (runtime->IsJavaDebuggable()) {
David Brazdil331a5e12019-04-01 22:46:16 +0000979 // Threads created by ThreadPool ("runtime threads") are not allowed to load
980 // classes when debuggable to match class-initialization semantics
981 // expectations. Do not verify in the background.
982 return;
983 }
984
David Brazdil527072e2019-04-03 15:15:40 +0100985 if (!IsSdkVersionSetAndAtLeast(runtime->GetTargetSdkVersion(), SdkVersion::kQ)) {
986 // Do not run for legacy apps as they may depend on the previous class loader behaviour.
987 return;
988 }
989
990 if (runtime->IsShuttingDown(self)) {
David Brazdil331a5e12019-04-01 22:46:16 +0000991 // Not allowed to create new threads during runtime shutdown.
992 return;
993 }
994
David Brazdil35a3f6a2019-03-04 15:59:06 +0000995 uint32_t location_checksum;
996 std::string dex_location;
997 std::string vdex_path;
998 if (OatFileAssistant::AnonymousDexVdexLocation(GetDexFileHeaders(dex_files),
999 kRuntimeISA,
1000 &location_checksum,
1001 &dex_location,
1002 &vdex_path)) {
1003 if (verification_thread_pool_ == nullptr) {
1004 verification_thread_pool_.reset(
1005 new ThreadPool("Verification thread pool", /* num_threads= */ 1));
1006 verification_thread_pool_->StartWorkers(self);
1007 }
1008 verification_thread_pool_->AddTask(self, new BackgroundVerificationTask(
1009 dex_files,
1010 class_loader,
1011 class_loader_context,
1012 vdex_path));
David Brazdil331a5e12019-04-01 22:46:16 +00001013 }
David Brazdil331a5e12019-04-01 22:46:16 +00001014}
1015
1016void OatFileManager::WaitForWorkersToBeCreated() {
1017 DCHECK(!Runtime::Current()->IsShuttingDown(Thread::Current()))
1018 << "Cannot create new threads during runtime shutdown";
1019 if (verification_thread_pool_ != nullptr) {
1020 verification_thread_pool_->WaitForWorkersToBeCreated();
1021 }
1022}
1023
1024void OatFileManager::DeleteThreadPool() {
1025 verification_thread_pool_.reset(nullptr);
1026}
1027
1028void OatFileManager::WaitForBackgroundVerificationTasks() {
1029 if (verification_thread_pool_ != nullptr) {
1030 Thread* const self = Thread::Current();
1031 verification_thread_pool_->WaitForWorkersToBeCreated();
1032 verification_thread_pool_->Wait(self, /* do_work= */ true, /* may_hold_locks= */ false);
1033 }
1034}
1035
Andreas Gampe9ef308d2019-03-28 11:06:26 -07001036void OatFileManager::SetOnlyUseSystemOatFiles(bool enforce, bool assert_no_files_loaded) {
Nicolas Geoffray68bf3902017-09-07 14:40:48 +01001037 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Andreas Gampe9ef308d2019-03-28 11:06:26 -07001038 if (!only_use_system_oat_files_ && enforce && assert_no_files_loaded) {
Andreas Gampe99c07952019-03-30 17:43:55 +00001039 // Make sure all files that were loaded up to this point are on /system. Skip the image
1040 // files.
1041 std::vector<const OatFile*> boot_vector = GetBootOatFiles();
1042 std::unordered_set<const OatFile*> boot_set(boot_vector.begin(), boot_vector.end());
1043
1044 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
1045 if (boot_set.find(oat_file.get()) == boot_set.end()) {
1046 CHECK(LocationIsOnSystem(oat_file->GetLocation().c_str())) << oat_file->GetLocation();
1047 }
1048 }
Andreas Gampe3383f9c2019-03-15 11:46:08 -07001049 }
Andreas Gampe9ef308d2019-03-28 11:06:26 -07001050 only_use_system_oat_files_ = enforce;
Nicolas Geoffray68bf3902017-09-07 14:40:48 +01001051}
1052
Nicolas Geoffray04680f32016-03-17 11:56:54 +00001053void OatFileManager::DumpForSigQuit(std::ostream& os) {
1054 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
1055 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
1056 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
1057 if (ContainsElement(boot_oat_files, oat_file.get())) {
1058 continue;
1059 }
Andreas Gampe29d38e72016-03-23 15:31:51 +00001060 os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
Nicolas Geoffray04680f32016-03-17 11:56:54 +00001061 }
1062}
1063
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -07001064} // namespace art