blob: d71ef547e03aba8c3ba364128aff75e510407df8 [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 Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080026#include "class_linker.h"
Mathieu Chartier80b37b72015-10-12 18:13:39 -070027#include "dex_file-inl.h"
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -080028#include "gc/scoped_gc_critical_section.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070029#include "gc/space/image_space.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080030#include "handle_scope-inl.h"
31#include "mirror/class_loader.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070032#include "oat_file_assistant.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070033#include "obj_ptr-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070034#include "scoped_thread_state_change-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070035#include "thread-inl.h"
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -080036#include "thread_list.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070037
38namespace art {
39
Mathieu Chartierfbc31082016-01-24 11:59:56 -080040// If true, then we attempt to load the application image if it exists.
41static constexpr bool kEnableAppImage = true;
42
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070043const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070044 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070045 DCHECK(oat_file != nullptr);
46 if (kIsDebugBuild) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070047 CHECK(oat_files_.find(oat_file) == oat_files_.end());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070048 for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
49 CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
50 // Check that we don't have an oat file with the same address. Copies of the same oat file
51 // should be loaded at different addresses.
52 CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
53 }
54 }
55 have_non_pic_oat_file_ = have_non_pic_oat_file_ || !oat_file->IsPic();
Mathieu Chartiere58991b2015-10-13 07:59:34 -070056 const OatFile* ret = oat_file.get();
57 oat_files_.insert(std::move(oat_file));
58 return ret;
59}
60
61void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
62 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
63 DCHECK(oat_file != nullptr);
64 std::unique_ptr<const OatFile> compare(oat_file);
65 auto it = oat_files_.find(compare);
66 CHECK(it != oat_files_.end());
67 oat_files_.erase(it);
68 compare.release();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070069}
70
Calin Juravle0b791272016-04-18 16:38:27 +010071const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
72 const std::string& dex_base_location) const {
73 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
74 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
75 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
76 for (const OatDexFile* oat_dex_file : oat_dex_files) {
77 if (DexFile::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
78 return oat_file.get();
79 }
80 }
81 }
82 return nullptr;
83}
84
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070085const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
86 const {
87 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartiere58991b2015-10-13 07:59:34 -070088 return FindOpenedOatFileFromOatLocationLocked(oat_location);
89}
90
91const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
92 const std::string& oat_location) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070093 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
94 if (oat_file->GetLocation() == oat_location) {
95 return oat_file.get();
96 }
97 }
98 return nullptr;
99}
100
Jeff Haodcdc85b2015-12-04 14:06:18 -0800101std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
102 std::vector<const OatFile*> oat_files;
103 std::vector<gc::space::ImageSpace*> image_spaces =
104 Runtime::Current()->GetHeap()->GetBootImageSpaces();
105 for (gc::space::ImageSpace* image_space : image_spaces) {
106 oat_files.push_back(image_space->GetOatFile());
107 }
108 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700109}
110
111const OatFile* OatFileManager::GetPrimaryOatFile() const {
112 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800113 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
114 if (!boot_oat_files.empty()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700115 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800116 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
117 boot_oat_files.end()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700118 return oat_file.get();
119 }
120 }
121 }
122 return nullptr;
123}
124
125OatFileManager::~OatFileManager() {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700126 // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
127 // UnRegisterOatFileLocation.
128 oat_files_.clear();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700129}
130
Jeff Haodcdc85b2015-12-04 14:06:18 -0800131std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
132 std::vector<gc::space::ImageSpace*> spaces) {
133 std::vector<const OatFile*> oat_files;
134 for (gc::space::ImageSpace* space : spaces) {
135 oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
136 }
137 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700138}
139
140class DexFileAndClassPair : ValueObject {
141 public:
142 DexFileAndClassPair(const DexFile* dex_file, size_t current_class_index, bool from_loaded_oat)
143 : cached_descriptor_(GetClassDescriptor(dex_file, current_class_index)),
144 dex_file_(dex_file),
145 current_class_index_(current_class_index),
146 from_loaded_oat_(from_loaded_oat) {}
147
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700148 DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700149
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700150 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700151
152 const char* GetCachedDescriptor() const {
153 return cached_descriptor_;
154 }
155
156 bool operator<(const DexFileAndClassPair& rhs) const {
157 const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
158 if (cmp != 0) {
159 // Note that the order must be reversed. We want to iterate over the classes in dex files.
160 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
161 return cmp > 0;
162 }
163 return dex_file_ < rhs.dex_file_;
164 }
165
166 bool DexFileHasMoreClasses() const {
167 return current_class_index_ + 1 < dex_file_->NumClassDefs();
168 }
169
170 void Next() {
171 ++current_class_index_;
Jeff Haof0192c82016-03-28 20:39:50 -0700172 cached_descriptor_ = GetClassDescriptor(dex_file_, current_class_index_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700173 }
174
175 size_t GetCurrentClassIndex() const {
176 return current_class_index_;
177 }
178
179 bool FromLoadedOat() const {
180 return from_loaded_oat_;
181 }
182
183 const DexFile* GetDexFile() const {
Jeff Haof0192c82016-03-28 20:39:50 -0700184 return dex_file_;
185 }
186
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700187 private:
188 static const char* GetClassDescriptor(const DexFile* dex_file, size_t index) {
189 DCHECK(IsUint<16>(index));
190 const DexFile::ClassDef& class_def = dex_file->GetClassDef(static_cast<uint16_t>(index));
191 return dex_file->StringByTypeIdx(class_def.class_idx_);
192 }
193
194 const char* cached_descriptor_;
Jeff Haof0192c82016-03-28 20:39:50 -0700195 const DexFile* dex_file_;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700196 size_t current_class_index_;
197 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
198 // and what was loaded before. Any old duplicates must have been
199 // OK, and any new "internal" duplicates are as well (they must
200 // be from multidex, which resolves correctly).
201};
202
203static void AddDexFilesFromOat(const OatFile* oat_file,
204 bool already_loaded,
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700205 /*out*/std::priority_queue<DexFileAndClassPair>* heap,
206 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700207 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
208 std::string error;
209 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
210 if (dex_file == nullptr) {
211 LOG(WARNING) << "Could not create dex file from oat file: " << error;
212 } else if (dex_file->NumClassDefs() > 0U) {
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700213 heap->emplace(dex_file.get(), /*current_class_index*/0U, already_loaded);
214 opened_dex_files->push_back(std::move(dex_file));
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700215 }
216 }
217}
218
219static void AddNext(/*inout*/DexFileAndClassPair* original,
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700220 /*inout*/std::priority_queue<DexFileAndClassPair>* heap) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700221 if (original->DexFileHasMoreClasses()) {
222 original->Next();
223 heap->push(std::move(*original));
Jeff Haof0192c82016-03-28 20:39:50 -0700224 }
225}
226
Mathieu Chartier3398c782016-09-30 10:27:43 -0700227static void IterateOverJavaDexFile(ObjPtr<mirror::Object> dex_file,
Jeff Haof0192c82016-03-28 20:39:50 -0700228 ArtField* const cookie_field,
229 std::function<bool(const DexFile*)> fn)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700230 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700231 if (dex_file != nullptr) {
232 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
233 if (long_array == nullptr) {
234 // This should never happen so log a warning.
235 LOG(WARNING) << "Null DexFile::mCookie";
236 return;
237 }
238 int32_t long_array_size = long_array->GetLength();
239 // Start from 1 to skip the oat file.
240 for (int32_t j = 1; j < long_array_size; ++j) {
241 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
242 long_array->GetWithoutChecks(j)));
243 if (!fn(cp_dex_file)) {
244 return;
245 }
246 }
247 }
248}
249
250static void IterateOverPathClassLoader(
251 ScopedObjectAccessAlreadyRunnable& soa,
252 Handle<mirror::ClassLoader> class_loader,
253 MutableHandle<mirror::ObjectArray<mirror::Object>> dex_elements,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700254 std::function<bool(const DexFile*)> fn) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700255 // Handle this step.
256 // Handle as if this is the child PathClassLoader.
257 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
258 // We need to get the DexPathList and loop through it.
259 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
260 ArtField* const dex_file_field =
261 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700262 ObjPtr<mirror::Object> dex_path_list =
Andreas Gampe46aba362016-10-28 14:33:28 -0700263 soa.DecodeField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
Jeff Haof0192c82016-03-28 20:39:50 -0700264 GetObject(class_loader.Get());
265 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
266 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -0700267 ObjPtr<mirror::Object> dex_elements_obj =
Jeff Haof0192c82016-03-28 20:39:50 -0700268 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
269 GetObject(dex_path_list);
270 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
271 // at the mCookie which is a DexFile vector.
272 if (dex_elements_obj != nullptr) {
273 dex_elements.Assign(dex_elements_obj->AsObjectArray<mirror::Object>());
274 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
275 mirror::Object* element = dex_elements->GetWithoutChecks(i);
276 if (element == nullptr) {
277 // Should never happen, fall back to java code to throw a NPE.
278 break;
279 }
Mathieu Chartier3398c782016-09-30 10:27:43 -0700280 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Jeff Haof0192c82016-03-28 20:39:50 -0700281 IterateOverJavaDexFile(dex_file, cookie_field, fn);
282 }
283 }
284 }
285}
286
287static bool GetDexFilesFromClassLoader(
288 ScopedObjectAccessAlreadyRunnable& soa,
289 mirror::ClassLoader* class_loader,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700290 std::priority_queue<DexFileAndClassPair>* queue) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700291 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
292 // The boot class loader. We don't load any of these files, as we know we compiled against
293 // them correctly.
294 return true;
295 }
296
297 // Unsupported class-loader?
Mathieu Chartier0795f232016-09-27 18:43:30 -0700298 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
299 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700300 VLOG(class_linker) << "Unsupported class-loader "
301 << mirror::Class::PrettyClass(class_loader->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700302 return false;
303 }
304
305 bool recursive_result = GetDexFilesFromClassLoader(soa, class_loader->GetParent(), queue);
306 if (!recursive_result) {
307 // Something wrong up the chain.
308 return false;
309 }
310
311 // Collect all the dex files.
312 auto GetDexFilesFn = [&] (const DexFile* cp_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700313 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700314 if (cp_dex_file->NumClassDefs() > 0) {
315 queue->emplace(cp_dex_file, 0U, true);
316 }
317 return true; // Continue looking.
318 };
319
320 // Handle for dex-cache-element.
321 StackHandleScope<3> hs(soa.Self());
322 MutableHandle<mirror::ObjectArray<mirror::Object>> dex_elements(
323 hs.NewHandle<mirror::ObjectArray<mirror::Object>>(nullptr));
324 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
325
326 IterateOverPathClassLoader(soa, h_class_loader, dex_elements, GetDexFilesFn);
327
328 return true;
329}
330
331static void GetDexFilesFromDexElementsArray(
332 ScopedObjectAccessAlreadyRunnable& soa,
333 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700334 std::priority_queue<DexFileAndClassPair>* queue) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700335 if (dex_elements.Get() == nullptr) {
336 // Nothing to do.
337 return;
338 }
339
340 ArtField* const cookie_field = soa.DecodeField(WellKnownClasses::dalvik_system_DexFile_cookie);
341 ArtField* const dex_file_field =
342 soa.DecodeField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700343 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
Jeff Haof0192c82016-03-28 20:39:50 -0700344 WellKnownClasses::dalvik_system_DexPathList__Element);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700345 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
346 WellKnownClasses::dalvik_system_DexFile);
Jeff Haof0192c82016-03-28 20:39:50 -0700347
348 // Collect all the dex files.
349 auto GetDexFilesFn = [&] (const DexFile* cp_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700350 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700351 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
352 queue->emplace(cp_dex_file, 0U, true);
353 }
354 return true; // Continue looking.
355 };
356
357 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
358 mirror::Object* element = dex_elements->GetWithoutChecks(i);
359 if (element == nullptr) {
360 continue;
361 }
362
363 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
364
Mathieu Chartier3398c782016-09-30 10:27:43 -0700365 ObjPtr<mirror::Object> dex_file;
Mathieu Chartier0795f232016-09-27 18:43:30 -0700366 if (element_class == element->GetClass()) {
Jeff Haof0192c82016-03-28 20:39:50 -0700367 dex_file = dex_file_field->GetObject(element);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700368 } else if (dexfile_class == element->GetClass()) {
Jeff Haof0192c82016-03-28 20:39:50 -0700369 dex_file = element;
370 } else {
David Sehr709b0702016-10-13 09:12:37 -0700371 LOG(WARNING) << "Unsupported element in dex_elements: "
372 << mirror::Class::PrettyClass(element->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700373 continue;
374 }
375
376 IterateOverJavaDexFile(dex_file, cookie_field, GetDexFilesFn);
377 }
378}
379
380static bool AreSharedLibrariesOk(const std::string shared_libraries,
381 std::priority_queue<DexFileAndClassPair>& queue) {
382 if (shared_libraries.empty()) {
383 if (queue.empty()) {
384 // No shared libraries or oat files, as expected.
385 return true;
386 }
387 } else {
388 if (shared_libraries.compare(OatFile::kSpecialSharedLibrary) == 0) {
389 // If we find the special shared library, skip the shared libraries check.
390 return true;
391 }
392 // Shared libraries is a series of dex file paths and their checksums, each separated by '*'.
393 std::vector<std::string> shared_libraries_split;
394 Split(shared_libraries, '*', &shared_libraries_split);
395
396 size_t index = 0;
397 std::priority_queue<DexFileAndClassPair> temp = queue;
398 while (!temp.empty() && index < shared_libraries_split.size() - 1) {
399 DexFileAndClassPair pair(temp.top());
400 const DexFile* dex_file = pair.GetDexFile();
Andreas Gampe4c481a42016-11-03 08:21:59 -0700401 const std::string& dex_filename = dex_file->GetLocation();
Jeff Haof0192c82016-03-28 20:39:50 -0700402 uint32_t dex_checksum = dex_file->GetLocationChecksum();
403 if (dex_filename != shared_libraries_split[index] ||
404 dex_checksum != std::stoul(shared_libraries_split[index + 1])) {
405 break;
406 }
407 temp.pop();
408 index += 2;
409 }
410
411 // Check is successful if it made it through the queue and all the shared libraries.
412 return temp.empty() && index == shared_libraries_split.size();
413 }
414 return false;
415}
416
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700417// Check for class-def collisions in dex files.
418//
Jeff Haof0192c82016-03-28 20:39:50 -0700419// This first walks the class loader chain, getting all the dex files from the class loader. If
420// the class loader is null or one of the class loaders in the chain is unsupported, we collect
421// dex files from all open non-boot oat files to be safe.
422//
423// This first checks whether the shared libraries are in the expected order and the oat files
424// have the expected checksums. If so, we exit early. Otherwise, we do the collision check.
425//
426// The collision check works by maintaining a heap with one class from each dex file, sorted by the
427// class descriptor. Then a dex-file/class pair is continually removed from the heap and compared
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700428// against the following top element. If the descriptor is the same, it is now checked whether
429// the two elements agree on whether their dex file was from an already-loaded oat-file or the
430// new oat file. Any disagreement indicates a collision.
431bool OatFileManager::HasCollisions(const OatFile* oat_file,
Jeff Haof0192c82016-03-28 20:39:50 -0700432 jobject class_loader,
433 jobjectArray dex_elements,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700434 std::string* error_msg /*out*/) const {
435 DCHECK(oat_file != nullptr);
436 DCHECK(error_msg != nullptr);
Jeff Haof0192c82016-03-28 20:39:50 -0700437
438 std::priority_queue<DexFileAndClassPair> queue;
Jeff Haof0192c82016-03-28 20:39:50 -0700439
440 // Try to get dex files from the given class loader. If the class loader is null, or we do
441 // not support one of the class loaders in the chain, conservatively compare against all
442 // (non-boot) oat files.
443 bool class_loader_ok = false;
444 {
445 ScopedObjectAccess soa(Thread::Current());
446 StackHandleScope<2> hs(Thread::Current());
447 Handle<mirror::ClassLoader> h_class_loader =
Mathieu Chartier0795f232016-09-27 18:43:30 -0700448 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
Jeff Haof0192c82016-03-28 20:39:50 -0700449 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
Mathieu Chartier0795f232016-09-27 18:43:30 -0700450 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
Jeff Haof0192c82016-03-28 20:39:50 -0700451 if (h_class_loader.Get() != nullptr &&
452 GetDexFilesFromClassLoader(soa, h_class_loader.Get(), &queue)) {
453 class_loader_ok = true;
454
455 // In this case, also take into account the dex_elements array, if given. We don't need to
456 // read it otherwise, as we'll compare against all open oat files anyways.
457 GetDexFilesFromDexElementsArray(soa, h_dex_elements, &queue);
458 } else if (h_class_loader.Get() != nullptr) {
459 VLOG(class_linker) << "Something unsupported with "
David Sehr709b0702016-10-13 09:12:37 -0700460 << mirror::Class::PrettyClass(h_class_loader->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700461 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700462 }
463
464 // Dex files are registered late - once a class is actually being loaded. We have to compare
465 // against the open oat files. Take the oat_file_manager_lock_ that protects oat_files_ accesses.
466 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
467
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700468 // Vector that holds the newly opened dex files live, this is done to prevent leaks.
469 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
470
Jeff Haof0192c82016-03-28 20:39:50 -0700471 if (!class_loader_ok) {
472 // Add dex files from already loaded oat files, but skip boot.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700473
Jeff Haof0192c82016-03-28 20:39:50 -0700474 // Clean up the queue.
475 while (!queue.empty()) {
476 queue.pop();
477 }
478
Jeff Haof0192c82016-03-28 20:39:50 -0700479 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
480 // The same OatFile can be loaded multiple times at different addresses. In this case, we don't
481 // need to check both against each other since they would have resolved the same way at compile
482 // time.
483 std::unordered_set<std::string> unique_locations;
484 for (const std::unique_ptr<const OatFile>& loaded_oat_file : oat_files_) {
485 DCHECK_NE(loaded_oat_file.get(), oat_file);
486 const std::string& location = loaded_oat_file->GetLocation();
487 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), loaded_oat_file.get()) ==
488 boot_oat_files.end() && location != oat_file->GetLocation() &&
489 unique_locations.find(location) == unique_locations.end()) {
490 unique_locations.insert(location);
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700491 AddDexFilesFromOat(loaded_oat_file.get(),
492 /*already_loaded*/true,
493 &queue,
494 /*out*/&opened_dex_files);
Jeff Haof0192c82016-03-28 20:39:50 -0700495 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700496 }
497 }
498
Jeff Haof0192c82016-03-28 20:39:50 -0700499 // Exit if shared libraries are ok. Do a full duplicate classes check otherwise.
500 const std::string
501 shared_libraries(oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey));
502 if (AreSharedLibrariesOk(shared_libraries, queue)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700503 return false;
504 }
505
Andreas Gampe1fdbe1b2016-06-10 08:36:20 -0700506 ScopedTrace st("Collision check");
507
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700508 // Add dex files from the oat file to check.
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700509 AddDexFilesFromOat(oat_file, /*already_loaded*/false, &queue, &opened_dex_files);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700510
511 // Now drain the queue.
512 while (!queue.empty()) {
513 // Modifying the top element is only safe if we pop right after.
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700514 DexFileAndClassPair compare_pop(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700515 queue.pop();
516
517 // Compare against the following elements.
518 while (!queue.empty()) {
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700519 DexFileAndClassPair top(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700520
521 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
522 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
523 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
524 *error_msg =
525 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s",
526 compare_pop.GetCachedDescriptor(),
527 compare_pop.GetDexFile()->GetLocation().c_str(),
528 top.GetDexFile()->GetLocation().c_str());
529 return true;
530 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700531 queue.pop();
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700532 AddNext(&top, &queue);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700533 } else {
534 // Something else. Done here.
535 break;
536 }
537 }
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700538 AddNext(&compare_pop, &queue);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700539 }
540
541 return false;
542}
543
544std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
545 const char* dex_location,
546 const char* oat_location,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800547 jobject class_loader,
548 jobjectArray dex_elements,
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700549 const OatFile** out_oat_file,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700550 std::vector<std::string>* error_msgs) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800551 ScopedTrace trace(__FUNCTION__);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700552 CHECK(dex_location != nullptr);
553 CHECK(error_msgs != nullptr);
554
555 // Verify we aren't holding the mutator lock, which could starve GC if we
556 // have to generate or relocate an oat file.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800557 Thread* const self = Thread::Current();
558 Locks::mutator_lock_->AssertNotHeld(self);
559 Runtime* const runtime = Runtime::Current();
Calin Juravleb077e152016-02-18 18:47:37 +0000560
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700561 OatFileAssistant oat_file_assistant(dex_location,
562 oat_location,
563 kRuntimeISA,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800564 !runtime->IsAotCompiler());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700565
566 // Lock the target oat location to avoid races generating and loading the
567 // oat file.
568 std::string error_msg;
569 if (!oat_file_assistant.Lock(/*out*/&error_msg)) {
570 // Don't worry too much if this fails. If it does fail, it's unlikely we
571 // can generate an oat file anyway.
572 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
573 }
574
575 const OatFile* source_oat_file = nullptr;
576
Richard Uhler01be6812016-05-17 10:34:52 -0700577 if (!oat_file_assistant.IsUpToDate()) {
578 // Update the oat file on disk if we can, based on the --compiler-filter
579 // option derived from the current runtime options.
580 // This may fail, but that's okay. Best effort is all that matters here.
Richard Uhlerd1472a22016-04-15 15:18:56 -0700581 switch (oat_file_assistant.MakeUpToDate(/*profile_changed*/false, /*out*/ &error_msg)) {
Richard Uhler01be6812016-05-17 10:34:52 -0700582 case OatFileAssistant::kUpdateFailed:
583 LOG(WARNING) << error_msg;
584 break;
Richard Uhler1e860612016-03-30 12:17:55 -0700585
Richard Uhler01be6812016-05-17 10:34:52 -0700586 case OatFileAssistant::kUpdateNotAttempted:
587 // Avoid spamming the logs if we decided not to attempt making the oat
588 // file up to date.
589 VLOG(oat) << error_msg;
590 break;
Richard Uhler1e860612016-03-30 12:17:55 -0700591
Richard Uhler01be6812016-05-17 10:34:52 -0700592 case OatFileAssistant::kUpdateSucceeded:
593 // Nothing to do.
594 break;
595 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700596 }
597
598 // Get the oat file on disk.
599 std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800600
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700601 if (oat_file != nullptr) {
602 // Take the file only if it has no collisions, or we must take it because of preopting.
Jeff Haof0192c82016-03-28 20:39:50 -0700603 bool accept_oat_file =
604 !HasCollisions(oat_file.get(), class_loader, dex_elements, /*out*/ &error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700605 if (!accept_oat_file) {
606 // Failed the collision check. Print warning.
607 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
608 LOG(WARNING) << "Found duplicate classes, falling back to interpreter mode for "
609 << dex_location;
610 } else {
611 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
612 " load classes for " << dex_location;
613 }
614 LOG(WARNING) << error_msg;
615
616 // However, if the app was part of /system and preopted, there is no original dex file
617 // available. In that case grudgingly accept the oat file.
Richard Uhler76f5cb62016-04-04 13:30:16 -0700618 if (!oat_file_assistant.HasOriginalDexFiles()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700619 accept_oat_file = true;
620 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
621 << "Allow oat file use. This is potentially dangerous.";
622 }
623 }
624
625 if (accept_oat_file) {
626 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
627 source_oat_file = RegisterOatFile(std::move(oat_file));
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700628 *out_oat_file = source_oat_file;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700629 }
630 }
631
632 std::vector<std::unique_ptr<const DexFile>> dex_files;
633
634 // Load the dex files from the oat file.
635 if (source_oat_file != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800636 bool added_image_space = false;
637 if (source_oat_file->IsExecutable()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700638 std::unique_ptr<gc::space::ImageSpace> image_space =
639 kEnableAppImage ? oat_file_assistant.OpenImageSpace(source_oat_file) : nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800640 if (image_space != nullptr) {
641 ScopedObjectAccess soa(self);
642 StackHandleScope<1> hs(self);
643 Handle<mirror::ClassLoader> h_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700644 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800645 // Can not load app image without class loader.
646 if (h_loader.Get() != nullptr) {
647 std::string temp_error_msg;
648 // Add image space has a race condition since other threads could be reading from the
649 // spaces array.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800650 {
651 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800652 gc::ScopedGCCriticalSection gcs(self,
653 gc::kGcCauseAddRemoveAppImageSpace,
654 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800655 ScopedSuspendAll ssa("Add image space");
656 runtime->GetHeap()->AddSpace(image_space.get());
657 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800658 {
659 ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
660 added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
661 h_loader,
662 dex_elements,
663 dex_location,
664 /*out*/&dex_files,
665 /*out*/&temp_error_msg);
666 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800667 if (added_image_space) {
Mathieu Chartierbd064ea2016-02-11 16:27:18 -0800668 // Successfully added image space to heap, release the map so that it does not get
669 // freed.
670 image_space.release();
671 } else {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800672 LOG(INFO) << "Failed to add image file " << temp_error_msg;
673 dex_files.clear();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800674 {
675 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800676 gc::ScopedGCCriticalSection gcs(self,
677 gc::kGcCauseAddRemoveAppImageSpace,
678 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800679 ScopedSuspendAll ssa("Remove image space");
680 runtime->GetHeap()->RemoveSpace(image_space.get());
681 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800682 // Non-fatal, don't update error_msg.
683 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800684 }
685 }
686 }
687 if (!added_image_space) {
688 DCHECK(dex_files.empty());
689 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
690 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700691 if (dex_files.empty()) {
692 error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
693 }
694 }
695
696 // Fall back to running out of the original dex file if we couldn't load any
697 // dex_files from the oat file.
698 if (dex_files.empty()) {
699 if (oat_file_assistant.HasOriginalDexFiles()) {
700 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700701 static constexpr bool kVerifyChecksum = true;
702 if (!DexFile::Open(
703 dex_location, dex_location, kVerifyChecksum, /*out*/ &error_msg, &dex_files)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700704 LOG(WARNING) << error_msg;
Alex Light3045b662016-04-20 14:26:34 -0700705 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
706 + " because: " + error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700707 }
708 } else {
709 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
710 }
711 } else {
712 error_msgs->push_back("No original dex files found for dex location "
713 + std::string(dex_location));
714 }
715 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000716
717 // TODO(calin): Consider optimizing this knowing that is useless to record the
718 // use of fully compiled apks.
719 Runtime::Current()->NotifyDexLoaded(dex_location);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700720 return dex_files;
721}
722
Nicolas Geoffray04680f32016-03-17 11:56:54 +0000723void OatFileManager::DumpForSigQuit(std::ostream& os) {
724 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
725 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
726 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
727 if (ContainsElement(boot_oat_files, oat_file.get())) {
728 continue;
729 }
Andreas Gampe29d38e72016-03-23 15:31:51 +0000730 os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
Nicolas Geoffray04680f32016-03-17 11:56:54 +0000731 }
732}
733
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700734} // namespace art