blob: b34b5505eb1f5883aaee511b4fc9f1daa6f87790 [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>
22
23#include "base/logging.h"
24#include "base/stl_util.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080025#include "class_linker.h"
Mathieu Chartier80b37b72015-10-12 18:13:39 -070026#include "dex_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070027#include "gc/space/image_space.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080028#include "handle_scope-inl.h"
29#include "mirror/class_loader.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070030#include "oat_file_assistant.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080031#include "scoped_thread_state_change.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070032#include "thread-inl.h"
33
34namespace art {
35
36// For b/21333911.
Mathieu Chartier80b37b72015-10-12 18:13:39 -070037// Only enabled for debug builds to prevent bit rot. There are too many performance regressions for
38// normal builds.
39static constexpr bool kDuplicateClassesCheck = kIsDebugBuild;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070040
Mathieu Chartierfbc31082016-01-24 11:59:56 -080041// If true, then we attempt to load the application image if it exists.
42static constexpr bool kEnableAppImage = true;
43
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070044const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070045 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070046 DCHECK(oat_file != nullptr);
47 if (kIsDebugBuild) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070048 CHECK(oat_files_.find(oat_file) == oat_files_.end());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070049 for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
50 CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
51 // Check that we don't have an oat file with the same address. Copies of the same oat file
52 // should be loaded at different addresses.
53 CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
54 }
55 }
56 have_non_pic_oat_file_ = have_non_pic_oat_file_ || !oat_file->IsPic();
Mathieu Chartiere58991b2015-10-13 07:59:34 -070057 const OatFile* ret = oat_file.get();
58 oat_files_.insert(std::move(oat_file));
59 return ret;
60}
61
62void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
63 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
64 DCHECK(oat_file != nullptr);
65 std::unique_ptr<const OatFile> compare(oat_file);
66 auto it = oat_files_.find(compare);
67 CHECK(it != oat_files_.end());
68 oat_files_.erase(it);
69 compare.release();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070070}
71
72const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
73 const {
74 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartiere58991b2015-10-13 07:59:34 -070075 return FindOpenedOatFileFromOatLocationLocked(oat_location);
76}
77
78const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
79 const std::string& oat_location) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070080 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
81 if (oat_file->GetLocation() == oat_location) {
82 return oat_file.get();
83 }
84 }
85 return nullptr;
86}
87
Jeff Haodcdc85b2015-12-04 14:06:18 -080088std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
89 std::vector<const OatFile*> oat_files;
90 std::vector<gc::space::ImageSpace*> image_spaces =
91 Runtime::Current()->GetHeap()->GetBootImageSpaces();
92 for (gc::space::ImageSpace* image_space : image_spaces) {
93 oat_files.push_back(image_space->GetOatFile());
94 }
95 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070096}
97
98const OatFile* OatFileManager::GetPrimaryOatFile() const {
99 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800100 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
101 if (!boot_oat_files.empty()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700102 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800103 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
104 boot_oat_files.end()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700105 return oat_file.get();
106 }
107 }
108 }
109 return nullptr;
110}
111
112OatFileManager::~OatFileManager() {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700113 // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
114 // UnRegisterOatFileLocation.
115 oat_files_.clear();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700116}
117
Jeff Haodcdc85b2015-12-04 14:06:18 -0800118std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
119 std::vector<gc::space::ImageSpace*> spaces) {
120 std::vector<const OatFile*> oat_files;
121 for (gc::space::ImageSpace* space : spaces) {
122 oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
123 }
124 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700125}
126
127class DexFileAndClassPair : ValueObject {
128 public:
129 DexFileAndClassPair(const DexFile* dex_file, size_t current_class_index, bool from_loaded_oat)
130 : cached_descriptor_(GetClassDescriptor(dex_file, current_class_index)),
131 dex_file_(dex_file),
132 current_class_index_(current_class_index),
133 from_loaded_oat_(from_loaded_oat) {}
134
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700135 DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700136
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700137 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700138
139 const char* GetCachedDescriptor() const {
140 return cached_descriptor_;
141 }
142
143 bool operator<(const DexFileAndClassPair& rhs) const {
144 const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
145 if (cmp != 0) {
146 // Note that the order must be reversed. We want to iterate over the classes in dex files.
147 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
148 return cmp > 0;
149 }
150 return dex_file_ < rhs.dex_file_;
151 }
152
153 bool DexFileHasMoreClasses() const {
154 return current_class_index_ + 1 < dex_file_->NumClassDefs();
155 }
156
157 void Next() {
158 ++current_class_index_;
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700159 cached_descriptor_ = GetClassDescriptor(dex_file_.get(), current_class_index_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700160 }
161
162 size_t GetCurrentClassIndex() const {
163 return current_class_index_;
164 }
165
166 bool FromLoadedOat() const {
167 return from_loaded_oat_;
168 }
169
170 const DexFile* GetDexFile() const {
171 return dex_file_.get();
172 }
173
174 private:
175 static const char* GetClassDescriptor(const DexFile* dex_file, size_t index) {
176 DCHECK(IsUint<16>(index));
177 const DexFile::ClassDef& class_def = dex_file->GetClassDef(static_cast<uint16_t>(index));
178 return dex_file->StringByTypeIdx(class_def.class_idx_);
179 }
180
181 const char* cached_descriptor_;
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700182 std::shared_ptr<const DexFile> dex_file_;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700183 size_t current_class_index_;
184 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
185 // and what was loaded before. Any old duplicates must have been
186 // OK, and any new "internal" duplicates are as well (they must
187 // be from multidex, which resolves correctly).
188};
189
190static void AddDexFilesFromOat(const OatFile* oat_file,
191 bool already_loaded,
192 /*out*/std::priority_queue<DexFileAndClassPair>* heap) {
193 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
194 std::string error;
195 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
196 if (dex_file == nullptr) {
197 LOG(WARNING) << "Could not create dex file from oat file: " << error;
198 } else if (dex_file->NumClassDefs() > 0U) {
199 heap->emplace(dex_file.release(), /*current_class_index*/0U, already_loaded);
200 }
201 }
202}
203
204static void AddNext(/*inout*/DexFileAndClassPair* original,
205 /*inout*/std::priority_queue<DexFileAndClassPair>* heap) {
206 if (original->DexFileHasMoreClasses()) {
207 original->Next();
208 heap->push(std::move(*original));
209 }
210}
211
212// Check for class-def collisions in dex files.
213//
214// This works by maintaining a heap with one class from each dex file, sorted by the class
215// descriptor. Then a dex-file/class pair is continually removed from the heap and compared
216// against the following top element. If the descriptor is the same, it is now checked whether
217// the two elements agree on whether their dex file was from an already-loaded oat-file or the
218// new oat file. Any disagreement indicates a collision.
219bool OatFileManager::HasCollisions(const OatFile* oat_file,
220 std::string* error_msg /*out*/) const {
221 DCHECK(oat_file != nullptr);
222 DCHECK(error_msg != nullptr);
223 if (!kDuplicateClassesCheck) {
224 return false;
225 }
226
227 // Dex files are registered late - once a class is actually being loaded. We have to compare
228 // against the open oat files. Take the oat_file_manager_lock_ that protects oat_files_ accesses.
229 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
230
231 std::priority_queue<DexFileAndClassPair> queue;
232
233 // Add dex files from already loaded oat files, but skip boot.
Jeff Haodcdc85b2015-12-04 14:06:18 -0800234 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700235 // The same OatFile can be loaded multiple times at different addresses. In this case, we don't
236 // need to check both against each other since they would have resolved the same way at compile
237 // time.
238 std::unordered_set<std::string> unique_locations;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700239 for (const std::unique_ptr<const OatFile>& loaded_oat_file : oat_files_) {
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700240 DCHECK_NE(loaded_oat_file.get(), oat_file);
241 const std::string& location = loaded_oat_file->GetLocation();
Jeff Haodcdc85b2015-12-04 14:06:18 -0800242 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), loaded_oat_file.get()) ==
243 boot_oat_files.end() && location != oat_file->GetLocation() &&
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700244 unique_locations.find(location) == unique_locations.end()) {
245 unique_locations.insert(location);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700246 AddDexFilesFromOat(loaded_oat_file.get(), /*already_loaded*/true, &queue);
247 }
248 }
249
250 if (queue.empty()) {
251 // No other oat files, return early.
252 return false;
253 }
254
255 // Add dex files from the oat file to check.
256 AddDexFilesFromOat(oat_file, /*already_loaded*/false, &queue);
257
258 // Now drain the queue.
259 while (!queue.empty()) {
260 // Modifying the top element is only safe if we pop right after.
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700261 DexFileAndClassPair compare_pop(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700262 queue.pop();
263
264 // Compare against the following elements.
265 while (!queue.empty()) {
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700266 DexFileAndClassPair top(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700267
268 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
269 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
270 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
271 *error_msg =
272 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s",
273 compare_pop.GetCachedDescriptor(),
274 compare_pop.GetDexFile()->GetLocation().c_str(),
275 top.GetDexFile()->GetLocation().c_str());
276 return true;
277 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700278 queue.pop();
279 AddNext(&top, &queue);
280 } else {
281 // Something else. Done here.
282 break;
283 }
284 }
285 AddNext(&compare_pop, &queue);
286 }
287
288 return false;
289}
290
291std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
292 const char* dex_location,
293 const char* oat_location,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800294 jobject class_loader,
295 jobjectArray dex_elements,
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700296 const OatFile** out_oat_file,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700297 std::vector<std::string>* error_msgs) {
298 CHECK(dex_location != nullptr);
299 CHECK(error_msgs != nullptr);
300
301 // Verify we aren't holding the mutator lock, which could starve GC if we
302 // have to generate or relocate an oat file.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800303 Thread* const self = Thread::Current();
304 Locks::mutator_lock_->AssertNotHeld(self);
305 Runtime* const runtime = Runtime::Current();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700306 OatFileAssistant oat_file_assistant(dex_location,
307 oat_location,
308 kRuntimeISA,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800309 !runtime->IsAotCompiler());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700310
311 // Lock the target oat location to avoid races generating and loading the
312 // oat file.
313 std::string error_msg;
314 if (!oat_file_assistant.Lock(/*out*/&error_msg)) {
315 // Don't worry too much if this fails. If it does fail, it's unlikely we
316 // can generate an oat file anyway.
317 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
318 }
319
320 const OatFile* source_oat_file = nullptr;
321
Nicolas Geoffraye722d292015-12-15 11:51:37 +0000322 // Update the oat file on disk if we can. This may fail, but that's okay.
323 // Best effort is all that matters here.
324 if (!oat_file_assistant.MakeUpToDate(/*out*/&error_msg)) {
Nicolas Geoffraya28267f2015-12-16 12:34:50 +0000325 LOG(INFO) << error_msg;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700326 }
327
328 // Get the oat file on disk.
329 std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800330
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700331 if (oat_file != nullptr) {
332 // Take the file only if it has no collisions, or we must take it because of preopting.
333 bool accept_oat_file = !HasCollisions(oat_file.get(), /*out*/ &error_msg);
334 if (!accept_oat_file) {
335 // Failed the collision check. Print warning.
336 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
337 LOG(WARNING) << "Found duplicate classes, falling back to interpreter mode for "
338 << dex_location;
339 } else {
340 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
341 " load classes for " << dex_location;
342 }
343 LOG(WARNING) << error_msg;
344
345 // However, if the app was part of /system and preopted, there is no original dex file
346 // available. In that case grudgingly accept the oat file.
347 if (!DexFile::MaybeDex(dex_location)) {
348 accept_oat_file = true;
349 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
350 << "Allow oat file use. This is potentially dangerous.";
351 }
352 }
353
354 if (accept_oat_file) {
355 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
356 source_oat_file = RegisterOatFile(std::move(oat_file));
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700357 *out_oat_file = source_oat_file;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700358 }
359 }
360
361 std::vector<std::unique_ptr<const DexFile>> dex_files;
362
363 // Load the dex files from the oat file.
364 if (source_oat_file != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800365 bool added_image_space = false;
366 if (source_oat_file->IsExecutable()) {
367 std::unique_ptr<gc::space::ImageSpace> image_space(
368 kEnableAppImage ? oat_file_assistant.OpenImageSpace(source_oat_file) : nullptr);
369 if (image_space != nullptr) {
370 ScopedObjectAccess soa(self);
371 StackHandleScope<1> hs(self);
372 Handle<mirror::ClassLoader> h_loader(
373 hs.NewHandle(soa.Decode<mirror::ClassLoader*>(class_loader)));
374 // Can not load app image without class loader.
375 if (h_loader.Get() != nullptr) {
376 std::string temp_error_msg;
377 // Add image space has a race condition since other threads could be reading from the
378 // spaces array.
379 runtime->GetHeap()->AddSpace(image_space.get());
380 added_image_space = true;
381 if (!runtime->GetClassLinker()->AddImageSpace(image_space.get(),
382 h_loader,
383 dex_elements,
384 dex_location,
385 /*out*/&dex_files,
386 /*out*/&temp_error_msg)) {
387 LOG(INFO) << "Failed to add image file " << temp_error_msg;
388 dex_files.clear();
389 runtime->GetHeap()->RemoveSpace(image_space.get());
390 added_image_space = false;
391 // Non-fatal, don't update error_msg.
392 }
393 image_space.release();
394 }
395 }
396 }
397 if (!added_image_space) {
398 DCHECK(dex_files.empty());
399 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
400 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700401 if (dex_files.empty()) {
402 error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
403 }
404 }
405
406 // Fall back to running out of the original dex file if we couldn't load any
407 // dex_files from the oat file.
408 if (dex_files.empty()) {
409 if (oat_file_assistant.HasOriginalDexFiles()) {
410 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
411 if (!DexFile::Open(dex_location, dex_location, /*out*/ &error_msg, &dex_files)) {
412 LOG(WARNING) << error_msg;
413 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location));
414 }
415 } else {
416 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
417 }
418 } else {
419 error_msgs->push_back("No original dex files found for dex location "
420 + std::string(dex_location));
421 }
422 }
423 return dex_files;
424}
425
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700426bool OatFileManager::RegisterOatFileLocation(const std::string& oat_location) {
427 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_count_lock_);
428 auto it = oat_file_count_.find(oat_location);
429 if (it != oat_file_count_.end()) {
430 ++it->second;
431 return false;
432 }
433 oat_file_count_.insert(std::pair<std::string, size_t>(oat_location, 1u));
434 return true;
435}
436
437void OatFileManager::UnRegisterOatFileLocation(const std::string& oat_location) {
438 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_count_lock_);
439 auto it = oat_file_count_.find(oat_location);
440 if (it != oat_file_count_.end()) {
441 --it->second;
442 if (it->second == 0) {
443 oat_file_count_.erase(it);
444 }
445 }
446}
447
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700448} // namespace art