xref: /aosp_15_r20/art/runtime/oat/oat_file_manager.cc (revision 795d594fd825385562da6b089ea9b2033f3abf5a)
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                                                                  kRuntimeQuickCodeISA,
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           image_space = gc::space::ImageSpace::CreateFromAppImage(
300               art_file.c_str(), oat_file.get(), &error_msg);
301           if (image_space == nullptr) {
302             (OS::FileExists(art_file.c_str()) ? LOG_STREAM(INFO) : VLOG_STREAM(image))
303                 << "Could not load runtime generated app image: " << error_msg;
304           }
305         }
306       }
307       if (image_space != nullptr) {
308         ScopedObjectAccess soa(self);
309         StackHandleScope<1> hs(self);
310         Handle<mirror::ClassLoader> h_loader(
311             hs.NewHandle(soa.Decode<mirror::ClassLoader>(class_loader)));
312         // Can not load app image without class loader.
313         if (h_loader != nullptr) {
314           oat_file->SetAppImageBegin(image_space->Begin());
315           std::string temp_error_msg;
316           // Add image space has a race condition since other threads could be reading from the
317           // spaces array.
318           {
319             ScopedThreadSuspension sts(self, ThreadState::kSuspended);
320             gc::ScopedGCCriticalSection gcs(self,
321                                             gc::kGcCauseAddRemoveAppImageSpace,
322                                             gc::kCollectorTypeAddRemoveAppImageSpace);
323             ScopedSuspendAll ssa("Add image space");
324             runtime->GetHeap()->AddSpace(image_space.get());
325           }
326           {
327             ScopedTrace image_space_timing("Adding image space");
328             gc::space::ImageSpace* space_ptr = image_space.get();
329             added_image_space = runtime->GetClassLinker()->AddImageSpaces(
330                 ArrayRef<gc::space::ImageSpace*>(&space_ptr, /*size=*/1),
331                 h_loader,
332                 context.get(),
333                 /*out*/ &dex_files,
334                 /*out*/ &temp_error_msg);
335           }
336           if (added_image_space) {
337             // Successfully added image space to heap, release the map so that it does not get
338             // freed.
339             image_space.release();  // NOLINT b/117926937
340 
341             // Register for tracking.
342             for (const auto& dex_file : dex_files) {
343               dex::tracking::RegisterDexFile(dex_file.get());
344             }
345           } else {
346             LOG(INFO) << "Failed to add image file: " << temp_error_msg;
347             oat_file->SetAppImageBegin(nullptr);
348             dex_files.clear();
349             {
350               ScopedThreadSuspension sts(self, ThreadState::kSuspended);
351               gc::ScopedGCCriticalSection gcs(self,
352                                               gc::kGcCauseAddRemoveAppImageSpace,
353                                               gc::kCollectorTypeAddRemoveAppImageSpace);
354               ScopedSuspendAll ssa("Remove image space");
355               runtime->GetHeap()->RemoveSpace(image_space.get());
356             }
357             // Non-fatal, don't update error_msg.
358           }
359         }
360       }
361       if (!added_image_space) {
362         DCHECK(dex_files.empty());
363 
364         if (oat_file->RequiresImage()) {
365           LOG(WARNING) << "Loading "
366                        << oat_file->GetLocation()
367                        << " non-executable as it requires an image which we failed to load";
368           // file as non-executable.
369           auto nonexecutable_oat_file_assistant =
370               std::make_unique<OatFileAssistant>(dex_location,
371                                                  kRuntimeQuickCodeISA,
372                                                  context.get(),
373                                                  /*load_executable=*/false,
374                                                  only_use_system_oat_files_);
375           oat_file.reset(nonexecutable_oat_file_assistant->GetBestOatFile().release());
376 
377           // The file could be deleted concurrently (for example background
378           // dexopt, or secondary oat file being deleted by the app).
379           if (oat_file == nullptr) {
380             LOG(WARNING) << "Failed to reload oat file non-executable " << dex_location;
381           }
382         }
383 
384         if (oat_file != nullptr) {
385           dex_files = oat_file_assistant->LoadDexFiles(*oat_file.get(), dex_location);
386 
387           // Register for tracking.
388           for (const auto& dex_file : dex_files) {
389             dex::tracking::RegisterDexFile(dex_file.get());
390           }
391         }
392       }
393       if (dex_files.empty()) {
394         ScopedTrace failed_to_open_dex_files("FailedToOpenDexFilesFromOat");
395         error_msgs->push_back("Failed to open dex files from " + odex_location);
396       } else if (should_madvise) {
397         size_t madvise_size_limit = Runtime::Current()->GetMadviseWillNeedTotalDexSize();
398         for (const std::unique_ptr<const DexFile>& dex_file : dex_files) {
399           // Prefetch the dex file based on vdex size limit (name should
400           // have been dex size limit).
401           VLOG(oat) << "Madvising dex file: " << dex_file->GetLocation();
402           Runtime::MadviseFileForRange(madvise_size_limit,
403                                        dex_file->Size(),
404                                        dex_file->Begin(),
405                                        dex_file->Begin() + dex_file->Size(),
406                                        dex_file->GetLocation());
407           if (dex_file->Size() >= madvise_size_limit) {
408             break;
409           }
410           madvise_size_limit -= dex_file->Size();
411         }
412       }
413 
414       if (oat_file != nullptr) {
415         VLOG(class_linker) << "Registering " << oat_file->GetLocation();
416         *out_oat_file = RegisterOatFile(std::move(oat_file));
417       }
418     } else {
419       // oat_file == nullptr
420       // Verify if any of the dex files being loaded is already in the class path.
421       // If so, report an error with the current stack trace.
422       // Most likely the developer didn't intend to do this because it will waste
423       // performance and memory.
424       if (oat_file_assistant->GetBestStatus() == OatFileAssistant::kOatContextOutOfDate) {
425         std::set<const DexFile*> already_exists_in_classpath =
426             context->CheckForDuplicateDexFiles(MakeNonOwningPointerVector(dex_files));
427         if (!already_exists_in_classpath.empty()) {
428           ScopedTrace duplicate_dex_files("DuplicateDexFilesInContext");
429           auto duplicate_it = already_exists_in_classpath.begin();
430           std::string duplicates = (*duplicate_it)->GetLocation();
431           for (duplicate_it++ ; duplicate_it != already_exists_in_classpath.end(); duplicate_it++) {
432             duplicates += "," + (*duplicate_it)->GetLocation();
433           }
434 
435           std::ostringstream out;
436           out << "Trying to load dex files which is already loaded in the same ClassLoader "
437               << "hierarchy.\n"
438               << "This is a strong indication of bad ClassLoader construct which leads to poor "
439               << "performance and wastes memory.\n"
440               << "The list of duplicate dex files is: " << duplicates << "\n"
441               << "The current class loader context is: "
442               << context->EncodeContextForOatFile("") << "\n"
443               << "Java stack trace:\n";
444 
445           {
446             ScopedObjectAccess soa(self);
447             self->DumpJavaStack(out);
448           }
449 
450           // We log this as an ERROR to stress the fact that this is most likely unintended.
451           // Note that ART cannot do anything about it. It is up to the app to fix their logic.
452           // Here we are trying to give a heads up on why the app might have performance issues.
453           LOG(ERROR) << out.str();
454         }
455       }
456     }
457 
458     Runtime::Current()->GetAppInfo()->RegisterOdexStatus(
459         dex_location,
460         compilation_filter,
461         compilation_reason,
462         odex_status);
463   }
464 
465   // If we arrive here with an empty dex files list, it means we fail to load
466   // it/them through an .oat file.
467   if (dex_files.empty()) {
468     std::string error_msg;
469     static constexpr bool kVerifyChecksum = true;
470     ArtDexFileLoader dex_file_loader(dex_location);
471     if (!dex_file_loader.Open(Runtime::Current()->IsVerificationEnabled(),
472                               kVerifyChecksum,
473                               /*out*/ &error_msg,
474                               &dex_files)) {
475       ScopedTrace fail_to_open_dex_from_apk("FailedToOpenDexFilesFromApk");
476       LOG(WARNING) << error_msg;
477       error_msgs->push_back("Failed to open dex files from " + std::string(dex_location)
478                             + " because: " + error_msg);
479     }
480   }
481 
482   if (Runtime::Current()->GetJit() != nullptr) {
483     Runtime::Current()->GetJit()->RegisterDexFiles(dex_files, class_loader);
484   }
485 
486   // Now that we loaded the dex/odex files, notify the runtime.
487   // Note that we do this everytime we load dex files.
488   Runtime::Current()->NotifyDexFileLoaded();
489 
490   return dex_files;
491 }
492 
GetDexFileHeaders(const std::vector<MemMap> & maps)493 static std::vector<const DexFile::Header*> GetDexFileHeaders(const std::vector<MemMap>& maps) {
494   std::vector<const DexFile::Header*> headers;
495   headers.reserve(maps.size());
496   for (const MemMap& map : maps) {
497     DCHECK(map.IsValid());
498     headers.push_back(reinterpret_cast<const DexFile::Header*>(map.Begin()));
499   }
500   return headers;
501 }
502 
OpenDexFilesFromOat(std::vector<MemMap> && dex_mem_maps,jobject class_loader,jobjectArray dex_elements,const OatFile ** out_oat_file,std::vector<std::string> * error_msgs)503 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat(
504     std::vector<MemMap>&& dex_mem_maps,
505     jobject class_loader,
506     jobjectArray dex_elements,
507     const OatFile** out_oat_file,
508     std::vector<std::string>* error_msgs) {
509   std::vector<std::unique_ptr<const DexFile>> dex_files = OpenDexFilesFromOat_Impl(
510       std::move(dex_mem_maps),
511       class_loader,
512       dex_elements,
513       out_oat_file,
514       error_msgs);
515 
516   if (error_msgs->empty()) {
517     // Remove write permission from DexFile pages. We do this at the end because
518     // OatFile assigns OatDexFile pointer in the DexFile objects.
519     for (std::unique_ptr<const DexFile>& dex_file : dex_files) {
520       if (!dex_file->DisableWrite()) {
521         error_msgs->push_back("Failed to make dex file " + dex_file->GetLocation() + " read-only");
522       }
523     }
524   }
525 
526   if (!error_msgs->empty()) {
527     return std::vector<std::unique_ptr<const DexFile>>();
528   }
529 
530   return dex_files;
531 }
532 
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)533 std::vector<std::unique_ptr<const DexFile>> OatFileManager::OpenDexFilesFromOat_Impl(
534     std::vector<MemMap>&& dex_mem_maps,
535     jobject class_loader,
536     jobjectArray dex_elements,
537     const OatFile** out_oat_file,
538     std::vector<std::string>* error_msgs) {
539   ScopedTrace trace(__FUNCTION__);
540   std::string error_msg;
541   DCHECK(error_msgs != nullptr);
542 
543   // Extract dex file headers from `dex_mem_maps`.
544   const std::vector<const DexFile::Header*> dex_headers = GetDexFileHeaders(dex_mem_maps);
545 
546   // Determine dex/vdex locations and the combined location checksum.
547   std::string dex_location;
548   std::string vdex_path;
549   bool has_vdex = OatFileAssistant::AnonymousDexVdexLocation(dex_headers,
550                                                              kRuntimeQuickCodeISA,
551                                                              &dex_location,
552                                                              &vdex_path);
553 
554   // Attempt to open an existing vdex and check dex file checksums match.
555   std::unique_ptr<VdexFile> vdex_file = nullptr;
556   if (has_vdex && OS::FileExists(vdex_path.c_str())) {
557     vdex_file = VdexFile::Open(vdex_path,
558                                /* writable= */ false,
559                                /* low_4gb= */ false,
560                                &error_msg);
561     if (vdex_file == nullptr) {
562       LOG(WARNING) << "Failed to open vdex " << vdex_path << ": " << error_msg;
563     } else if (!vdex_file->MatchesDexFileChecksums(dex_headers)) {
564       LOG(WARNING) << "Failed to open vdex " << vdex_path << ": dex file checksum mismatch";
565       vdex_file.reset(nullptr);
566     }
567   }
568 
569   // Load dex files. Skip structural dex file verification if vdex was found
570   // and dex checksums matched.
571   std::vector<std::unique_ptr<const DexFile>> dex_files;
572   for (size_t i = 0; i < dex_mem_maps.size(); ++i) {
573     static constexpr bool kVerifyChecksum = true;
574     ArtDexFileLoader dex_file_loader(std::move(dex_mem_maps[i]),
575                                      DexFileLoader::GetMultiDexLocation(i, dex_location.c_str()));
576     std::unique_ptr<const DexFile> dex_file(dex_file_loader.Open(
577         dex_headers[i]->checksum_,
578         /* verify= */ (vdex_file == nullptr) && Runtime::Current()->IsVerificationEnabled(),
579         kVerifyChecksum,
580         &error_msg));
581     if (dex_file != nullptr) {
582       dex::tracking::RegisterDexFile(dex_file.get());  // Register for tracking.
583       dex_files.push_back(std::move(dex_file));
584     } else {
585       error_msgs->push_back("Failed to open dex files from memory: " + error_msg);
586     }
587   }
588 
589   // Check if we should proceed to creating an OatFile instance backed by the vdex.
590   // We need: (a) an existing vdex, (b) class loader (can be null if invoked via reflection),
591   // and (c) no errors during dex file loading.
592   if (vdex_file == nullptr || class_loader == nullptr || !error_msgs->empty()) {
593     return dex_files;
594   }
595 
596   // Attempt to create a class loader context, check OpenDexFiles succeeds (prerequisite
597   // for using the context later).
598   std::unique_ptr<ClassLoaderContext> context = ClassLoaderContext::CreateContextForClassLoader(
599       class_loader,
600       dex_elements);
601   if (context == nullptr) {
602     LOG(ERROR) << "Could not create class loader context for " << vdex_path;
603     return dex_files;
604   }
605   DCHECK(context->OpenDexFiles())
606       << "Context created from already opened dex files should not attempt to open again";
607 
608   // Initialize an OatFile instance backed by the loaded vdex.
609   std::unique_ptr<OatFile> oat_file(OatFile::OpenFromVdex(MakeNonOwningPointerVector(dex_files),
610                                                           std::move(vdex_file),
611                                                           dex_location,
612                                                           context.get()));
613   if (oat_file != nullptr) {
614     VLOG(class_linker) << "Registering " << oat_file->GetLocation();
615     *out_oat_file = RegisterOatFile(std::move(oat_file));
616   }
617   return dex_files;
618 }
619 
620 // Check how many vdex files exist in the same directory as the vdex file we are about
621 // to write. If more than or equal to kAnonymousVdexCacheSize, unlink the least
622 // recently used one(s) (according to stat-reported atime).
UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string & vdex_path_to_add,std::string * error_msg)623 static bool UnlinkLeastRecentlyUsedVdexIfNeeded(const std::string& vdex_path_to_add,
624                                                 std::string* error_msg) {
625   std::string basename = android::base::Basename(vdex_path_to_add);
626   if (!OatFileAssistant::IsAnonymousVdexBasename(basename)) {
627     // File is not for in memory dex files.
628     return true;
629   }
630 
631   if (OS::FileExists(vdex_path_to_add.c_str())) {
632     // File already exists and will be overwritten.
633     // This will not change the number of entries in the cache.
634     return true;
635   }
636 
637   auto last_slash = vdex_path_to_add.rfind('/');
638   CHECK(last_slash != std::string::npos);
639   std::string vdex_dir = vdex_path_to_add.substr(0, last_slash + 1);
640 
641   if (!OS::DirectoryExists(vdex_dir.c_str())) {
642     // Folder does not exist yet. Cache has zero entries.
643     return true;
644   }
645 
646   std::vector<std::pair<time_t, std::string>> cache;
647 
648   DIR* c_dir = opendir(vdex_dir.c_str());
649   if (c_dir == nullptr) {
650     *error_msg = "Unable to open " + vdex_dir + " to delete unused vdex files";
651     return false;
652   }
653   for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
654     if (de->d_type != DT_REG) {
655       continue;
656     }
657     basename = de->d_name;
658     if (!OatFileAssistant::IsAnonymousVdexBasename(basename)) {
659       continue;
660     }
661     std::string fullname = vdex_dir + basename;
662 
663     struct stat s;
664     int rc = TEMP_FAILURE_RETRY(stat(fullname.c_str(), &s));
665     if (rc == -1) {
666       *error_msg = "Failed to stat() anonymous vdex file " + fullname;
667       return false;
668     }
669 
670     cache.push_back(std::make_pair(s.st_atime, fullname));
671   }
672   CHECK_EQ(0, closedir(c_dir)) << "Unable to close directory.";
673 
674   if (cache.size() < OatFileManager::kAnonymousVdexCacheSize) {
675     return true;
676   }
677 
678   std::sort(cache.begin(),
679             cache.end(),
680             [](const auto& a, const auto& b) { return a.first < b.first; });
681   for (size_t i = OatFileManager::kAnonymousVdexCacheSize - 1; i < cache.size(); ++i) {
682     if (unlink(cache[i].second.c_str()) != 0) {
683       *error_msg = "Could not unlink anonymous vdex file " + cache[i].second;
684       return false;
685     }
686   }
687 
688   return true;
689 }
690 
691 class BackgroundVerificationTask final : public Task {
692  public:
BackgroundVerificationTask(const std::vector<const DexFile * > & dex_files,jobject class_loader,const std::string & vdex_path)693   BackgroundVerificationTask(const std::vector<const DexFile*>& dex_files,
694                              jobject class_loader,
695                              const std::string& vdex_path)
696       : dex_files_(dex_files),
697         vdex_path_(vdex_path) {
698     Thread* const self = Thread::Current();
699     ScopedObjectAccess soa(self);
700     // Create a global ref for `class_loader` because it will be accessed from a different thread.
701     class_loader_ = soa.Vm()->AddGlobalRef(self, soa.Decode<mirror::ClassLoader>(class_loader));
702     CHECK(class_loader_ != nullptr);
703   }
704 
~BackgroundVerificationTask()705   ~BackgroundVerificationTask() {
706     Thread* const self = Thread::Current();
707     ScopedObjectAccess soa(self);
708     soa.Vm()->DeleteGlobalRef(self, class_loader_);
709   }
710 
Run(Thread * self)711   void Run(Thread* self) override {
712     std::string error_msg;
713     ClassLinker* const class_linker = Runtime::Current()->GetClassLinker();
714     verifier::VerifierDeps verifier_deps(dex_files_);
715 
716     // Iterate over all classes and verify them.
717     for (const DexFile* dex_file : dex_files_) {
718       for (uint32_t cdef_idx = 0; cdef_idx < dex_file->NumClassDefs(); cdef_idx++) {
719         const dex::ClassDef& class_def = dex_file->GetClassDef(cdef_idx);
720 
721         // Take handles inside the loop. The background verification is low priority
722         // and we want to minimize the risk of blocking anyone else.
723         ScopedObjectAccess soa(self);
724         StackHandleScope<2> hs(self);
725         Handle<mirror::ClassLoader> h_loader(hs.NewHandle(
726             soa.Decode<mirror::ClassLoader>(class_loader_)));
727         Handle<mirror::Class> h_class =
728             hs.NewHandle(class_linker->FindClass(self, *dex_file, class_def.class_idx_, h_loader));
729 
730         if (h_class == nullptr) {
731           DCHECK(self->IsExceptionPending());
732           self->ClearException();
733           continue;
734         }
735 
736         if (&h_class->GetDexFile() != dex_file) {
737           // There is a different class in the class path or a parent class loader
738           // with the same descriptor. This `h_class` is not resolvable, skip it.
739           continue;
740         }
741 
742         DCHECK(h_class->IsResolved()) << h_class->PrettyDescriptor();
743         class_linker->VerifyClass(self, &verifier_deps, h_class);
744         if (self->IsExceptionPending()) {
745           // ClassLinker::VerifyClass can throw, but the exception isn't useful here.
746           self->ClearException();
747         }
748 
749         DCHECK(h_class->IsVerified() || h_class->IsErroneous())
750             << h_class->PrettyDescriptor() << ": state=" << h_class->GetStatus();
751 
752         if (h_class->IsVerified()) {
753           verifier_deps.RecordClassVerified(*dex_file, class_def);
754         }
755       }
756     }
757 
758     // Delete old vdex files if there are too many in the folder.
759     if (!UnlinkLeastRecentlyUsedVdexIfNeeded(vdex_path_, &error_msg)) {
760       LOG(ERROR) << "Could not unlink old vdex files " << vdex_path_ << ": " << error_msg;
761       return;
762     }
763 
764     // Construct a vdex file and write `verifier_deps` into it.
765     if (!VdexFile::WriteToDisk(vdex_path_,
766                                dex_files_,
767                                verifier_deps,
768                                &error_msg)) {
769       LOG(ERROR) << "Could not write anonymous vdex " << vdex_path_ << ": " << error_msg;
770       return;
771     }
772   }
773 
Finalize()774   void Finalize() override {
775     delete this;
776   }
777 
778  private:
779   const std::vector<const DexFile*> dex_files_;
780   jobject class_loader_;
781   const std::string vdex_path_;
782 
783   DISALLOW_COPY_AND_ASSIGN(BackgroundVerificationTask);
784 };
785 
RunBackgroundVerification(const std::vector<const DexFile * > & dex_files,jobject class_loader)786 void OatFileManager::RunBackgroundVerification(const std::vector<const DexFile*>& dex_files,
787                                                jobject class_loader) {
788   Runtime* const runtime = Runtime::Current();
789   Thread* const self = Thread::Current();
790 
791   if (runtime->IsJavaDebuggable()) {
792     // Threads created by ThreadPool ("runtime threads") are not allowed to load
793     // classes when debuggable to match class-initialization semantics
794     // expectations. Do not verify in the background.
795     return;
796   }
797 
798   {
799     // Temporarily create a class loader context to see if we recognize the
800     // chain.
801     std::unique_ptr<ClassLoaderContext> context(
802         ClassLoaderContext::CreateContextForClassLoader(class_loader, nullptr));
803     if (context == nullptr) {
804       // We only run background verification for class loaders we know the lookup
805       // chain. Because the background verification runs on runtime threads,
806       // which do not call Java, we won't be able to load classes when
807       // verifying, which is something the current verifier relies on.
808       return;
809     }
810   }
811 
812   if (!IsSdkVersionSetAndAtLeast(runtime->GetTargetSdkVersion(), SdkVersion::kQ)) {
813     // Do not run for legacy apps as they may depend on the previous class loader behaviour.
814     return;
815   }
816 
817   if (runtime->IsShuttingDown(self)) {
818     // Not allowed to create new threads during runtime shutdown.
819     return;
820   }
821 
822   if (dex_files.size() < 1) {
823     // Nothing to verify.
824     return;
825   }
826 
827   std::string dex_location = dex_files[0]->GetLocation();
828   const std::string& data_dir = Runtime::Current()->GetProcessDataDirectory();
829   if (!dex_location.starts_with(data_dir)) {
830     // For now, we only run background verification for secondary dex files.
831     // Running it for primary or split APKs could have some undesirable
832     // side-effects, like overloading the device on app startup.
833     return;
834   }
835 
836   std::string error_msg;
837   std::string odex_filename;
838   if (!OatFileAssistant::DexLocationToOdexFilename(dex_location,
839                                                    kRuntimeQuickCodeISA,
840                                                    &odex_filename,
841                                                    &error_msg)) {
842     LOG(WARNING) << "Could not get odex filename for " << dex_location << ": " << error_msg;
843     return;
844   }
845 
846   if (LocationIsOnArtApexData(odex_filename) && Runtime::Current()->DenyArtApexDataFiles()) {
847     // Ignore vdex file associated with this odex file as the odex file is not trustworthy.
848     return;
849   }
850 
851   {
852     WriterMutexLock mu(self, *Locks::oat_file_manager_lock_);
853     if (verification_thread_pool_ == nullptr) {
854       verification_thread_pool_.reset(
855           ThreadPool::Create("Verification thread pool", /* num_threads= */ 1));
856       verification_thread_pool_->StartWorkers(self);
857     }
858   }
859   verification_thread_pool_->AddTask(self, new BackgroundVerificationTask(
860       dex_files,
861       class_loader,
862       GetVdexFilename(odex_filename)));
863 }
864 
WaitForWorkersToBeCreated()865 void OatFileManager::WaitForWorkersToBeCreated() {
866   DCHECK(!Runtime::Current()->IsShuttingDown(Thread::Current()))
867       << "Cannot create new threads during runtime shutdown";
868   if (verification_thread_pool_ != nullptr) {
869     verification_thread_pool_->WaitForWorkersToBeCreated();
870   }
871 }
872 
DeleteThreadPool()873 void OatFileManager::DeleteThreadPool() {
874   verification_thread_pool_.reset(nullptr);
875 }
876 
WaitForBackgroundVerificationTasksToFinish()877 void OatFileManager::WaitForBackgroundVerificationTasksToFinish() {
878   if (verification_thread_pool_ == nullptr) {
879     return;
880   }
881 
882   Thread* const self = Thread::Current();
883   verification_thread_pool_->Wait(self, /* do_work= */ true, /* may_hold_locks= */ false);
884 }
885 
WaitForBackgroundVerificationTasks()886 void OatFileManager::WaitForBackgroundVerificationTasks() {
887   if (verification_thread_pool_ != nullptr) {
888     Thread* const self = Thread::Current();
889     verification_thread_pool_->WaitForWorkersToBeCreated();
890     verification_thread_pool_->Wait(self, /* do_work= */ true, /* may_hold_locks= */ false);
891   }
892 }
893 
ClearOnlyUseTrustedOatFiles()894 void OatFileManager::ClearOnlyUseTrustedOatFiles() {
895   only_use_system_oat_files_ = false;
896 }
897 
SetOnlyUseTrustedOatFiles()898 void OatFileManager::SetOnlyUseTrustedOatFiles() {
899   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
900   if (!oat_files_.empty()) {
901     LOG(FATAL) << "Unexpected non-empty loaded oat files ";
902   }
903   only_use_system_oat_files_ = true;
904 }
905 
DumpForSigQuit(std::ostream & os)906 void OatFileManager::DumpForSigQuit(std::ostream& os) {
907   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
908   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
909   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
910     if (ContainsElement(boot_oat_files, oat_file.get())) {
911       continue;
912     }
913     os << oat_file->GetLocation() << ": " << oat_file->GetCompilerFilter() << "\n";
914   }
915 }
916 
ContainsPc(const void * code)917 bool OatFileManager::ContainsPc(const void* code) {
918   ReaderMutexLock mu(Thread::Current(), *Locks::oat_file_manager_lock_);
919   std::vector<const OatFile*> boot_oat_files = GetBootOatFiles();
920   for (const std::unique_ptr<const OatFile>& oat_file : oat_files_) {
921     if (oat_file->Contains(code)) {
922       return true;
923     }
924   }
925   return false;
926 }
927 
928 }  // namespace art
929