blob: 9eee156bb0d3f4990bbe3616e28872cbb18ab1bc [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 Chartier80b37b72015-10-12 18:13:39 -070025#include "dex_file-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070026#include "gc/space/image_space.h"
27#include "oat_file_assistant.h"
28#include "thread-inl.h"
29
30namespace art {
31
32// For b/21333911.
Mathieu Chartier80b37b72015-10-12 18:13:39 -070033// Only enabled for debug builds to prevent bit rot. There are too many performance regressions for
34// normal builds.
35static constexpr bool kDuplicateClassesCheck = kIsDebugBuild;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070036
37const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070038 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070039 DCHECK(oat_file != nullptr);
40 if (kIsDebugBuild) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070041 CHECK(oat_files_.find(oat_file) == oat_files_.end());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070042 for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
43 CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
44 // Check that we don't have an oat file with the same address. Copies of the same oat file
45 // should be loaded at different addresses.
46 CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
47 }
48 }
49 have_non_pic_oat_file_ = have_non_pic_oat_file_ || !oat_file->IsPic();
Mathieu Chartiere58991b2015-10-13 07:59:34 -070050 const OatFile* ret = oat_file.get();
51 oat_files_.insert(std::move(oat_file));
52 return ret;
53}
54
55void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
56 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
57 DCHECK(oat_file != nullptr);
58 std::unique_ptr<const OatFile> compare(oat_file);
59 auto it = oat_files_.find(compare);
60 CHECK(it != oat_files_.end());
61 oat_files_.erase(it);
62 compare.release();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070063}
64
65const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
66 const {
67 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartiere58991b2015-10-13 07:59:34 -070068 return FindOpenedOatFileFromOatLocationLocked(oat_location);
69}
70
71const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
72 const std::string& oat_location) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070073 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
74 if (oat_file->GetLocation() == oat_location) {
75 return oat_file.get();
76 }
77 }
78 return nullptr;
79}
80
81const OatFile* OatFileManager::GetBootOatFile() const {
82 gc::space::ImageSpace* image_space = Runtime::Current()->GetHeap()->GetImageSpace();
83 if (image_space == nullptr) {
84 return nullptr;
85 }
86 return image_space->GetOatFile();
87}
88
89const OatFile* OatFileManager::GetPrimaryOatFile() const {
90 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
91 const OatFile* boot_oat_file = GetBootOatFile();
92 if (boot_oat_file != nullptr) {
93 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
94 if (oat_file.get() != boot_oat_file) {
95 return oat_file.get();
96 }
97 }
98 }
99 return nullptr;
100}
101
102OatFileManager::~OatFileManager() {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700103 // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
104 // UnRegisterOatFileLocation.
105 oat_files_.clear();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700106}
107
108const OatFile* OatFileManager::RegisterImageOatFile(gc::space::ImageSpace* space) {
109 return RegisterOatFile(space->ReleaseOatFile());
110}
111
112class DexFileAndClassPair : ValueObject {
113 public:
114 DexFileAndClassPair(const DexFile* dex_file, size_t current_class_index, bool from_loaded_oat)
115 : cached_descriptor_(GetClassDescriptor(dex_file, current_class_index)),
116 dex_file_(dex_file),
117 current_class_index_(current_class_index),
118 from_loaded_oat_(from_loaded_oat) {}
119
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700120 DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700121
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700122 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700123
124 const char* GetCachedDescriptor() const {
125 return cached_descriptor_;
126 }
127
128 bool operator<(const DexFileAndClassPair& rhs) const {
129 const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
130 if (cmp != 0) {
131 // Note that the order must be reversed. We want to iterate over the classes in dex files.
132 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
133 return cmp > 0;
134 }
135 return dex_file_ < rhs.dex_file_;
136 }
137
138 bool DexFileHasMoreClasses() const {
139 return current_class_index_ + 1 < dex_file_->NumClassDefs();
140 }
141
142 void Next() {
143 ++current_class_index_;
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700144 cached_descriptor_ = GetClassDescriptor(dex_file_.get(), current_class_index_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700145 }
146
147 size_t GetCurrentClassIndex() const {
148 return current_class_index_;
149 }
150
151 bool FromLoadedOat() const {
152 return from_loaded_oat_;
153 }
154
155 const DexFile* GetDexFile() const {
156 return dex_file_.get();
157 }
158
159 private:
160 static const char* GetClassDescriptor(const DexFile* dex_file, size_t index) {
161 DCHECK(IsUint<16>(index));
162 const DexFile::ClassDef& class_def = dex_file->GetClassDef(static_cast<uint16_t>(index));
163 return dex_file->StringByTypeIdx(class_def.class_idx_);
164 }
165
166 const char* cached_descriptor_;
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700167 std::shared_ptr<const DexFile> dex_file_;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700168 size_t current_class_index_;
169 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
170 // and what was loaded before. Any old duplicates must have been
171 // OK, and any new "internal" duplicates are as well (they must
172 // be from multidex, which resolves correctly).
173};
174
175static void AddDexFilesFromOat(const OatFile* oat_file,
176 bool already_loaded,
177 /*out*/std::priority_queue<DexFileAndClassPair>* heap) {
178 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
179 std::string error;
180 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
181 if (dex_file == nullptr) {
182 LOG(WARNING) << "Could not create dex file from oat file: " << error;
183 } else if (dex_file->NumClassDefs() > 0U) {
184 heap->emplace(dex_file.release(), /*current_class_index*/0U, already_loaded);
185 }
186 }
187}
188
189static void AddNext(/*inout*/DexFileAndClassPair* original,
190 /*inout*/std::priority_queue<DexFileAndClassPair>* heap) {
191 if (original->DexFileHasMoreClasses()) {
192 original->Next();
193 heap->push(std::move(*original));
194 }
195}
196
197// Check for class-def collisions in dex files.
198//
199// This works by maintaining a heap with one class from each dex file, sorted by the class
200// descriptor. Then a dex-file/class pair is continually removed from the heap and compared
201// against the following top element. If the descriptor is the same, it is now checked whether
202// the two elements agree on whether their dex file was from an already-loaded oat-file or the
203// new oat file. Any disagreement indicates a collision.
204bool OatFileManager::HasCollisions(const OatFile* oat_file,
205 std::string* error_msg /*out*/) const {
206 DCHECK(oat_file != nullptr);
207 DCHECK(error_msg != nullptr);
208 if (!kDuplicateClassesCheck) {
209 return false;
210 }
211
212 // Dex files are registered late - once a class is actually being loaded. We have to compare
213 // against the open oat files. Take the oat_file_manager_lock_ that protects oat_files_ accesses.
214 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
215
216 std::priority_queue<DexFileAndClassPair> queue;
217
218 // Add dex files from already loaded oat files, but skip boot.
219 const OatFile* boot_oat = GetBootOatFile();
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700220 // The same OatFile can be loaded multiple times at different addresses. In this case, we don't
221 // need to check both against each other since they would have resolved the same way at compile
222 // time.
223 std::unordered_set<std::string> unique_locations;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700224 for (const std::unique_ptr<const OatFile>& loaded_oat_file : oat_files_) {
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700225 DCHECK_NE(loaded_oat_file.get(), oat_file);
226 const std::string& location = loaded_oat_file->GetLocation();
227 if (loaded_oat_file.get() != boot_oat &&
228 location != oat_file->GetLocation() &&
229 unique_locations.find(location) == unique_locations.end()) {
230 unique_locations.insert(location);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700231 AddDexFilesFromOat(loaded_oat_file.get(), /*already_loaded*/true, &queue);
232 }
233 }
234
235 if (queue.empty()) {
236 // No other oat files, return early.
237 return false;
238 }
239
240 // Add dex files from the oat file to check.
241 AddDexFilesFromOat(oat_file, /*already_loaded*/false, &queue);
242
243 // Now drain the queue.
244 while (!queue.empty()) {
245 // Modifying the top element is only safe if we pop right after.
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700246 DexFileAndClassPair compare_pop(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700247 queue.pop();
248
249 // Compare against the following elements.
250 while (!queue.empty()) {
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700251 DexFileAndClassPair top(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700252
253 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
254 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
255 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
256 *error_msg =
257 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s",
258 compare_pop.GetCachedDescriptor(),
259 compare_pop.GetDexFile()->GetLocation().c_str(),
260 top.GetDexFile()->GetLocation().c_str());
261 return true;
262 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700263 queue.pop();
264 AddNext(&top, &queue);
265 } else {
266 // Something else. Done here.
267 break;
268 }
269 }
270 AddNext(&compare_pop, &queue);
271 }
272
273 return false;
274}
275
276std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
277 const char* dex_location,
278 const char* oat_location,
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700279 const OatFile** out_oat_file,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700280 std::vector<std::string>* error_msgs) {
281 CHECK(dex_location != nullptr);
282 CHECK(error_msgs != nullptr);
283
284 // Verify we aren't holding the mutator lock, which could starve GC if we
285 // have to generate or relocate an oat file.
286 Locks::mutator_lock_->AssertNotHeld(Thread::Current());
287
288 OatFileAssistant oat_file_assistant(dex_location,
289 oat_location,
290 kRuntimeISA,
291 !Runtime::Current()->IsAotCompiler());
292
293 // Lock the target oat location to avoid races generating and loading the
294 // oat file.
295 std::string error_msg;
296 if (!oat_file_assistant.Lock(/*out*/&error_msg)) {
297 // Don't worry too much if this fails. If it does fail, it's unlikely we
298 // can generate an oat file anyway.
299 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
300 }
301
302 const OatFile* source_oat_file = nullptr;
303
304 // Update the oat file on disk if we can. This may fail, but that's okay.
305 // Best effort is all that matters here.
306 if (!oat_file_assistant.MakeUpToDate(/*out*/&error_msg)) {
307 LOG(WARNING) << error_msg;
308 }
309
310 // Get the oat file on disk.
311 std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
312 if (oat_file != nullptr) {
313 // Take the file only if it has no collisions, or we must take it because of preopting.
314 bool accept_oat_file = !HasCollisions(oat_file.get(), /*out*/ &error_msg);
315 if (!accept_oat_file) {
316 // Failed the collision check. Print warning.
317 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
318 LOG(WARNING) << "Found duplicate classes, falling back to interpreter mode for "
319 << dex_location;
320 } else {
321 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
322 " load classes for " << dex_location;
323 }
324 LOG(WARNING) << error_msg;
325
326 // However, if the app was part of /system and preopted, there is no original dex file
327 // available. In that case grudgingly accept the oat file.
328 if (!DexFile::MaybeDex(dex_location)) {
329 accept_oat_file = true;
330 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
331 << "Allow oat file use. This is potentially dangerous.";
332 }
333 }
334
335 if (accept_oat_file) {
336 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
337 source_oat_file = RegisterOatFile(std::move(oat_file));
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700338 *out_oat_file = source_oat_file;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700339 }
340 }
341
342 std::vector<std::unique_ptr<const DexFile>> dex_files;
343
344 // Load the dex files from the oat file.
345 if (source_oat_file != nullptr) {
346 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
347 if (dex_files.empty()) {
348 error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
349 }
350 }
351
352 // Fall back to running out of the original dex file if we couldn't load any
353 // dex_files from the oat file.
354 if (dex_files.empty()) {
355 if (oat_file_assistant.HasOriginalDexFiles()) {
356 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
357 if (!DexFile::Open(dex_location, dex_location, /*out*/ &error_msg, &dex_files)) {
358 LOG(WARNING) << error_msg;
359 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location));
360 }
361 } else {
362 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
363 }
364 } else {
365 error_msgs->push_back("No original dex files found for dex location "
366 + std::string(dex_location));
367 }
368 }
369 return dex_files;
370}
371
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700372bool OatFileManager::RegisterOatFileLocation(const std::string& oat_location) {
373 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_count_lock_);
374 auto it = oat_file_count_.find(oat_location);
375 if (it != oat_file_count_.end()) {
376 ++it->second;
377 return false;
378 }
379 oat_file_count_.insert(std::pair<std::string, size_t>(oat_location, 1u));
380 return true;
381}
382
383void OatFileManager::UnRegisterOatFileLocation(const std::string& oat_location) {
384 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_count_lock_);
385 auto it = oat_file_count_.find(oat_location);
386 if (it != oat_file_count_.end()) {
387 --it->second;
388 if (it->second == 0) {
389 oat_file_count_.erase(it);
390 }
391 }
392}
393
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700394} // namespace art