1 /*
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 <stdlib.h>
20 #include <sys/stat.h>
21 
22 #include <memory>
23 #include <queue>
24 #include <vector>
25 
26 #include "android-base/file.h"
27 #include "android-base/stringprintf.h"
28 #include "android-base/strings.h"
29 #include "art_field-inl.h"
30 #include "base/bit_vector-inl.h"
31 #include "base/file_utils.h"
32 #include "base/logging.h"  // For VLOG.
33 #include "base/mutex-inl.h"
34 #include "base/sdk_version.h"
35 #include "base/stl_util.h"
36 #include "base/systrace.h"
37 #include "class_linker.h"
38 #include "class_loader_context.h"
39 #include "dex/art_dex_file_loader.h"
40 #include "dex/dex_file-inl.h"
41 #include "dex/dex_file_loader.h"
42 #include "dex/dex_file_tracking_registrar.h"
43 #include "gc/scoped_gc_critical_section.h"
44 #include "gc/space/image_space.h"
45 #include "handle_scope-inl.h"
46 #include "jit/jit.h"
47 #include "jni/java_vm_ext.h"
48 #include "jni/jni_internal.h"
49 #include "mirror/class_loader.h"
50 #include "mirror/object-inl.h"
51 #include "oat_file.h"
52 #include "oat_file_assistant.h"
53 #include "obj_ptr-inl.h"
54 #include "runtime_image.h"
55 #include "scoped_thread_state_change-inl.h"
56 #include "thread-current-inl.h"
57 #include "thread_list.h"
58 #include "thread_pool.h"
59 #include "vdex_file.h"
60 #include "verifier/verifier_deps.h"
61 #include "well_known_classes.h"
62 
63 namespace art HIDDEN {
64 
65 using android::base::StringPrintf;
66 
67 // If true, we attempt to load the application image if it exists.
68 static constexpr bool kEnableAppImage = true;
69 
70 // If true, we attempt to load an app image generated by the runtime.
71 static const bool kEnableRuntimeAppImage = true;
72 
73 #if defined(__ANDROID__)
74 static const char* kDisableAppImageKeyword = "_disable_art_image_";
75 #endif
76 
RegisterOatFile(std::unique_ptr<const OatFile> oat_file,bool in_memory)77 const OatFile* OatFileManager::RegisterOatFile(std::unique_ptr<const OatFile> oat_file,
78                                                bool in_memory) {
79   // Use class_linker vlog to match the log for dex file registration.
80   VLOG(class_linker) << "Registered oat file " << oat_file->GetLocation();
81   PaletteNotifyOatFileLoaded(oat_file->GetLocation().c_str());
82 
83   WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
84   CHECK(in_memory ||
85         !only_use_system_oat_files_ ||
86         LocationIsTrusted(oat_file->GetLocation(), !Runtime::Current()->DenyArtApexDataFiles()) ||
87         !oat_file->IsExecutable())
88       << "Registering a non /system oat file: " << oat_file->GetLocation() << " android-root="
89       << GetAndroidRoot();
90   DCHECK(oat_file != nullptr);
91   if (kIsDebugBuild) {
92     CHECK(oat_files_.find(oat_file) == oat_files_.end());
93     for (const std::unique_ptr<const OatFile>& existing : oat_files_) {
94       CHECK_NE(oat_file.get(), existing.get()) << oat_file->GetLocation();
95       // Check that we don't have an oat file with the same address. Copies of the same oat file
96       // should be loaded at different addresses.
97       CHECK_NE(oat_file->Begin(), existing->Begin()) << "Oat file already mapped at that location";
98     }
99   }
100   const OatFile* ret = oat_file.get();
101   oat_files_.insert(std::move(oat_file));
102   return ret;
103 }
104 
UnRegisterAndDeleteOatFile(const OatFile * oat_file)105 void OatFileManager::UnRegisterAndDeleteOatFile(const OatFile* oat_file) {
106   WriterMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
107   DCHECK(oat_file != nullptr);
108   std::unique_ptr<const OatFile> compare(oat_file);
109   auto it = oat_files_.find(compare);
110   CHECK(it != oat_files_.end());
111   oat_files_.erase(it);
112   compare.release();  // NOLINT b/117926937
113 }
114 
FindOpenedOatFileFromDexLocation(const std::string & dex_base_location) const115 const OatFile* OatFileManager::FindOpenedOatFileFromDexLocation(
116     const std::string& dex_base_location) const {
117   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
118   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
119     const std::vector<const OatDexFile*>& oat_dex_files = oat_file->GetOatDexFiles();
120     for (const OatDexFile* oat_dex_file : oat_dex_files) {
121       if (DexFileLoader::GetBaseLocation(oat_dex_file->GetDexFileLocation()) == dex_base_location) {
122         return oat_file.get();
123       }
124     }
125   }
126   return nullptr;
127 }
128 
FindOpenedOatFileFromOatLocation(const std::string & oat_location) const129 const OatFile* OatFileManager::FindOpenedOatFileFromOatLocation(const std::string& oat_location)
130     const {
131   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
132   return FindOpenedOatFileFromOatLocationLocked(oat_location);
133 }
134 
FindOpenedOatFileFromOatLocationLocked(const std::string & oat_location) const135 const OatFile* OatFileManager::FindOpenedOatFileFromOatLocationLocked(
136     const std::string& oat_location) const {
137   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
138     if (oat_file->GetLocation() == oat_location) {
139       return oat_file.get();
140     }
141   }
142   return nullptr;
143 }
144 
GetBootOatFiles() const145 std::vector<const OatFile*> OatFileManager::GetBootOatFiles() const {
146   std::vector<gc::space::ImageSpace*> image_spaces =
147       Runtime::Current()->GetHeap()->GetBootImageSpaces();
148   std::vector<const OatFile*> oat_files;
149   oat_files.reserve(image_spaces.size());
150   for (gc::space::ImageSpace* image_space : image_spaces) {
151     oat_files.push_back(image_space->GetOatFile());
152   }
153   return oat_files;
154 }
155 
OatFileManager()156 OatFileManager::OatFileManager()
157     : only_use_system_oat_files_(false) {}
158 
~OatFileManager()159 OatFileManager::~OatFileManager() {
160   // Explicitly clear oat_files_ since the OatFile destructor calls back into OatFileManager for
161   // UnRegisterOatFileLocation.
162   oat_files_.clear();
163 }
164 
RegisterImageOatFiles(const std::vector<gc::space::ImageSpace * > & spaces)165 std::vector<const OatFile*> OatFileManager::RegisterImageOatFiles(
166     const std::vector<gc::space::ImageSpace*>& spaces) {
167   std::vector<const OatFile*> oat_files;
168   oat_files.reserve(spaces.size());
169   for (gc::space::ImageSpace* space : spaces) {
170     // The oat file was generated in memory if the image space has a profile.
171     bool in_memory = !space->GetProfileFiles().empty();
172     oat_files.push_back(RegisterOatFile(space->ReleaseOatFile(), in_memory));
173   }
174   return oat_files;
175 }
176 
ShouldLoadAppImage() const177 bool OatFileManager::ShouldLoadAppImage() const {
178   Runtime* const runtime = Runtime::Current();
179   if (!kEnableAppImage || runtime->IsJavaDebuggableAtInit()) {
180     return false;
181   }
182 
183 #if defined(__ANDROID__)
184   const char* process_name = getprogname();
185   // Some processes would rather take the runtime impact in the interest of memory (b/292210260)
186   if (process_name != nullptr && strstr(process_name, kDisableAppImageKeyword) != nullptr) {
187     LOG(INFO) << "Skipping app image load for " << process_name;
188     return false;
189   }
190 #endif
191 
192   return true;
193 }
194 
OpenDexFilesFromOat(const char * dex_location,jobject class_loader,jobjectArray dex_elements,const OatFile ** out_oat_file,std::vector<std::string> * error_msgs)195 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
196     const char* dex_location,
197     jobject class_loader,
198     jobjectArray dex_elements,
199     const OatFile** out_oat_file,
200     std::vector<std::string>* error_msgs) {
201   ScopedTrace trace(StringPrintf("%s(%s)", __FUNCTION__, dex_location));
202   CHECK(dex_location != nullptr);
203   CHECK(error_msgs != nullptr);
204 
205   // Verify we aren't holding the mutator lock, which could starve GC when
206   // hitting the disk.
207   Thread* const self = Thread::Current();
208   Locks::mutator_lock_->AssertNotHeld(self);
209   Runtime* const runtime = Runtime::Current();
210 
211   std::vector<std::unique_ptr<const DexFile>> dex_files;
212   std::unique_ptr<ClassLoaderContext> context(
213       ClassLoaderContext::CreateContextForClassLoader(class_loader, dex_elements));
214 
215   // If the class_loader is null there's not much we can do. This happens if a dex files is loaded
216   // directly with DexFile APIs instead of using class loaders.
217   if (class_loader == nullptr) {
218     LOG(WARNING) << "Opening an oat file without a class loader. "
219                  << "Are you using the deprecated DexFile APIs?";
220   } else if (context != nullptr) {
221     auto oat_file_assistant = std::make_unique<OatFileAssistant>(dex_location,
222                                                                  kRuntimeISA,
223                                                                  context.get(),
224                                                                  runtime->GetOatFilesExecutable(),
225                                                                  only_use_system_oat_files_);
226 
227     // Get the current optimization status for trace debugging.
228     // Implementation detail note: GetOptimizationStatus will select the same
229     // oat file as GetBestOatFile used below, and in doing so it already pre-populates
230     // some OatFileAssistant internal fields.
231     std::string odex_location;
232     std::string compilation_filter;
233     std::string compilation_reason;
234     std::string odex_status;
235     OatFileAssistant::Location ignored_location;
236     oat_file_assistant->GetOptimizationStatus(
237         &odex_location, &compilation_filter, &compilation_reason, &odex_status, &ignored_location);
238 
239     ScopedTrace odex_loading(StringPrintf(
240         "location=%s status=%s filter=%s reason=%s",
241         odex_location.c_str(),
242         odex_status.c_str(),
243         compilation_filter.c_str(),
244         compilation_reason.c_str()));
245 
246     const bool has_registered_app_info = Runtime::Current()->GetAppInfo()->HasRegisteredAppInfo();
247     const AppInfo::CodeType code_type =
248         Runtime::Current()->GetAppInfo()->GetRegisteredCodeType(dex_location);
249     // We only want to madvise primary/split dex artifacts as a startup optimization. However,
250     // as the code_type for those artifacts may not be set until the initial app info registration,
251     // we conservatively madvise everything until the app info registration is complete.
252     const bool should_madvise = !has_registered_app_info ||
253                                 code_type == AppInfo::CodeType::kPrimaryApk ||
254                                 code_type == AppInfo::CodeType::kSplitApk;
255 
256     // Proceed with oat file loading.
257     std::unique_ptr<const OatFile> oat_file(oat_file_assistant->GetBestOatFile().release());
258     VLOG(oat) << "OatFileAssistant(" << dex_location << ").GetBestOatFile()="
259               << (oat_file != nullptr ? oat_file->GetLocation() : "")
260               << " (executable=" << (oat_file != nullptr ? oat_file->IsExecutable() : false) << ")";
261 
262     CHECK(oat_file == nullptr || odex_location == oat_file->GetLocation())
263         << "OatFileAssistant non-determinism in choosing best oat files. "
264         << "optimization-status-location=" << odex_location
265         << " best_oat_file-location=" << oat_file->GetLocation();
266 
267     if (oat_file != nullptr) {
268       bool compilation_enabled =
269           CompilerFilter::IsAotCompilationEnabled(oat_file->GetCompilerFilter());
270       // Load the dex files from the oat file.
271       bool added_image_space = false;
272       if (should_madvise) {
273         VLOG(oat) << "Madvising oat file: " << oat_file->GetLocation();
274         size_t madvise_size_limit = runtime->GetMadviseWillNeedSizeOdex();
275         Runtime::MadviseFileForRange(madvise_size_limit,
276                                      oat_file->Size(),
277                                      oat_file->Begin(),
278                                      oat_file->End(),
279                                      oat_file->GetLocation());
280       }
281 
282       ScopedTrace app_image_timing("AppImage:Loading");
283 
284       // We need to throw away the image space if we are debuggable but the oat-file source of the
285       // image is not otherwise we might get classes with inlined methods or other such things.
286       std::unique_ptr<gc::space::ImageSpace> image_space;
287       if (ShouldLoadAppImage()) {
288         if (oat_file->IsExecutable()) {
289           // App images generated by the compiler can only be used if the oat file
290           // is executable.
291           image_space = oat_file_assistant->OpenImageSpace(oat_file.get());
292         }
293         // Load the runtime image. This logic must be aligned with the one that determines when to
294         // keep runtime images in `ArtManagerLocal.cleanup` in
295         // `art/libartservice/service/java/com/android/server/art/ArtManagerLocal.java`.
296         if (kEnableRuntimeAppImage && image_space == nullptr && !compilation_enabled) {
297           std::string art_file = RuntimeImage::GetRuntimeImagePath(dex_location);
298           std::string error_msg;
299           ScopedObjectAccess soa(self);
300           image_space = gc::space::ImageSpace::CreateFromAppImage(
301               art_file.c_str(), oat_file.get(), &error_msg);
302           if (image_space == nullptr) {
303             (OS::FileExists(art_file.c_str()) ? LOG_STREAM(INFO) : VLOG_STREAM(image))
304                 << "Could not load runtime generated app image: " << error_msg;
305           }
306         }
307       }
308       if (image_space != nullptr) {
309         ScopedObjectAccess soa(self);
310         StackHandleScope<1> hs(self);
311         Handle<mirror::ClassLoader> h_loader(
312             hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
313         // Can not load app image without class loader.
314         if (h_loader != nullptr) {
315           oat_file->SetAppImageBegin(image_space->Begin());
316           std::string temp_error_msg;
317           // Add image space has a race condition since other threads could be reading from the
318           // spaces array.
319           {
320             ScopedThreadSuspension sts(self, ThreadState::kSuspended);
321             gc::ScopedGCCriticalSection gcs(self,
322                                             gc::kGcCauseAddRemoveAppImageSpace,
323                                             gc::kCollectorTypeAddRemoveAppImageSpace);
324             ScopedSuspendAll ssa("Add image space");
325             runtime->GetHeap()->AddSpace(image_space.get());
326           }
327           {
328             ScopedTrace image_space_timing("Adding image space");
329             gc::space::ImageSpace* space_ptr = image_space.get();
330             added_image_space = runtime->GetClassLinker()->AddImageSpaces(
331                 ArrayRef<gc::space::ImageSpace*>(&space_ptr, /*size=*/1),
332                 h_loader,
333                 context.get(),
334                 /*out*/ &dex_files,
335                 /*out*/ &temp_error_msg);
336           }
337           if (added_image_space) {
338             // Successfully added image space to heap, release the map so that it does not get
339             // freed.
340             image_space.release();  // NOLINT b/117926937
341 
342             // Register for tracking.
343             for (const auto& dex_file : dex_files) {
344               dex::tracking::RegisterDexFile(dex_file.get());
345             }
346           } else {
347             LOG(INFO) << "Failed to add image file: " << temp_error_msg;
348             oat_file->SetAppImageBegin(nullptr);
349             dex_files.clear();
350             {
351               ScopedThreadSuspension sts(self, ThreadState::kSuspended);
352               gc::ScopedGCCriticalSection gcs(self,
353                                               gc::kGcCauseAddRemoveAppImageSpace,
354                                               gc::kCollectorTypeAddRemoveAppImageSpace);
355               ScopedSuspendAll ssa("Remove image space");
356               runtime->GetHeap()->RemoveSpace(image_space.get());
357             }
358             // Non-fatal, don't update error_msg.
359           }
360         }
361       }
362       if (!added_image_space) {
363         DCHECK(dex_files.empty());
364 
365         if (oat_file->RequiresImage()) {
366           LOG(WARNING) << "Loading "
367                        << oat_file->GetLocation()
368                        << " non-executable as it requires an image which we failed to load";
369           // file as non-executable.
370           auto nonexecutable_oat_file_assistant =
371               std::make_unique<OatFileAssistant>(dex_location,
372                                                  kRuntimeISA,
373                                                  context.get(),
374                                                  /*load_executable=*/false,
375                                                  only_use_system_oat_files_);
376           oat_file.reset(nonexecutable_oat_file_assistant->GetBestOatFile().release());
377 
378           // The file could be deleted concurrently (for example background
379           // dexopt, or secondary oat file being deleted by the app).
380           if (oat_file == nullptr) {
381             LOG(WARNING) << "Failed to reload oat file non-executable " << dex_location;
382           }
383         }
384 
385         if (oat_file != nullptr) {
386           dex_files = oat_file_assistant->LoadDexFiles(*oat_file.get(), dex_location);
387 
388           // Register for tracking.
389           for (const auto& dex_file : dex_files) {
390             dex::tracking::RegisterDexFile(dex_file.get());
391           }
392         }
393       }
394       if (dex_files.empty()) {
395         ScopedTrace failed_to_open_dex_files("FailedToOpenDexFilesFromOat");
396         error_msgs->push_back("Failed to open dex files from " + odex_location);
397       } else if (should_madvise) {
398         size_t madvise_size_limit = Runtime::Current()->GetMadviseWillNeedTotalDexSize();
399         for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
400           // Prefetch the dex file based on vdex size limit (name should
401           // have been dex size limit).
402           VLOG(oat) << "Madvising dex file: " << dex_file->GetLocation();
403           Runtime::MadviseFileForRange(madvise_size_limit,
404                                        dex_file->Size(),
405                                        dex_file->Begin(),
406                                        dex_file->Begin() + dex_file->Size(),
407                                        dex_file->GetLocation());
408           if (dex_file->Size() >= madvise_size_limit) {
409             break;
410           }
411           madvise_size_limit -= dex_file->Size();
412         }
413       }
414 
415       if (oat_file != nullptr) {
416         VLOG(class_linker) << "Registering " << oat_file->GetLocation();
417         *out_oat_file = RegisterOatFile(std::move(oat_file));
418       }
419     } else {
420       // oat_file == nullptr
421       // Verify if any of the dex files being loaded is already in the class path.
422       // If so, report an error with the current stack trace.
423       // Most likely the developer didn't intend to do this because it will waste
424       // performance and memory.
425       if (oat_file_assistant->GetBestStatus() == OatFileAssistant::kOatContextOutOfDate) {
426         std::set<const DexFile*> already_exists_in_classpath =
427             context->CheckForDuplicateDexFiles(MakeNonOwningPointerVector(dex_files));
428         if (!already_exists_in_classpath.empty()) {
429           ScopedTrace duplicate_dex_files("DuplicateDexFilesInContext");
430           auto duplicate_it = already_exists_in_classpath.begin();
431           std::string duplicates = (*duplicate_it)->GetLocation();
432           for (duplicate_it++ ; duplicate_it != already_exists_in_classpath.end(); duplicate_it++) {
433             duplicates += "," + (*duplicate_it)->GetLocation();
434           }
435 
436           std::ostringstream out;
437           out << "Trying to load dex files which is already loaded in the same ClassLoader "
438               << "hierarchy.\n"
439               << "This is a strong indication of bad ClassLoader construct which leads to poor "
440               << "performance and wastes memory.\n"
441               << "The list of duplicate dex files is: " << duplicates << "\n"
442               << "The current class loader context is: "
443               << context->EncodeContextForOatFile("") << "\n"
444               << "Java stack trace:\n";
445 
446           {
447             ScopedObjectAccess soa(self);
448             self->DumpJavaStack(out);
449           }
450 
451           // We log this as an ERROR to stress the fact that this is most likely unintended.
452           // Note that ART cannot do anything about it. It is up to the app to fix their logic.
453           // Here we are trying to give a heads up on why the app might have performance issues.
454           LOG(ERROR) << out.str();
455         }
456       }
457     }
458 
459     Runtime::Current()->GetAppInfo()->RegisterOdexStatus(
460         dex_location,
461         compilation_filter,
462         compilation_reason,
463         odex_status);
464   }
465 
466   // If we arrive here with an empty dex files list, it means we fail to load
467   // it/them through an .oat file.
468   if (dex_files.empty()) {
469     std::string error_msg;
470     static constexpr bool kVerifyChecksum = true;
471     ArtDexFileLoader dex_file_loader(dex_location);
472     if (!dex_file_loader.Open(Runtime::Current()->IsVerificationEnabled(),
473                               kVerifyChecksum,
474                               /*out*/ &error_msg,
475                               &dex_files)) {
476       ScopedTrace fail_to_open_dex_from_apk("FailedToOpenDexFilesFromApk");
477       LOG(WARNING) << error_msg;
478       error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
479                             + " because: " + error_msg);
480     }
481   }
482 
483   if (Runtime::Current()->GetJit() != nullptr) {
484     Runtime::Current()->GetJit()->RegisterDexFiles(dex_files, class_loader);
485   }
486 
487   // Now that we loaded the dex/odex files, notify the runtime.
488   // Note that we do this everytime we load dex files.
489   Runtime::Current()->NotifyDexFileLoaded();
490 
491   return dex_files;
492 }
493 
GetDexFileHeaders(const std::vector<MemMap> & maps)494 static std::vector<const DexFile::Header*> GetDexFileHeaders(const std::vector<MemMap>& maps) {
495   std::vector<const DexFile::Header*> headers;
496   headers.reserve(maps.size());
497   for (const MemMap& map : maps) {
498     DCHECK(map.IsValid());
499     headers.push_back(reinterpret_cast<const DexFile::Header*>(map.Begin()));
500   }
501   return headers;
502 }
503 
OpenDexFilesFromOat(std::vector<MemMap> && dex_mem_maps,jobject class_loader,jobjectArray dex_elements,const OatFile ** out_oat_file,std::vector<std::string> * error_msgs)504 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
505     std::vector<MemMap>&& dex_mem_maps,
506     jobject class_loader,
507     jobjectArray dex_elements,
508     const OatFile** out_oat_file,
509     std::vector<std::string>* error_msgs) {
510   std::vector<std::unique_ptr<const DexFile>> dex_files = OpenDexFilesFromOat_Impl(
511       std::move(dex_mem_maps),
512       class_loader,
513       dex_elements,
514       out_oat_file,
515       error_msgs);
516 
517   if (error_msgs->empty()) {
518     // Remove write permission from DexFile pages. We do this at the end because
519     // OatFile assigns OatDexFile pointer in the DexFile objects.
520     for (std::unique_ptr<const DexFile>& dex_file : dex_files) {
521       if (!dex_file->DisableWrite()) {
522         error_msgs->push_back("Failed to make dex file " + dex_file->GetLocation() + " read-only");
523       }
524     }
525   }
526 
527   if (!error_msgs->empty()) {
528     return std::vector<std::unique_ptr<const DexFile>>();
529   }
530 
531   return dex_files;
532 }
533 
OpenDexFilesFromOat_Impl(std::vector<MemMap> && dex_mem_maps,jobject class_loader,jobjectArray dex_elements,const OatFile ** out_oat_file,std::vector<std::string> * error_msgs)534 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat_Impl(
535     std::vector<MemMap>&& dex_mem_maps,
536     jobject class_loader,
537     jobjectArray dex_elements,
538     const OatFile** out_oat_file,
539     std::vector<std::string>* error_msgs) {
540   ScopedTrace trace(__FUNCTION__);
541   std::string error_msg;
542   DCHECK(error_msgs != nullptr);
543 
544   // Extract dex file headers from `dex_mem_maps`.
545   const std::vector<const DexFile::Header*> dex_headers = GetDexFileHeaders(dex_mem_maps);
546 
547   // Determine dex/vdex locations and the combined location checksum.
548   std::string dex_location;
549   std::string vdex_path;
550   bool has_vdex = OatFileAssistant::AnonymousDexVdexLocation(dex_headers,
551                                                              kRuntimeISA,
552                                                              &dex_location,
553                                                              &vdex_path);
554 
555   // Attempt to open an existing vdex and check dex file checksums match.
556   std::unique_ptr<VdexFile> vdex_file = nullptr;
557   if (has_vdex && OS::FileExists(vdex_path.c_str())) {
558     vdex_file = VdexFile::Open(vdex_path,
559                                /* writable= */ false,
560                                /* low_4gb= */ false,
561                                &error_msg);
562     if (vdex_file == nullptr) {
563       LOG(WARNING) << "Failed to open vdex " << vdex_path << ": " << error_msg;
564     } else if (!vdex_file->MatchesDexFileChecksums(dex_headers)) {
565       LOG(WARNING) << "Failed to open vdex " << vdex_path << ": dex file checksum mismatch";
566       vdex_file.reset(nullptr);
567     }
568   }
569 
570   // Load dex files. Skip structural dex file verification if vdex was found
571   // and dex checksums matched.
572   std::vector<std::unique_ptr<const DexFile>> dex_files;
573   for (size_t i = 0; i < dex_mem_maps.size(); ++i) {
574     static constexpr bool kVerifyChecksum = true;
575     ArtDexFileLoader dex_file_loader(std::move(dex_mem_maps[i]),
576                                      DexFileLoader::GetMultiDexLocation(i, dex_location.c_str()));
577     std::unique_ptr<const DexFile> dex_file(dex_file_loader.Open(
578         dex_headers[i]->checksum_,
579         /* verify= */ (vdex_file == nullptr) && Runtime::Current()->IsVerificationEnabled(),
580         kVerifyChecksum,
581         &error_msg));
582     if (dex_file != nullptr) {
583       dex::tracking::RegisterDexFile(dex_file.get());  // Register for tracking.
584       dex_files.push_back(std::move(dex_file));
585     } else {
586       error_msgs->push_back("Failed to open dex files from memory: " + error_msg);
587     }
588   }
589 
590   // Check if we should proceed to creating an OatFile instance backed by the vdex.
591   // We need: (a) an existing vdex, (b) class loader (can be null if invoked via reflection),
592   // and (c) no errors during dex file loading.
593   if (vdex_file == nullptr || class_loader == nullptr || !error_msgs->empty()) {
594     return dex_files;
595   }
596 
597   // Attempt to create a class loader context, check OpenDexFiles succeeds (prerequisite
598   // for using the context later).
599   std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::CreateContextForClassLoader(
600       class_loader,
601       dex_elements);
602   if (context == nullptr) {
603     LOG(ERROR) << "Could not create class loader context for " << vdex_path;
604     return dex_files;
605   }
606   DCHECK(context->OpenDexFiles())
607       << "Context created from already opened dex files should not attempt to open again";
608 
609   // Initialize an OatFile instance backed by the loaded vdex.
610   std::unique_ptr<OatFile> oat_file(OatFile::OpenFromVdex(MakeNonOwningPointerVector(dex_files),
611                                                           std::move(vdex_file),
612                                                           dex_location,
613                                                           context.get()));
614   if (oat_file != nullptr) {
615     VLOG(class_linker) << "Registering " << oat_file->GetLocation();
616     *out_oat_file = RegisterOatFile(std::move(oat_file));
617   }
618   return dex_files;
619 }
620 
621 // Check how many vdex files exist in the same directory as the vdex file we are about
622 // to write. If more than or equal to kAnonymousVdexCacheSize, unlink the least
623 // recently used one(s) (according to stat-reported atime).
UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string & vdex_path_to_add,std::string * error_msg)624 static bool UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string& vdex_path_to_add,
625                                                 std::string* error_msg) {
626   std::string basename = android::base::Basename(vdex_path_to_add);
627   if (!OatFileAssistant::IsAnonymousVdexBasename(basename)) {
628     // File is not for in memory dex files.
629     return true;
630   }
631 
632   if (OS::FileExists(vdex_path_to_add.c_str())) {
633     // File already exists and will be overwritten.
634     // This will not change the number of entries in the cache.
635     return true;
636   }
637 
638   auto last_slash = vdex_path_to_add.rfind('/');
639   CHECK(last_slash != std::string::npos);
640   std::string vdex_dir = vdex_path_to_add.substr(0, last_slash + 1);
641 
642   if (!OS::DirectoryExists(vdex_dir.c_str())) {
643     // Folder does not exist yet. Cache has zero entries.
644     return true;
645   }
646 
647   std::vector<std::pair<time_t, std::string>> cache;
648 
649   DIR* c_dir = opendir(vdex_dir.c_str());
650   if (c_dir == nullptr) {
651     *error_msg = "Unable to open " + vdex_dir + " to delete unused vdex files";
652     return false;
653   }
654   for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
655     if (de->d_type != DT_REG) {
656       continue;
657     }
658     basename = de->d_name;
659     if (!OatFileAssistant::IsAnonymousVdexBasename(basename)) {
660       continue;
661     }
662     std::string fullname = vdex_dir + basename;
663 
664     struct stat s;
665     int rc = TEMP_FAILURE_RETRY(stat(fullname.c_str(), &s));
666     if (rc == -1) {
667       *error_msg = "Failed to stat() anonymous vdex file " + fullname;
668       return false;
669     }
670 
671     cache.push_back(std::make_pair(s.st_atime, fullname));
672   }
673   CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
674 
675   if (cache.size() < OatFileManager::kAnonymousVdexCacheSize) {
676     return true;
677   }
678 
679   std::sort(cache.begin(),
680             cache.end(),
681             [](const auto& a, const auto& b) { return a.first < b.first; });
682   for (size_t i = OatFileManager::kAnonymousVdexCacheSize - 1; i < cache.size(); ++i) {
683     if (unlink(cache[i].second.c_str()) != 0) {
684       *error_msg = "Could not unlink anonymous vdex file " + cache[i].second;
685       return false;
686     }
687   }
688 
689   return true;
690 }
691 
692 class BackgroundVerificationTask final : public Task {
693  public:
BackgroundVerificationTask(const std::vector<const DexFile * > & dex_files,jobject class_loader,const std::string & vdex_path)694   BackgroundVerificationTask(const std::vector<const DexFile*>& dex_files,
695                              jobject class_loader,
696                              const std::string& vdex_path)
697       : dex_files_(dex_files),
698         vdex_path_(vdex_path) {
699     Thread* const self = Thread::Current();
700     ScopedObjectAccess soa(self);
701     // Create a global ref for `class_loader` because it will be accessed from a different thread.
702     class_loader_ = soa.Vm()->AddGlobalRef(self, soa.Decode<mirror::ClassLoader>(class_loader));
703     CHECK(class_loader_ != nullptr);
704   }
705 
~BackgroundVerificationTask()706   ~BackgroundVerificationTask() {
707     Thread* const self = Thread::Current();
708     ScopedObjectAccess soa(self);
709     soa.Vm()->DeleteGlobalRef(self, class_loader_);
710   }
711 
Run(Thread * self)712   void Run(Thread* self) override {
713     std::string error_msg;
714     ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
715     verifier::VerifierDeps verifier_deps(dex_files_);
716 
717     // Iterate over all classes and verify them.
718     for (const DexFile* dex_file : dex_files_) {
719       for (uint32_t cdef_idx = 0; cdef_idx < dex_file->NumClassDefs(); cdef_idx++) {
720         const dex::ClassDef& class_def = dex_file->GetClassDef(cdef_idx);
721 
722         // Take handles inside the loop. The background verification is low priority
723         // and we want to minimize the risk of blocking anyone else.
724         ScopedObjectAccess soa(self);
725         StackHandleScope<2> hs(self);
726         Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
727             soa.Decode<mirror::ClassLoader>(class_loader_)));
728         Handle<mirror::Class> h_class(hs.NewHandle<mirror::Class>(class_linker->FindClass(
729             self,
730             dex_file->GetClassDescriptor(class_def),
731             h_loader)));
732 
733         if (h_class == nullptr) {
734           DCHECK(self->IsExceptionPending());
735           self->ClearException();
736           continue;
737         }
738 
739         if (&h_class->GetDexFile() != dex_file) {
740           // There is a different class in the class path or a parent class loader
741           // with the same descriptor. This `h_class` is not resolvable, skip it.
742           continue;
743         }
744 
745         DCHECK(h_class->IsResolved()) << h_class->PrettyDescriptor();
746         class_linker->VerifyClass(self, &verifier_deps, h_class);
747         if (self->IsExceptionPending()) {
748           // ClassLinker::VerifyClass can throw, but the exception isn't useful here.
749           self->ClearException();
750         }
751 
752         DCHECK(h_class->IsVerified() || h_class->IsErroneous())
753             << h_class->PrettyDescriptor() << ": state=" << h_class->GetStatus();
754 
755         if (h_class->IsVerified()) {
756           verifier_deps.RecordClassVerified(*dex_file, class_def);
757         }
758       }
759     }
760 
761     // Delete old vdex files if there are too many in the folder.
762     if (!UnlinkLeastRecentlyUsedVdexIfNeeded(vdex_path_, &error_msg)) {
763       LOG(ERROR) << "Could not unlink old vdex files " << vdex_path_ << ": " << error_msg;
764       return;
765     }
766 
767     // Construct a vdex file and write `verifier_deps` into it.
768     if (!VdexFile::WriteToDisk(vdex_path_,
769                                dex_files_,
770                                verifier_deps,
771                                &error_msg)) {
772       LOG(ERROR) << "Could not write anonymous vdex " << vdex_path_ << ": " << error_msg;
773       return;
774     }
775   }
776 
Finalize()777   void Finalize() override {
778     delete this;
779   }
780 
781  private:
782   const std::vector<const DexFile*> dex_files_;
783   jobject class_loader_;
784   const std::string vdex_path_;
785 
786   DISALLOW_COPY_AND_ASSIGN(BackgroundVerificationTask);
787 };
788 
RunBackgroundVerification(const std::vector<const DexFile * > & dex_files,jobject class_loader)789 void OatFileManager::RunBackgroundVerification(const std::vector<const DexFile*>& dex_files,
790                                                jobject class_loader) {
791   Runtime* const runtime = Runtime::Current();
792   Thread* const self = Thread::Current();
793 
794   if (runtime->IsJavaDebuggable()) {
795     // Threads created by ThreadPool ("runtime threads") are not allowed to load
796     // classes when debuggable to match class-initialization semantics
797     // expectations. Do not verify in the background.
798     return;
799   }
800 
801   {
802     // Temporarily create a class loader context to see if we recognize the
803     // chain.
804     std::unique_ptr<ClassLoaderContext> context(
805         ClassLoaderContext::CreateContextForClassLoader(class_loader, nullptr));
806     if (context == nullptr) {
807       // We only run background verification for class loaders we know the lookup
808       // chain. Because the background verification runs on runtime threads,
809       // which do not call Java, we won't be able to load classes when
810       // verifying, which is something the current verifier relies on.
811       return;
812     }
813   }
814 
815   if (!IsSdkVersionSetAndAtLeast(runtime->GetTargetSdkVersion(), SdkVersion::kQ)) {
816     // Do not run for legacy apps as they may depend on the previous class loader behaviour.
817     return;
818   }
819 
820   if (runtime->IsShuttingDown(self)) {
821     // Not allowed to create new threads during runtime shutdown.
822     return;
823   }
824 
825   if (dex_files.size() < 1) {
826     // Nothing to verify.
827     return;
828   }
829 
830   std::string dex_location = dex_files[0]->GetLocation();
831   const std::string& data_dir = Runtime::Current()->GetProcessDataDirectory();
832   if (!dex_location.starts_with(data_dir)) {
833     // For now, we only run background verification for secondary dex files.
834     // Running it for primary or split APKs could have some undesirable
835     // side-effects, like overloading the device on app startup.
836     return;
837   }
838 
839   std::string error_msg;
840   std::string odex_filename;
841   if (!OatFileAssistant::DexLocationToOdexFilename(dex_location,
842                                                    kRuntimeISA,
843                                                    &odex_filename,
844                                                    &error_msg)) {
845     LOG(WARNING) << "Could not get odex filename for " << dex_location << ": " << error_msg;
846     return;
847   }
848 
849   if (LocationIsOnArtApexData(odex_filename) && Runtime::Current()->DenyArtApexDataFiles()) {
850     // Ignore vdex file associated with this odex file as the odex file is not trustworthy.
851     return;
852   }
853 
854   {
855     WriterMutexLock mu(self, *Locks::oat_file_manager_lock_);
856     if (verification_thread_pool_ == nullptr) {
857       verification_thread_pool_.reset(
858           ThreadPool::Create("Verification thread pool", /* num_threads= */ 1));
859       verification_thread_pool_->StartWorkers(self);
860     }
861   }
862   verification_thread_pool_->AddTask(self, new BackgroundVerificationTask(
863       dex_files,
864       class_loader,
865       GetVdexFilename(odex_filename)));
866 }
867 
WaitForWorkersToBeCreated()868 void OatFileManager::WaitForWorkersToBeCreated() {
869   DCHECK(!Runtime::Current()->IsShuttingDown(Thread::Current()))
870       << "Cannot create new threads during runtime shutdown";
871   if (verification_thread_pool_ != nullptr) {
872     verification_thread_pool_->WaitForWorkersToBeCreated();
873   }
874 }
875 
DeleteThreadPool()876 void OatFileManager::DeleteThreadPool() {
877   verification_thread_pool_.reset(nullptr);
878 }
879 
WaitForBackgroundVerificationTasksToFinish()880 void OatFileManager::WaitForBackgroundVerificationTasksToFinish() {
881   if (verification_thread_pool_ == nullptr) {
882     return;
883   }
884 
885   Thread* const self = Thread::Current();
886   verification_thread_pool_->Wait(self, /* do_work= */ true, /* may_hold_locks= */ false);
887 }
888 
WaitForBackgroundVerificationTasks()889 void OatFileManager::WaitForBackgroundVerificationTasks() {
890   if (verification_thread_pool_ != nullptr) {
891     Thread* const self = Thread::Current();
892     verification_thread_pool_->WaitForWorkersToBeCreated();
893     verification_thread_pool_->Wait(self, /* do_work= */ true, /* may_hold_locks= */ false);
894   }
895 }
896 
ClearOnlyUseTrustedOatFiles()897 void OatFileManager::ClearOnlyUseTrustedOatFiles() {
898   only_use_system_oat_files_ = false;
899 }
900 
SetOnlyUseTrustedOatFiles()901 void OatFileManager::SetOnlyUseTrustedOatFiles() {
902   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
903   if (!oat_files_.empty()) {
904     LOG(FATAL) << "Unexpected non-empty loaded oat files ";
905   }
906   only_use_system_oat_files_ = true;
907 }
908 
DumpForSigQuit(std::ostream & os)909 void OatFileManager::DumpForSigQuit(std::ostream& os) {
910   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
911   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
912   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
913     if (ContainsElement(boot_oat_files, oat_file.get())) {
914       continue;
915     }
916     os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
917   }
918 }
919 
ContainsPc(const void * code)920 bool OatFileManager::ContainsPc(const void* code) {
921   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
922   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
923   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
924     if (oat_file->Contains(code)) {
925       return true;
926     }
927   }
928   return false;
929 }
930 
931 }  // namespace art
932