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