blob: 5641459f419e09a89fd85e65fc55b155101f8859 [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"
Andreas Gampe08883de2016-11-08 13:20:52 -080031#include "jni_internal.h"
Mathieu Chartierfbc31082016-01-24 11:59:56 -080032#include "mirror/class_loader.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070033#include "oat_file_assistant.h"
Mathieu Chartier3398c782016-09-30 10:27:43 -070034#include "obj_ptr-inl.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070035#include "scoped_thread_state_change-inl.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070036#include "thread-inl.h"
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -080037#include "thread_list.h"
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070038
39namespace art {
40
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
Calin Juravle0b791272016-04-18 16:38:27 +010072const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
73 const std::string& dex_base_location) const {
74 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
75 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
76 const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
77 for (const OatDexFile* oat_dex_file : oat_dex_files) {
78 if (DexFile::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
79 return oat_file.get();
80 }
81 }
82 }
83 return nullptr;
84}
85
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070086const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
87 const {
88 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Mathieu Chartiere58991b2015-10-13 07:59:34 -070089 return FindOpenedOatFileFromOatLocationLocked(oat_location);
90}
91
92const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
93 const std::string& oat_location) const {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -070094 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
95 if (oat_file->GetLocation() == oat_location) {
96 return oat_file.get();
97 }
98 }
99 return nullptr;
100}
101
Jeff Haodcdc85b2015-12-04 14:06:18 -0800102std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
103 std::vector<const OatFile*> oat_files;
104 std::vector<gc::space::ImageSpace*> image_spaces =
105 Runtime::Current()->GetHeap()->GetBootImageSpaces();
106 for (gc::space::ImageSpace* image_space : image_spaces) {
107 oat_files.push_back(image_space->GetOatFile());
108 }
109 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700110}
111
112const OatFile* OatFileManager::GetPrimaryOatFile() const {
113 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
Jeff Haodcdc85b2015-12-04 14:06:18 -0800114 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
115 if (!boot_oat_files.empty()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700116 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
Jeff Haodcdc85b2015-12-04 14:06:18 -0800117 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), oat_file.get()) ==
118 boot_oat_files.end()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700119 return oat_file.get();
120 }
121 }
122 }
123 return nullptr;
124}
125
126OatFileManager::~OatFileManager() {
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700127 // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
128 // UnRegisterOatFileLocation.
129 oat_files_.clear();
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700130}
131
Jeff Haodcdc85b2015-12-04 14:06:18 -0800132std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
133 std::vector<gc::space::ImageSpace*> spaces) {
134 std::vector<const OatFile*> oat_files;
135 for (gc::space::ImageSpace* space : spaces) {
136 oat_files.push_back(RegisterOatFile(space->ReleaseOatFile()));
137 }
138 return oat_files;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700139}
140
141class DexFileAndClassPair : ValueObject {
142 public:
143 DexFileAndClassPair(const DexFile* dex_file, size_t current_class_index, bool from_loaded_oat)
144 : cached_descriptor_(GetClassDescriptor(dex_file, current_class_index)),
145 dex_file_(dex_file),
146 current_class_index_(current_class_index),
147 from_loaded_oat_(from_loaded_oat) {}
148
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700149 DexFileAndClassPair(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700150
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700151 DexFileAndClassPair& operator=(const DexFileAndClassPair& rhs) = default;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700152
153 const char* GetCachedDescriptor() const {
154 return cached_descriptor_;
155 }
156
157 bool operator<(const DexFileAndClassPair& rhs) const {
158 const int cmp = strcmp(cached_descriptor_, rhs.cached_descriptor_);
159 if (cmp != 0) {
160 // Note that the order must be reversed. We want to iterate over the classes in dex files.
161 // They are sorted lexicographically. Thus, the priority-queue must be a min-queue.
162 return cmp > 0;
163 }
164 return dex_file_ < rhs.dex_file_;
165 }
166
167 bool DexFileHasMoreClasses() const {
168 return current_class_index_ + 1 < dex_file_->NumClassDefs();
169 }
170
171 void Next() {
172 ++current_class_index_;
Jeff Haof0192c82016-03-28 20:39:50 -0700173 cached_descriptor_ = GetClassDescriptor(dex_file_, current_class_index_);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700174 }
175
176 size_t GetCurrentClassIndex() const {
177 return current_class_index_;
178 }
179
180 bool FromLoadedOat() const {
181 return from_loaded_oat_;
182 }
183
184 const DexFile* GetDexFile() const {
Jeff Haof0192c82016-03-28 20:39:50 -0700185 return dex_file_;
186 }
187
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700188 private:
189 static const char* GetClassDescriptor(const DexFile* dex_file, size_t index) {
190 DCHECK(IsUint<16>(index));
191 const DexFile::ClassDef& class_def = dex_file->GetClassDef(static_cast<uint16_t>(index));
192 return dex_file->StringByTypeIdx(class_def.class_idx_);
193 }
194
195 const char* cached_descriptor_;
Jeff Haof0192c82016-03-28 20:39:50 -0700196 const DexFile* dex_file_;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700197 size_t current_class_index_;
198 bool from_loaded_oat_; // We only need to compare mismatches between what we load now
199 // and what was loaded before. Any old duplicates must have been
200 // OK, and any new "internal" duplicates are as well (they must
201 // be from multidex, which resolves correctly).
202};
203
204static void AddDexFilesFromOat(const OatFile* oat_file,
205 bool already_loaded,
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700206 /*out*/std::priority_queue<DexFileAndClassPair>* heap,
207 std::vector<std::unique_ptr<const DexFile>>* opened_dex_files) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700208 for (const OatDexFile* oat_dex_file : oat_file->GetOatDexFiles()) {
209 std::string error;
210 std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error);
211 if (dex_file == nullptr) {
212 LOG(WARNING) << "Could not create dex file from oat file: " << error;
213 } else if (dex_file->NumClassDefs() > 0U) {
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700214 heap->emplace(dex_file.get(), /*current_class_index*/0U, already_loaded);
215 opened_dex_files->push_back(std::move(dex_file));
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700216 }
217 }
218}
219
220static void AddNext(/*inout*/DexFileAndClassPair* original,
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700221 /*inout*/std::priority_queue<DexFileAndClassPair>* heap) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700222 if (original->DexFileHasMoreClasses()) {
223 original->Next();
224 heap->push(std::move(*original));
Jeff Haof0192c82016-03-28 20:39:50 -0700225 }
226}
227
Andreas Gampeca620d72016-11-08 08:09:33 -0800228template <typename T>
Mathieu Chartier3398c782016-09-30 10:27:43 -0700229static void IterateOverJavaDexFile(ObjPtr<mirror::Object> dex_file,
Jeff Haof0192c82016-03-28 20:39:50 -0700230 ArtField* const cookie_field,
Andreas Gampeca620d72016-11-08 08:09:33 -0800231 const T& fn)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700232 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700233 if (dex_file != nullptr) {
234 mirror::LongArray* long_array = cookie_field->GetObject(dex_file)->AsLongArray();
235 if (long_array == nullptr) {
236 // This should never happen so log a warning.
237 LOG(WARNING) << "Null DexFile::mCookie";
238 return;
239 }
240 int32_t long_array_size = long_array->GetLength();
241 // Start from 1 to skip the oat file.
242 for (int32_t j = 1; j < long_array_size; ++j) {
243 const DexFile* cp_dex_file = reinterpret_cast<const DexFile*>(static_cast<uintptr_t>(
244 long_array->GetWithoutChecks(j)));
245 if (!fn(cp_dex_file)) {
246 return;
247 }
248 }
249 }
250}
251
Andreas Gampeca620d72016-11-08 08:09:33 -0800252template <typename T>
Jeff Haof0192c82016-03-28 20:39:50 -0700253static void IterateOverPathClassLoader(
Jeff Haof0192c82016-03-28 20:39:50 -0700254 Handle<mirror::ClassLoader> class_loader,
255 MutableHandle<mirror::ObjectArray<mirror::Object>> dex_elements,
Andreas Gampeca620d72016-11-08 08:09:33 -0800256 const T& fn) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700257 // Handle this step.
258 // Handle as if this is the child PathClassLoader.
259 // The class loader is a PathClassLoader which inherits from BaseDexClassLoader.
260 // We need to get the DexPathList and loop through it.
Andreas Gampe08883de2016-11-08 13:20:52 -0800261 ArtField* const cookie_field =
262 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Jeff Haof0192c82016-03-28 20:39:50 -0700263 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -0800264 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier3398c782016-09-30 10:27:43 -0700265 ObjPtr<mirror::Object> dex_path_list =
Andreas Gampe08883de2016-11-08 13:20:52 -0800266 jni::DecodeArtField(WellKnownClasses::dalvik_system_BaseDexClassLoader_pathList)->
267 GetObject(class_loader.Get());
Jeff Haof0192c82016-03-28 20:39:50 -0700268 if (dex_path_list != nullptr && dex_file_field != nullptr && cookie_field != nullptr) {
269 // DexPathList has an array dexElements of Elements[] which each contain a dex file.
Mathieu Chartier3398c782016-09-30 10:27:43 -0700270 ObjPtr<mirror::Object> dex_elements_obj =
Andreas Gampe08883de2016-11-08 13:20:52 -0800271 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList_dexElements)->
272 GetObject(dex_path_list);
Jeff Haof0192c82016-03-28 20:39:50 -0700273 // Loop through each dalvik.system.DexPathList$Element's dalvik.system.DexFile and look
274 // at the mCookie which is a DexFile vector.
275 if (dex_elements_obj != nullptr) {
276 dex_elements.Assign(dex_elements_obj->AsObjectArray<mirror::Object>());
277 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
278 mirror::Object* element = dex_elements->GetWithoutChecks(i);
279 if (element == nullptr) {
280 // Should never happen, fall back to java code to throw a NPE.
281 break;
282 }
Mathieu Chartier3398c782016-09-30 10:27:43 -0700283 ObjPtr<mirror::Object> dex_file = dex_file_field->GetObject(element);
Jeff Haof0192c82016-03-28 20:39:50 -0700284 IterateOverJavaDexFile(dex_file, cookie_field, fn);
285 }
286 }
287 }
288}
289
290static bool GetDexFilesFromClassLoader(
291 ScopedObjectAccessAlreadyRunnable& soa,
292 mirror::ClassLoader* class_loader,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700293 std::priority_queue<DexFileAndClassPair>* queue) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700294 if (ClassLinker::IsBootClassLoader(soa, class_loader)) {
295 // The boot class loader. We don't load any of these files, as we know we compiled against
296 // them correctly.
297 return true;
298 }
299
300 // Unsupported class-loader?
Mathieu Chartier0795f232016-09-27 18:43:30 -0700301 if (soa.Decode<mirror::Class>(WellKnownClasses::dalvik_system_PathClassLoader) !=
302 class_loader->GetClass()) {
David Sehr709b0702016-10-13 09:12:37 -0700303 VLOG(class_linker) << "Unsupported class-loader "
304 << mirror::Class::PrettyClass(class_loader->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700305 return false;
306 }
307
308 bool recursive_result = GetDexFilesFromClassLoader(soa, class_loader->GetParent(), queue);
309 if (!recursive_result) {
310 // Something wrong up the chain.
311 return false;
312 }
313
314 // Collect all the dex files.
315 auto GetDexFilesFn = [&] (const DexFile* cp_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700316 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700317 if (cp_dex_file->NumClassDefs() > 0) {
318 queue->emplace(cp_dex_file, 0U, true);
319 }
320 return true; // Continue looking.
321 };
322
323 // Handle for dex-cache-element.
324 StackHandleScope<3> hs(soa.Self());
325 MutableHandle<mirror::ObjectArray<mirror::Object>> dex_elements(
326 hs.NewHandle<mirror::ObjectArray<mirror::Object>>(nullptr));
327 Handle<mirror::ClassLoader> h_class_loader(hs.NewHandle(class_loader));
328
Andreas Gampe08883de2016-11-08 13:20:52 -0800329 IterateOverPathClassLoader(h_class_loader, dex_elements, GetDexFilesFn);
Jeff Haof0192c82016-03-28 20:39:50 -0700330
331 return true;
332}
333
334static void GetDexFilesFromDexElementsArray(
335 ScopedObjectAccessAlreadyRunnable& soa,
336 Handle<mirror::ObjectArray<mirror::Object>> dex_elements,
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700337 std::priority_queue<DexFileAndClassPair>* queue) REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700338 if (dex_elements.Get() == nullptr) {
339 // Nothing to do.
340 return;
341 }
342
Andreas Gampe08883de2016-11-08 13:20:52 -0800343 ArtField* const cookie_field =
344 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexFile_cookie);
Jeff Haof0192c82016-03-28 20:39:50 -0700345 ArtField* const dex_file_field =
Andreas Gampe08883de2016-11-08 13:20:52 -0800346 jni::DecodeArtField(WellKnownClasses::dalvik_system_DexPathList__Element_dexFile);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700347 ObjPtr<mirror::Class> const element_class = soa.Decode<mirror::Class>(
Jeff Haof0192c82016-03-28 20:39:50 -0700348 WellKnownClasses::dalvik_system_DexPathList__Element);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700349 ObjPtr<mirror::Class> const dexfile_class = soa.Decode<mirror::Class>(
350 WellKnownClasses::dalvik_system_DexFile);
Jeff Haof0192c82016-03-28 20:39:50 -0700351
352 // Collect all the dex files.
353 auto GetDexFilesFn = [&] (const DexFile* cp_dex_file)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700354 REQUIRES_SHARED(Locks::mutator_lock_) {
Jeff Haof0192c82016-03-28 20:39:50 -0700355 if (cp_dex_file != nullptr && cp_dex_file->NumClassDefs() > 0) {
356 queue->emplace(cp_dex_file, 0U, true);
357 }
358 return true; // Continue looking.
359 };
360
361 for (int32_t i = 0; i < dex_elements->GetLength(); ++i) {
362 mirror::Object* element = dex_elements->GetWithoutChecks(i);
363 if (element == nullptr) {
364 continue;
365 }
366
367 // We support this being dalvik.system.DexPathList$Element and dalvik.system.DexFile.
368
Mathieu Chartier3398c782016-09-30 10:27:43 -0700369 ObjPtr<mirror::Object> dex_file;
Mathieu Chartier0795f232016-09-27 18:43:30 -0700370 if (element_class == element->GetClass()) {
Jeff Haof0192c82016-03-28 20:39:50 -0700371 dex_file = dex_file_field->GetObject(element);
Mathieu Chartier0795f232016-09-27 18:43:30 -0700372 } else if (dexfile_class == element->GetClass()) {
Jeff Haof0192c82016-03-28 20:39:50 -0700373 dex_file = element;
374 } else {
David Sehr709b0702016-10-13 09:12:37 -0700375 LOG(WARNING) << "Unsupported element in dex_elements: "
376 << mirror::Class::PrettyClass(element->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700377 continue;
378 }
379
380 IterateOverJavaDexFile(dex_file, cookie_field, GetDexFilesFn);
381 }
382}
383
Vladimir Marko5c657fe2016-11-03 15:12:29 +0000384static bool AreSharedLibrariesOk(const std::string& shared_libraries,
Jeff Haof0192c82016-03-28 20:39:50 -0700385 std::priority_queue<DexFileAndClassPair>& queue) {
386 if (shared_libraries.empty()) {
387 if (queue.empty()) {
388 // No shared libraries or oat files, as expected.
389 return true;
390 }
391 } else {
392 if (shared_libraries.compare(OatFile::kSpecialSharedLibrary) == 0) {
393 // If we find the special shared library, skip the shared libraries check.
394 return true;
395 }
396 // Shared libraries is a series of dex file paths and their checksums, each separated by '*'.
397 std::vector<std::string> shared_libraries_split;
398 Split(shared_libraries, '*', &shared_libraries_split);
399
400 size_t index = 0;
401 std::priority_queue<DexFileAndClassPair> temp = queue;
402 while (!temp.empty() && index < shared_libraries_split.size() - 1) {
403 DexFileAndClassPair pair(temp.top());
404 const DexFile* dex_file = pair.GetDexFile();
Andreas Gampe4c481a42016-11-03 08:21:59 -0700405 const std::string& dex_filename = dex_file->GetLocation();
Jeff Haob4f52302016-11-14 15:31:06 -0800406 if (dex_filename != shared_libraries_split[index]) {
407 break;
408 }
409 char* end;
410 size_t shared_lib_checksum = strtoul(shared_libraries_split[index + 1].c_str(), &end, 10);
Jeff Haof0192c82016-03-28 20:39:50 -0700411 uint32_t dex_checksum = dex_file->GetLocationChecksum();
Jeff Haob4f52302016-11-14 15:31:06 -0800412 if (*end != '\0' || dex_checksum != shared_lib_checksum) {
Jeff Haof0192c82016-03-28 20:39:50 -0700413 break;
414 }
415 temp.pop();
416 index += 2;
417 }
418
419 // Check is successful if it made it through the queue and all the shared libraries.
420 return temp.empty() && index == shared_libraries_split.size();
421 }
422 return false;
423}
424
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700425// Check for class-def collisions in dex files.
426//
Jeff Haof0192c82016-03-28 20:39:50 -0700427// This first walks the class loader chain, getting all the dex files from the class loader. If
428// the class loader is null or one of the class loaders in the chain is unsupported, we collect
429// dex files from all open non-boot oat files to be safe.
430//
431// This first checks whether the shared libraries are in the expected order and the oat files
432// have the expected checksums. If so, we exit early. Otherwise, we do the collision check.
433//
434// The collision check works by maintaining a heap with one class from each dex file, sorted by the
435// class descriptor. Then a dex-file/class pair is continually removed from the heap and compared
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700436// against the following top element. If the descriptor is the same, it is now checked whether
437// the two elements agree on whether their dex file was from an already-loaded oat-file or the
438// new oat file. Any disagreement indicates a collision.
439bool OatFileManager::HasCollisions(const OatFile* oat_file,
Jeff Haof0192c82016-03-28 20:39:50 -0700440 jobject class_loader,
441 jobjectArray dex_elements,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700442 std::string* error_msg /*out*/) const {
443 DCHECK(oat_file != nullptr);
444 DCHECK(error_msg != nullptr);
Jeff Haof0192c82016-03-28 20:39:50 -0700445
446 std::priority_queue<DexFileAndClassPair> queue;
Jeff Haof0192c82016-03-28 20:39:50 -0700447
448 // Try to get dex files from the given class loader. If the class loader is null, or we do
449 // not support one of the class loaders in the chain, conservatively compare against all
450 // (non-boot) oat files.
451 bool class_loader_ok = false;
452 {
453 ScopedObjectAccess soa(Thread::Current());
454 StackHandleScope<2> hs(Thread::Current());
455 Handle<mirror::ClassLoader> h_class_loader =
Mathieu Chartier0795f232016-09-27 18:43:30 -0700456 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader));
Jeff Haof0192c82016-03-28 20:39:50 -0700457 Handle<mirror::ObjectArray<mirror::Object>> h_dex_elements =
Mathieu Chartier0795f232016-09-27 18:43:30 -0700458 hs.NewHandle(soa.Decode<mirror::ObjectArray<mirror::Object>>(dex_elements));
Jeff Haof0192c82016-03-28 20:39:50 -0700459 if (h_class_loader.Get() != nullptr &&
460 GetDexFilesFromClassLoader(soa, h_class_loader.Get(), &queue)) {
461 class_loader_ok = true;
462
463 // In this case, also take into account the dex_elements array, if given. We don't need to
464 // read it otherwise, as we'll compare against all open oat files anyways.
465 GetDexFilesFromDexElementsArray(soa, h_dex_elements, &queue);
466 } else if (h_class_loader.Get() != nullptr) {
467 VLOG(class_linker) << "Something unsupported with "
David Sehr709b0702016-10-13 09:12:37 -0700468 << mirror::Class::PrettyClass(h_class_loader->GetClass());
Jeff Haof0192c82016-03-28 20:39:50 -0700469 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700470 }
471
472 // Dex files are registered late - once a class is actually being loaded. We have to compare
473 // against the open oat files. Take the oat_file_manager_lock_ that protects oat_files_ accesses.
474 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
475
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700476 // Vector that holds the newly opened dex files live, this is done to prevent leaks.
477 std::vector<std::unique_ptr<const DexFile>> opened_dex_files;
478
Jeff Haof0192c82016-03-28 20:39:50 -0700479 if (!class_loader_ok) {
480 // Add dex files from already loaded oat files, but skip boot.
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700481
Jeff Haof0192c82016-03-28 20:39:50 -0700482 // Clean up the queue.
483 while (!queue.empty()) {
484 queue.pop();
485 }
486
Jeff Haof0192c82016-03-28 20:39:50 -0700487 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
488 // The same OatFile can be loaded multiple times at different addresses. In this case, we don't
489 // need to check both against each other since they would have resolved the same way at compile
490 // time.
491 std::unordered_set<std::string> unique_locations;
492 for (const std::unique_ptr<const OatFile>& loaded_oat_file : oat_files_) {
493 DCHECK_NE(loaded_oat_file.get(), oat_file);
494 const std::string& location = loaded_oat_file->GetLocation();
495 if (std::find(boot_oat_files.begin(), boot_oat_files.end(), loaded_oat_file.get()) ==
496 boot_oat_files.end() && location != oat_file->GetLocation() &&
497 unique_locations.find(location) == unique_locations.end()) {
498 unique_locations.insert(location);
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700499 AddDexFilesFromOat(loaded_oat_file.get(),
500 /*already_loaded*/true,
501 &queue,
502 /*out*/&opened_dex_files);
Jeff Haof0192c82016-03-28 20:39:50 -0700503 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700504 }
505 }
506
Jeff Haof0192c82016-03-28 20:39:50 -0700507 // Exit if shared libraries are ok. Do a full duplicate classes check otherwise.
508 const std::string
509 shared_libraries(oat_file->GetOatHeader().GetStoreValueByKey(OatHeader::kClassPathKey));
510 if (AreSharedLibrariesOk(shared_libraries, queue)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700511 return false;
512 }
513
Andreas Gampe1fdbe1b2016-06-10 08:36:20 -0700514 ScopedTrace st("Collision check");
515
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700516 // Add dex files from the oat file to check.
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700517 AddDexFilesFromOat(oat_file, /*already_loaded*/false, &queue, &opened_dex_files);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700518
519 // Now drain the queue.
520 while (!queue.empty()) {
521 // Modifying the top element is only safe if we pop right after.
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700522 DexFileAndClassPair compare_pop(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700523 queue.pop();
524
525 // Compare against the following elements.
526 while (!queue.empty()) {
Mathieu Chartier80b37b72015-10-12 18:13:39 -0700527 DexFileAndClassPair top(queue.top());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700528
529 if (strcmp(compare_pop.GetCachedDescriptor(), top.GetCachedDescriptor()) == 0) {
530 // Same descriptor. Check whether it's crossing old-oat-files to new-oat-files.
531 if (compare_pop.FromLoadedOat() != top.FromLoadedOat()) {
532 *error_msg =
533 StringPrintf("Found duplicated class when checking oat files: '%s' in %s and %s",
534 compare_pop.GetCachedDescriptor(),
535 compare_pop.GetDexFile()->GetLocation().c_str(),
536 top.GetDexFile()->GetLocation().c_str());
537 return true;
538 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700539 queue.pop();
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700540 AddNext(&top, &queue);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700541 } else {
542 // Something else. Done here.
543 break;
544 }
545 }
Mathieu Chartier14d7b3e2016-06-09 16:18:04 -0700546 AddNext(&compare_pop, &queue);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700547 }
548
549 return false;
550}
551
552std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
553 const char* dex_location,
554 const char* oat_location,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800555 jobject class_loader,
556 jobjectArray dex_elements,
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700557 const OatFile** out_oat_file,
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700558 std::vector<std::string>* error_msgs) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800559 ScopedTrace trace(__FUNCTION__);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700560 CHECK(dex_location != nullptr);
561 CHECK(error_msgs != nullptr);
562
563 // Verify we aren't holding the mutator lock, which could starve GC if we
564 // have to generate or relocate an oat file.
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800565 Thread* const self = Thread::Current();
566 Locks::mutator_lock_->AssertNotHeld(self);
567 Runtime* const runtime = Runtime::Current();
Calin Juravleb077e152016-02-18 18:47:37 +0000568
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700569 OatFileAssistant oat_file_assistant(dex_location,
570 oat_location,
571 kRuntimeISA,
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800572 !runtime->IsAotCompiler());
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700573
574 // Lock the target oat location to avoid races generating and loading the
575 // oat file.
576 std::string error_msg;
577 if (!oat_file_assistant.Lock(/*out*/&error_msg)) {
578 // Don't worry too much if this fails. If it does fail, it's unlikely we
579 // can generate an oat file anyway.
580 VLOG(class_linker) << "OatFileAssistant::Lock: " << error_msg;
581 }
582
583 const OatFile* source_oat_file = nullptr;
584
Richard Uhler01be6812016-05-17 10:34:52 -0700585 if (!oat_file_assistant.IsUpToDate()) {
586 // Update the oat file on disk if we can, based on the --compiler-filter
587 // option derived from the current runtime options.
588 // This may fail, but that's okay. Best effort is all that matters here.
Richard Uhlerd1472a22016-04-15 15:18:56 -0700589 switch (oat_file_assistant.MakeUpToDate(/*profile_changed*/false, /*out*/ &error_msg)) {
Richard Uhler01be6812016-05-17 10:34:52 -0700590 case OatFileAssistant::kUpdateFailed:
591 LOG(WARNING) << error_msg;
592 break;
Richard Uhler1e860612016-03-30 12:17:55 -0700593
Richard Uhler01be6812016-05-17 10:34:52 -0700594 case OatFileAssistant::kUpdateNotAttempted:
595 // Avoid spamming the logs if we decided not to attempt making the oat
596 // file up to date.
597 VLOG(oat) << error_msg;
598 break;
Richard Uhler1e860612016-03-30 12:17:55 -0700599
Richard Uhler01be6812016-05-17 10:34:52 -0700600 case OatFileAssistant::kUpdateSucceeded:
601 // Nothing to do.
602 break;
603 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700604 }
605
606 // Get the oat file on disk.
607 std::unique_ptr<const OatFile> oat_file(oat_file_assistant.GetBestOatFile().release());
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800608
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700609 if (oat_file != nullptr) {
610 // Take the file only if it has no collisions, or we must take it because of preopting.
Jeff Haof0192c82016-03-28 20:39:50 -0700611 bool accept_oat_file =
612 !HasCollisions(oat_file.get(), class_loader, dex_elements, /*out*/ &error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700613 if (!accept_oat_file) {
614 // Failed the collision check. Print warning.
615 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
616 LOG(WARNING) << "Found duplicate classes, falling back to interpreter mode for "
617 << dex_location;
618 } else {
619 LOG(WARNING) << "Found duplicate classes, dex-file-fallback disabled, will be failing to "
620 " load classes for " << dex_location;
621 }
622 LOG(WARNING) << error_msg;
623
624 // However, if the app was part of /system and preopted, there is no original dex file
625 // available. In that case grudgingly accept the oat file.
Richard Uhler76f5cb62016-04-04 13:30:16 -0700626 if (!oat_file_assistant.HasOriginalDexFiles()) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700627 accept_oat_file = true;
628 LOG(WARNING) << "Dex location " << dex_location << " does not seem to include dex file. "
629 << "Allow oat file use. This is potentially dangerous.";
630 }
631 }
632
633 if (accept_oat_file) {
634 VLOG(class_linker) << "Registering " << oat_file->GetLocation();
635 source_oat_file = RegisterOatFile(std::move(oat_file));
Mathieu Chartiere58991b2015-10-13 07:59:34 -0700636 *out_oat_file = source_oat_file;
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700637 }
638 }
639
640 std::vector<std::unique_ptr<const DexFile>> dex_files;
641
642 // Load the dex files from the oat file.
643 if (source_oat_file != nullptr) {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800644 bool added_image_space = false;
645 if (source_oat_file->IsExecutable()) {
Andreas Gampea463b6a2016-08-12 21:53:32 -0700646 std::unique_ptr<gc::space::ImageSpace> image_space =
647 kEnableAppImage ? oat_file_assistant.OpenImageSpace(source_oat_file) : nullptr;
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800648 if (image_space != nullptr) {
649 ScopedObjectAccess soa(self);
650 StackHandleScope<1> hs(self);
651 Handle<mirror::ClassLoader> h_loader(
Mathieu Chartier0795f232016-09-27 18:43:30 -0700652 hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800653 // Can not load app image without class loader.
654 if (h_loader.Get() != nullptr) {
655 std::string temp_error_msg;
656 // Add image space has a race condition since other threads could be reading from the
657 // spaces array.
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800658 {
659 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800660 gc::ScopedGCCriticalSection gcs(self,
661 gc::kGcCauseAddRemoveAppImageSpace,
662 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800663 ScopedSuspendAll ssa("Add image space");
664 runtime->GetHeap()->AddSpace(image_space.get());
665 }
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800666 {
667 ScopedTrace trace2(StringPrintf("Adding image space for location %s", dex_location));
668 added_image_space = runtime->GetClassLinker()->AddImageSpace(image_space.get(),
669 h_loader,
670 dex_elements,
671 dex_location,
672 /*out*/&dex_files,
673 /*out*/&temp_error_msg);
674 }
Mathieu Chartiera6e81ed2016-02-25 13:52:10 -0800675 if (added_image_space) {
Mathieu Chartierbd064ea2016-02-11 16:27:18 -0800676 // Successfully added image space to heap, release the map so that it does not get
677 // freed.
678 image_space.release();
679 } else {
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800680 LOG(INFO) << "Failed to add image file " << temp_error_msg;
681 dex_files.clear();
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800682 {
683 ScopedThreadSuspension sts(self, kSuspended);
Mathieu Chartier61d2b2d2016-02-04 13:31:46 -0800684 gc::ScopedGCCriticalSection gcs(self,
685 gc::kGcCauseAddRemoveAppImageSpace,
686 gc::kCollectorTypeAddRemoveAppImageSpace);
Mathieu Chartiera9d82fe2016-01-25 20:06:11 -0800687 ScopedSuspendAll ssa("Remove image space");
688 runtime->GetHeap()->RemoveSpace(image_space.get());
689 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800690 // Non-fatal, don't update error_msg.
691 }
Mathieu Chartierfbc31082016-01-24 11:59:56 -0800692 }
693 }
694 }
695 if (!added_image_space) {
696 DCHECK(dex_files.empty());
697 dex_files = oat_file_assistant.LoadDexFiles(*source_oat_file, dex_location);
698 }
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700699 if (dex_files.empty()) {
700 error_msgs->push_back("Failed to open dex files from " + source_oat_file->GetLocation());
701 }
702 }
703
704 // Fall back to running out of the original dex file if we couldn't load any
705 // dex_files from the oat file.
706 if (dex_files.empty()) {
707 if (oat_file_assistant.HasOriginalDexFiles()) {
708 if (Runtime::Current()->IsDexFileFallbackEnabled()) {
Aart Bik37d6a3b2016-06-21 18:30:10 -0700709 static constexpr bool kVerifyChecksum = true;
710 if (!DexFile::Open(
711 dex_location, dex_location, kVerifyChecksum, /*out*/ &error_msg, &dex_files)) {
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700712 LOG(WARNING) << error_msg;
Alex Light3045b662016-04-20 14:26:34 -0700713 error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
714 + " because: " + error_msg);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700715 }
716 } else {
717 error_msgs->push_back("Fallback mode disabled, skipping dex files.");
718 }
719 } else {
720 error_msgs->push_back("No original dex files found for dex location "
721 + std::string(dex_location));
722 }
723 }
Calin Juravlec90bc922016-02-24 10:13:09 +0000724
725 // TODO(calin): Consider optimizing this knowing that is useless to record the
726 // use of fully compiled apks.
727 Runtime::Current()->NotifyDexLoaded(dex_location);
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700728 return dex_files;
729}
730
Nicolas Geoffray04680f32016-03-17 11:56:54 +0000731void OatFileManager::DumpForSigQuit(std::ostream& os) {
732 ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
733 std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
734 for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
735 if (ContainsElement(boot_oat_files, oat_file.get())) {
736 continue;
737 }
Andreas Gampe29d38e72016-03-23 15:31:51 +0000738 os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
Nicolas Geoffray04680f32016-03-17 11:56:54 +0000739 }
740}
741
Mathieu Chartierf9c6fc62015-10-07 11:44:05 -0700742} // namespace art