blob: 33bd0f311d7c7ad913212355f137d63c3d7e4337 [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
Andreas Gampe46ee31b2016-12-14 10:11:49 -080023#include "android-base/stringprintf.h"
24
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070025#include "base/logging.h"
26#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080027#include "base/systrace.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080028#include "class_linker.h"
Mathieu Chartier80b37b72015-10-12 18:13:39 -070029#include "dex_file-inl.h"
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -080030#include "gc/scoped_gc_critical_section.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070031#include "gc/space/image_space.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080032#include "handle_scope-inl.h"
Andreas Gampe08883de2016-11-08 13:20:52 -080033#include "jni_internal.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080034#include "mirror/class_loader.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070035#include "oat_file_assistant.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070036#include "obj_ptr-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070037#include "scoped_thread_state_change-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070038#include "thread-inl.h"
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -080039#include "thread_list.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070040
41namespace art {
42
Andreas Gampe46ee31b2016-12-14 10:11:49 -080043using android::base::StringPrintf;
44
Mathieu Chartierfbc31082016-01-24 11:59:56 -080045// If true, then we attempt to load the application image if it exists.
46static constexpr bool kEnableAppImage = true;
47
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070048const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070049 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070050 DCHECK(oat_file != nullptr);
51 if (kIsDebugBuild) {
Mathieu Chartiere58991b2015-10-13 07:59:34 -070052 CHECK(oat_files_.find(oat_file) == oat_files_.end());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070053 for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
54 CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
55 // Check that we don't have an oat file with the same address. Copies of the same oat file
56 // should be loaded at different addresses.
57 CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
58 }
59 }
60 have_non_pic_oat_file_ = have_non_pic_oat_file_ || !oat_file->IsPic();
Mathieu Chartiere58991b2015-10-13 07:59:34 -070061 const OatFile* ret = oat_file.get();
62 oat_files_.insert(std::move(oat_file));
63 return ret;
64}
65
66void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
67 WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
68 DCHECK(oat_file != nullptr);
69 std::unique_ptr<const OatFile> compare(oat_file);
70 auto it = oat_files_.find(compare);
71 CHECK(it != oat_files_.end());
72 oat_files_.erase(it);
73 compare.release();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070074}
75
Calin Juravle0b791272016-04-18 16:38:27 +010076const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
77 const std::string& dex_base_location) const {
78 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
79 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
80 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
81 for (const OatDexFile* oat_dex_file : oat_dex_files) {
82 if (DexFile::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
83 return oat_file.get();
84 }
85 }
86 }
87 return nullptr;
88}
89
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070090const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
91 const {
92 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartiere58991b2015-10-13 07:59:34 -070093 return FindOpenedOatFileFromOatLocationLocked(oat_location);
94}
95
96const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
97 const std::string& oat_location) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070098 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
99 if (oat_file->GetLocation() == oat_location) {
100 return oat_file.get();
101 }
102 }
103 return nullptr;
104}
105
Jeff Haodcdc85b2015-12-04 14:06:18 -0800106std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
107 std::vector<const OatFile*> oat_files;
108 std::vector<gc::space::ImageSpace*> image_spaces =
109 Runtime::Current()->GetHeap()->GetBootImageSpaces();
110 for (gc::space::ImageSpace* image_space : image_spaces) {
111 oat_files.push_back(image_space->GetOatFile());
112 }
113 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700114}
115
116const OatFile* OatFileManager::GetPrimaryOatFile() const {
117 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800118 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
119 if (!boot_oat_files.empty()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700120 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800121 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
122 boot_oat_files.end()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700123 return oat_file.get();
124 }
125 }
126 }
127 return nullptr;
128}
129
130OatFileManager::~OatFileManager() {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700131 // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
132 // UnRegisterOatFileLocation.
133 oat_files_.clear();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700134}
135
Jeff Haodcdc85b2015-12-04 14:06:18 -0800136std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
137 std::vector<gc::space::ImageSpace*> spaces) {
138 std::vector<const OatFile*> oat_files;
139 for (gc::space::ImageSpace* space : spaces) {
140 oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
141 }
142 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700143}
144
145class DexFileAndClassPair : ValueObject {
146 public:
147 DexFileAndClassPair(const DexFile* dex_file, size_t current_class_index, bool from_loaded_oat)
148 : cached_descriptor_(GetClassDescriptor(dex_file, current_class_index)),
149 dex_file_(dex_file),
150 current_class_index_(current_class_index),
151 from_loaded_oat_(from_loaded_oat) {}
152
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700153 DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700154
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700155 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700156
157 const char* GetCachedDescriptor() const {
158 return cached_descriptor_;
159 }
160
161 bool operator<(const DexFileAndClassPair& rhs) const {
162 const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
163 if (cmp != 0) {
164 // Note that the order must be reversed. We want to iterate over the classes in dex files.
165 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
166 return cmp > 0;
167 }
168 return dex_file_ < rhs.dex_file_;
169 }
170
171 bool DexFileHasMoreClasses() const {
172 return current_class_index_ + 1 < dex_file_->NumClassDefs();
173 }
174
175 void Next() {
176 ++current_class_index_;
Jeff Haof0192c82016-03-28 20:39:50 -0700177 cached_descriptor_ = GetClassDescriptor(dex_file_, current_class_index_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700178 }
179
180 size_t GetCurrentClassIndex() const {
181 return current_class_index_;
182 }
183
184 bool FromLoadedOat() const {
185 return from_loaded_oat_;
186 }
187
188 const DexFile* GetDexFile() const {
Jeff Haof0192c82016-03-28 20:39:50 -0700189 return dex_file_;
190 }
191
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700192 private:
193 static const char* GetClassDescriptor(const DexFile* dex_file, size_t index) {
194 DCHECK(IsUint<16>(index));
195 const DexFile::ClassDef& class_def = dex_file->GetClassDef(static_cast<uint16_t>(index));
196 return dex_file->StringByTypeIdx(class_def.class_idx_);
197 }
198
199 const char* cached_descriptor_;
Jeff Haof0192c82016-03-28 20:39:50 -0700200 const DexFile* dex_file_;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700201 size_t current_class_index_;
202 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
203 // and what was loaded before. Any old duplicates must have been
204 // OK, and any new "internal" duplicates are as well (they must
205 // be from multidex, which resolves correctly).
206};
207
208static void AddDexFilesFromOat(const OatFile* oat_file,
209 bool already_loaded,
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700210 /*out*/std::priority_queue<DexFileAndClassPair>* heap,
211 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700212 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
213 std::string error;
214 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
215 if (dex_file == nullptr) {
216 LOG(WARNING) << "Could not create dex file from oat file: " << error;
217 } else if (dex_file->NumClassDefs() > 0U) {
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700218 heap->emplace(dex_file.get(), /*current_class_index*/0U, already_loaded);
219 opened_dex_files->push_back(std::move(dex_file));
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700220 }
221 }
222}
223
224static void AddNext(/*inout*/DexFileAndClassPair* original,
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700225 /*inout*/std::priority_queue<DexFileAndClassPair>* heap) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700226 if (original->DexFileHasMoreClasses()) {
227 original->Next();
228 heap->push(std::move(*original));
Jeff Haof0192c82016-03-28 20:39:50 -0700229 }
230}
231
Andreas Gampeca620d72016-11-08 08:09:33 -0800232template <typename T>
Mathieu Chartier3398c782016-09-30 10:27:43 -0700233static void IterateOverJavaDexFile(ObjPtr<mirror::Object> dex_file,
Jeff Haof0192c82016-03-28 20:39:50 -0700234 ArtField* const cookie_field,
Andreas Gampeca620d72016-11-08 08:09:33 -0800235 const T& fn)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700236 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700237 if (dex_file != nullptr) {
238 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
239 if (long_array == nullptr) {
240 // This should never happen so log a warning.
241 LOG(WARNING) << "Null DexFile::mCookie";
242 return;
243 }
244 int32_t long_array_size = long_array->GetLength();
245 // Start from 1 to skip the oat file.
246 for (int32_t j = 1; j < long_array_size; ++j) {
247 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
248 long_array->GetWithoutChecks(j)));
249 if (!fn(cp_dex_file)) {
250 return;
251 }
252 }
253 }
254}
255
Andreas Gampeca620d72016-11-08 08:09:33 -0800256template <typename T>
Jeff Haof0192c82016-03-28 20:39:50 -0700257static void IterateOverPathClassLoader(
Jeff Haof0192c82016-03-28 20:39:50 -0700258 Handle<mirror::ClassLoader> class_loader,
259 MutableHandle<mirror::ObjectArray<mirror::Object>> dex_elements,
Andreas Gampeca620d72016-11-08 08:09:33 -0800260 const T& fn) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700261 // Handle this step.
262 // Handle as if this is the child PathClassLoader.
263 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
264 // We need to get the DexPathList and loop through it.
Andreas Gampe08883de2016-11-08 13:20:52 -0800265 ArtField* const cookie_field =
266 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Jeff Haof0192c82016-03-28 20:39:50 -0700267 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -0800268 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700269 ObjPtr<mirror::Object> dex_path_list =
Andreas Gampe08883de2016-11-08 13:20:52 -0800270 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
271 GetObject(class_loader.Get());
Jeff Haof0192c82016-03-28 20:39:50 -0700272 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
273 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -0700274 ObjPtr<mirror::Object> dex_elements_obj =
Andreas Gampe08883de2016-11-08 13:20:52 -0800275 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
276 GetObject(dex_path_list);
Jeff Haof0192c82016-03-28 20:39:50 -0700277 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
278 // at the mCookie which is a DexFile vector.
279 if (dex_elements_obj != nullptr) {
280 dex_elements.Assign(dex_elements_obj->AsObjectArray<mirror::Object>());
281 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
282 mirror::Object* element = dex_elements->GetWithoutChecks(i);
283 if (element == nullptr) {
284 // Should never happen, fall back to java code to throw a NPE.
285 break;
286 }
Mathieu Chartier3398c782016-09-30 10:27:43 -0700287 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Jeff Haof0192c82016-03-28 20:39:50 -0700288 IterateOverJavaDexFile(dex_file, cookie_field, fn);
289 }
290 }
291 }
292}
293
294static bool GetDexFilesFromClassLoader(
295 ScopedObjectAccessAlreadyRunnable& soa,
296 mirror::ClassLoader* class_loader,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700297 std::priority_queue<DexFileAndClassPair>* queue) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700298 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
299 // The boot class loader. We don't load any of these files, as we know we compiled against
300 // them correctly.
301 return true;
302 }
303
304 // Unsupported class-loader?
Mathieu Chartier0795f232016-09-27 18:43:30 -0700305 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
306 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700307 VLOG(class_linker) << "Unsupported class-loader "
308 << mirror::Class::PrettyClass(class_loader->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700309 return false;
310 }
311
312 bool recursive_result = GetDexFilesFromClassLoader(soa, class_loader->GetParent(), queue);
313 if (!recursive_result) {
314 // Something wrong up the chain.
315 return false;
316 }
317
318 // Collect all the dex files.
319 auto GetDexFilesFn = [&] (const DexFile* cp_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700320 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700321 if (cp_dex_file->NumClassDefs() > 0) {
322 queue->emplace(cp_dex_file, 0U, true);
323 }
324 return true; // Continue looking.
325 };
326
327 // Handle for dex-cache-element.
328 StackHandleScope<3> hs(soa.Self());
329 MutableHandle<mirror::ObjectArray<mirror::Object>> dex_elements(
330 hs.NewHandle<mirror::ObjectArray<mirror::Object>>(nullptr));
331 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
332
Andreas Gampe08883de2016-11-08 13:20:52 -0800333 IterateOverPathClassLoader(h_class_loader, dex_elements, GetDexFilesFn);
Jeff Haof0192c82016-03-28 20:39:50 -0700334
335 return true;
336}
337
338static void GetDexFilesFromDexElementsArray(
339 ScopedObjectAccessAlreadyRunnable& soa,
340 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700341 std::priority_queue<DexFileAndClassPair>* queue) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700342 if (dex_elements.Get() == nullptr) {
343 // Nothing to do.
344 return;
345 }
346
Andreas Gampe08883de2016-11-08 13:20:52 -0800347 ArtField* const cookie_field =
348 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Jeff Haof0192c82016-03-28 20:39:50 -0700349 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -0800350 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700351 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
Jeff Haof0192c82016-03-28 20:39:50 -0700352 WellKnownClasses::dalvik_system_DexPathList__Element);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700353 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
354 WellKnownClasses::dalvik_system_DexFile);
Jeff Haof0192c82016-03-28 20:39:50 -0700355
356 // Collect all the dex files.
357 auto GetDexFilesFn = [&] (const DexFile* cp_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700358 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700359 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
360 queue->emplace(cp_dex_file, 0U, true);
361 }
362 return true; // Continue looking.
363 };
364
365 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
366 mirror::Object* element = dex_elements->GetWithoutChecks(i);
367 if (element == nullptr) {
368 continue;
369 }
370
371 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
372
Mathieu Chartier3398c782016-09-30 10:27:43 -0700373 ObjPtr<mirror::Object> dex_file;
Mathieu Chartier0795f232016-09-27 18:43:30 -0700374 if (element_class == element->GetClass()) {
Jeff Haof0192c82016-03-28 20:39:50 -0700375 dex_file = dex_file_field->GetObject(element);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700376 } else if (dexfile_class == element->GetClass()) {
Jeff Haof0192c82016-03-28 20:39:50 -0700377 dex_file = element;
378 } else {
David Sehr709b0702016-10-13 09:12:37 -0700379 LOG(WARNING) << "Unsupported element in dex_elements: "
380 << mirror::Class::PrettyClass(element->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700381 continue;
382 }
383
384 IterateOverJavaDexFile(dex_file, cookie_field, GetDexFilesFn);
385 }
386}
387
Vladimir Marko5c657fe2016-11-03 15:12:29 +0000388static bool AreSharedLibrariesOk(const std::string& shared_libraries,
Jeff Haof0192c82016-03-28 20:39:50 -0700389 std::priority_queue<DexFileAndClassPair>& queue) {
390 if (shared_libraries.empty()) {
391 if (queue.empty()) {
392 // No shared libraries or oat files, as expected.
393 return true;
394 }
395 } else {
396 if (shared_libraries.compare(OatFile::kSpecialSharedLibrary) == 0) {
397 // If we find the special shared library, skip the shared libraries check.
398 return true;
399 }
400 // Shared libraries is a series of dex file paths and their checksums, each separated by '*'.
401 std::vector<std::string> shared_libraries_split;
402 Split(shared_libraries, '*', &shared_libraries_split);
403
404 size_t index = 0;
405 std::priority_queue<DexFileAndClassPair> temp = queue;
406 while (!temp.empty() && index < shared_libraries_split.size() - 1) {
407 DexFileAndClassPair pair(temp.top());
408 const DexFile* dex_file = pair.GetDexFile();
Andreas Gampe4c481a42016-11-03 08:21:59 -0700409 const std::string& dex_filename = dex_file->GetLocation();
Jeff Haob4f52302016-11-14 15:31:06 -0800410 if (dex_filename != shared_libraries_split[index]) {
411 break;
412 }
413 char* end;
414 size_t shared_lib_checksum = strtoul(shared_libraries_split[index + 1].c_str(), &end, 10);
Jeff Haof0192c82016-03-28 20:39:50 -0700415 uint32_t dex_checksum = dex_file->GetLocationChecksum();
Jeff Haob4f52302016-11-14 15:31:06 -0800416 if (*end != '\0' || dex_checksum != shared_lib_checksum) {
Jeff Haof0192c82016-03-28 20:39:50 -0700417 break;
418 }
419 temp.pop();
420 index += 2;
421 }
422
423 // Check is successful if it made it through the queue and all the shared libraries.
424 return temp.empty() && index == shared_libraries_split.size();
425 }
426 return false;
427}
428
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700429// Check for class-def collisions in dex files.
430//
Jeff Haof0192c82016-03-28 20:39:50 -0700431// This first walks the class loader chain, getting all the dex files from the class loader. If
432// the class loader is null or one of the class loaders in the chain is unsupported, we collect
433// dex files from all open non-boot oat files to be safe.
434//
435// This first checks whether the shared libraries are in the expected order and the oat files
436// have the expected checksums. If so, we exit early. Otherwise, we do the collision check.
437//
438// The collision check works by maintaining a heap with one class from each dex file, sorted by the
439// class descriptor. Then a dex-file/class pair is continually removed from the heap and compared
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700440// against the following top element. If the descriptor is the same, it is now checked whether
441// the two elements agree on whether their dex file was from an already-loaded oat-file or the
442// new oat file. Any disagreement indicates a collision.
443bool OatFileManager::HasCollisions(const OatFile* oat_file,
Jeff Haof0192c82016-03-28 20:39:50 -0700444 jobject class_loader,
445 jobjectArray dex_elements,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700446 std::string* error_msg /*out*/) const {
447 DCHECK(oat_file != nullptr);
448 DCHECK(error_msg != nullptr);
Jeff Haof0192c82016-03-28 20:39:50 -0700449
450 std::priority_queue<DexFileAndClassPair> queue;
Jeff Haof0192c82016-03-28 20:39:50 -0700451
452 // Try to get dex files from the given class loader. If the class loader is null, or we do
453 // not support one of the class loaders in the chain, conservatively compare against all
454 // (non-boot) oat files.
455 bool class_loader_ok = false;
456 {
457 ScopedObjectAccess soa(Thread::Current());
458 StackHandleScope<2> hs(Thread::Current());
459 Handle<mirror::ClassLoader> h_class_loader =
Mathieu Chartier0795f232016-09-27 18:43:30 -0700460 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
Jeff Haof0192c82016-03-28 20:39:50 -0700461 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
Mathieu Chartier0795f232016-09-27 18:43:30 -0700462 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
Jeff Haof0192c82016-03-28 20:39:50 -0700463 if (h_class_loader.Get() != nullptr &&
464 GetDexFilesFromClassLoader(soa, h_class_loader.Get(), &queue)) {
465 class_loader_ok = true;
466
467 // In this case, also take into account the dex_elements array, if given. We don't need to
468 // read it otherwise, as we'll compare against all open oat files anyways.
469 GetDexFilesFromDexElementsArray(soa, h_dex_elements, &queue);
470 } else if (h_class_loader.Get() != nullptr) {
471 VLOG(class_linker) << "Something unsupported with "
David Sehr709b0702016-10-13 09:12:37 -0700472 << mirror::Class::PrettyClass(h_class_loader->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700473 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700474 }
475
476 // Dex files are registered late - once a class is actually being loaded. We have to compare
477 // against the open oat files. Take the oat_file_manager_lock_ that protects oat_files_ accesses.
478 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
479
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700480 // Vector that holds the newly opened dex files live, this is done to prevent leaks.
481 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
482
Jeff Haof0192c82016-03-28 20:39:50 -0700483 if (!class_loader_ok) {
484 // Add dex files from already loaded oat files, but skip boot.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700485
Jeff Haof0192c82016-03-28 20:39:50 -0700486 // Clean up the queue.
487 while (!queue.empty()) {
488 queue.pop();
489 }
490
Jeff Haof0192c82016-03-28 20:39:50 -0700491 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
492 // The same OatFile can be loaded multiple times at different addresses. In this case, we don't
493 // need to check both against each other since they would have resolved the same way at compile
494 // time.
495 std::unordered_set<std::string> unique_locations;
496 for (const std::unique_ptr<const OatFile>& loaded_oat_file : oat_files_) {
497 DCHECK_NE(loaded_oat_file.get(), oat_file);
498 const std::string& location = loaded_oat_file->GetLocation();
499 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), loaded_oat_file.get()) ==
500 boot_oat_files.end() && location != oat_file->GetLocation() &&
501 unique_locations.find(location) == unique_locations.end()) {
502 unique_locations.insert(location);
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700503 AddDexFilesFromOat(loaded_oat_file.get(),
504 /*already_loaded*/true,
505 &queue,
506 /*out*/&opened_dex_files);
Jeff Haof0192c82016-03-28 20:39:50 -0700507 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700508 }
509 }
510
Jeff Haof0192c82016-03-28 20:39:50 -0700511 // Exit if shared libraries are ok. Do a full duplicate classes check otherwise.
512 const std::string
513 shared_libraries(oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey));
514 if (AreSharedLibrariesOk(shared_libraries, queue)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700515 return false;
516 }
517
Andreas Gampe1fdbe1b2016-06-10 08:36:20 -0700518 ScopedTrace st("Collision check");
519
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700520 // Add dex files from the oat file to check.
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700521 AddDexFilesFromOat(oat_file, /*already_loaded*/false, &queue, &opened_dex_files);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700522
523 // Now drain the queue.
524 while (!queue.empty()) {
525 // Modifying the top element is only safe if we pop right after.
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700526 DexFileAndClassPair compare_pop(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700527 queue.pop();
528
529 // Compare against the following elements.
530 while (!queue.empty()) {
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700531 DexFileAndClassPair top(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700532
533 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
534 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
535 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
536 *error_msg =
537 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s",
538 compare_pop.GetCachedDescriptor(),
539 compare_pop.GetDexFile()->GetLocation().c_str(),
540 top.GetDexFile()->GetLocation().c_str());
541 return true;
542 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700543 queue.pop();
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700544 AddNext(&top, &queue);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700545 } else {
546 // Something else. Done here.
547 break;
548 }
549 }
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700550 AddNext(&compare_pop, &queue);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700551 }
552
553 return false;
554}
555
556std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
557 const char* dex_location,
558 const char* oat_location,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800559 jobject class_loader,
560 jobjectArray dex_elements,
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700561 const OatFile** out_oat_file,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700562 std::vector<std::string>* error_msgs) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800563 ScopedTrace trace(__FUNCTION__);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700564 CHECK(dex_location != nullptr);
565 CHECK(error_msgs != nullptr);
566
567 // Verify we aren't holding the mutator lock, which could starve GC if we
568 // have to generate or relocate an oat file.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800569 Thread* const self = Thread::Current();
570 Locks::mutator_lock_->AssertNotHeld(self);
571 Runtime* const runtime = Runtime::Current();
Calin Juravleb077e152016-02-18 18:47:37 +0000572
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700573 OatFileAssistant oat_file_assistant(dex_location,
574 oat_location,
575 kRuntimeISA,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800576 !runtime->IsAotCompiler());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700577
578 // Lock the target oat location to avoid races generating and loading the
579 // oat file.
580 std::string error_msg;
581 if (!oat_file_assistant.Lock(/*out*/&error_msg)) {
582 // Don't worry too much if this fails. If it does fail, it's unlikely we
583 // can generate an oat file anyway.
584 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
585 }
586
587 const OatFile* source_oat_file = nullptr;
588
Richard Uhler01be6812016-05-17 10:34:52 -0700589 if (!oat_file_assistant.IsUpToDate()) {
590 // Update the oat file on disk if we can, based on the --compiler-filter
591 // option derived from the current runtime options.
592 // This may fail, but that's okay. Best effort is all that matters here.
Richard Uhlerd1472a22016-04-15 15:18:56 -0700593 switch (oat_file_assistant.MakeUpToDate(/*profile_changed*/false, /*out*/ &error_msg)) {
Richard Uhler01be6812016-05-17 10:34:52 -0700594 case OatFileAssistant::kUpdateFailed:
595 LOG(WARNING) << error_msg;
596 break;
Richard Uhler1e860612016-03-30 12:17:55 -0700597
Richard Uhler01be6812016-05-17 10:34:52 -0700598 case OatFileAssistant::kUpdateNotAttempted:
599 // Avoid spamming the logs if we decided not to attempt making the oat
600 // file up to date.
601 VLOG(oat) << error_msg;
602 break;
Richard Uhler1e860612016-03-30 12:17:55 -0700603
Richard Uhler01be6812016-05-17 10:34:52 -0700604 case OatFileAssistant::kUpdateSucceeded:
605 // Nothing to do.
606 break;
607 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700608 }
609
610 // Get the oat file on disk.
611 std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800612
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700613 if (oat_file != nullptr) {
614 // Take the file only if it has no collisions, or we must take it because of preopting.
Jeff Haof0192c82016-03-28 20:39:50 -0700615 bool accept_oat_file =
616 !HasCollisions(oat_file.get(), class_loader, dex_elements, /*out*/ &error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700617 if (!accept_oat_file) {
618 // Failed the collision check. Print warning.
619 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
620 LOG(WARNING) << "Found duplicate classes, falling back to interpreter mode for "
621 << dex_location;
622 } else {
623 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
624 " load classes for " << dex_location;
625 }
626 LOG(WARNING) << error_msg;
627
628 // However, if the app was part of /system and preopted, there is no original dex file
629 // available. In that case grudgingly accept the oat file.
Richard Uhler76f5cb62016-04-04 13:30:16 -0700630 if (!oat_file_assistant.HasOriginalDexFiles()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700631 accept_oat_file = true;
632 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
633 << "Allow oat file use. This is potentially dangerous.";
634 }
635 }
636
637 if (accept_oat_file) {
638 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
639 source_oat_file = RegisterOatFile(std::move(oat_file));
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700640 *out_oat_file = source_oat_file;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700641 }
642 }
643
644 std::vector<std::unique_ptr<const DexFile>> dex_files;
645
646 // Load the dex files from the oat file.
647 if (source_oat_file != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800648 bool added_image_space = false;
649 if (source_oat_file->IsExecutable()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700650 std::unique_ptr<gc::space::ImageSpace> image_space =
651 kEnableAppImage ? oat_file_assistant.OpenImageSpace(source_oat_file) : nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800652 if (image_space != nullptr) {
653 ScopedObjectAccess soa(self);
654 StackHandleScope<1> hs(self);
655 Handle<mirror::ClassLoader> h_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700656 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800657 // Can not load app image without class loader.
658 if (h_loader.Get() != nullptr) {
659 std::string temp_error_msg;
660 // Add image space has a race condition since other threads could be reading from the
661 // spaces array.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800662 {
663 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800664 gc::ScopedGCCriticalSection gcs(self,
665 gc::kGcCauseAddRemoveAppImageSpace,
666 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800667 ScopedSuspendAll ssa("Add image space");
668 runtime->GetHeap()->AddSpace(image_space.get());
669 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800670 {
671 ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
672 added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
673 h_loader,
674 dex_elements,
675 dex_location,
676 /*out*/&dex_files,
677 /*out*/&temp_error_msg);
678 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800679 if (added_image_space) {
Mathieu Chartierbd064ea2016-02-11 16:27:18 -0800680 // Successfully added image space to heap, release the map so that it does not get
681 // freed.
682 image_space.release();
683 } else {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800684 LOG(INFO) << "Failed to add image file " << temp_error_msg;
685 dex_files.clear();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800686 {
687 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800688 gc::ScopedGCCriticalSection gcs(self,
689 gc::kGcCauseAddRemoveAppImageSpace,
690 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800691 ScopedSuspendAll ssa("Remove image space");
692 runtime->GetHeap()->RemoveSpace(image_space.get());
693 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800694 // Non-fatal, don't update error_msg.
695 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800696 }
697 }
698 }
699 if (!added_image_space) {
700 DCHECK(dex_files.empty());
701 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
702 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700703 if (dex_files.empty()) {
704 error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
705 }
706 }
707
708 // Fall back to running out of the original dex file if we couldn't load any
709 // dex_files from the oat file.
710 if (dex_files.empty()) {
711 if (oat_file_assistant.HasOriginalDexFiles()) {
712 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700713 static constexpr bool kVerifyChecksum = true;
714 if (!DexFile::Open(
715 dex_location, dex_location, kVerifyChecksum, /*out*/ &error_msg, &dex_files)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700716 LOG(WARNING) << error_msg;
Alex Light3045b662016-04-20 14:26:34 -0700717 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
718 + " because: " + error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700719 }
720 } else {
721 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
722 }
723 } else {
724 error_msgs->push_back("No original dex files found for dex location "
725 + std::string(dex_location));
726 }
727 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000728
729 // TODO(calin): Consider optimizing this knowing that is useless to record the
730 // use of fully compiled apks.
731 Runtime::Current()->NotifyDexLoaded(dex_location);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700732 return dex_files;
733}
734
Nicolas Geoffray04680f32016-03-17 11:56:54 +0000735void OatFileManager::DumpForSigQuit(std::ostream& os) {
736 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
737 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
738 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
739 if (ContainsElement(boot_oat_files, oat_file.get())) {
740 continue;
741 }
Andreas Gampe29d38e72016-03-23 15:31:51 +0000742 os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
Nicolas Geoffray04680f32016-03-17 11:56:54 +0000743 }
744}
745
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700746} // namespace art