1 /*
2  * Copyright (C) 2014 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_assistant.h"
18 
19 #include <sstream>
20 
21 #include <sys/stat.h>
22 #include "zlib.h"
23 
24 #include "android-base/stringprintf.h"
25 #include "android-base/strings.h"
26 
27 #include "base/file_utils.h"
28 #include "base/logging.h"  // For VLOG.
29 #include "base/macros.h"
30 #include "base/os.h"
31 #include "base/stl_util.h"
32 #include "base/string_view_cpp20.h"
33 #include "base/systrace.h"
34 #include "base/utils.h"
35 #include "class_linker.h"
36 #include "class_loader_context.h"
37 #include "compiler_filter.h"
38 #include "dex/art_dex_file_loader.h"
39 #include "dex/dex_file_loader.h"
40 #include "exec_utils.h"
41 #include "gc/heap.h"
42 #include "gc/space/image_space.h"
43 #include "image.h"
44 #include "oat.h"
45 #include "runtime.h"
46 #include "scoped_thread_state_change-inl.h"
47 #include "vdex_file.h"
48 
49 namespace art {
50 
51 using android::base::StringPrintf;
52 
53 static constexpr const char* kAnonymousDexPrefix = "Anonymous-DexFile@";
54 static constexpr const char* kVdexExtension = ".vdex";
55 
operator <<(std::ostream & stream,const OatFileAssistant::OatStatus status)56 std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status) {
57   switch (status) {
58     case OatFileAssistant::kOatCannotOpen:
59       stream << "kOatCannotOpen";
60       break;
61     case OatFileAssistant::kOatDexOutOfDate:
62       stream << "kOatDexOutOfDate";
63       break;
64     case OatFileAssistant::kOatBootImageOutOfDate:
65       stream << "kOatBootImageOutOfDate";
66       break;
67     case OatFileAssistant::kOatUpToDate:
68       stream << "kOatUpToDate";
69       break;
70     default:
71       UNREACHABLE();
72   }
73 
74   return stream;
75 }
76 
OatFileAssistant(const char * dex_location,const InstructionSet isa,bool load_executable,bool only_load_system_executable)77 OatFileAssistant::OatFileAssistant(const char* dex_location,
78                                    const InstructionSet isa,
79                                    bool load_executable,
80                                    bool only_load_system_executable)
81     : OatFileAssistant(dex_location,
82                        isa,
83                        load_executable,
84                        only_load_system_executable,
85                        /*vdex_fd=*/ -1,
86                        /*oat_fd=*/ -1,
87                        /*zip_fd=*/ -1) {}
88 
89 
OatFileAssistant(const char * dex_location,const InstructionSet isa,bool load_executable,bool only_load_system_executable,int vdex_fd,int oat_fd,int zip_fd)90 OatFileAssistant::OatFileAssistant(const char* dex_location,
91                                    const InstructionSet isa,
92                                    bool load_executable,
93                                    bool only_load_system_executable,
94                                    int vdex_fd,
95                                    int oat_fd,
96                                    int zip_fd)
97     : isa_(isa),
98       load_executable_(load_executable),
99       only_load_system_executable_(only_load_system_executable),
100       odex_(this, /*is_oat_location=*/ false),
101       oat_(this, /*is_oat_location=*/ true),
102       zip_fd_(zip_fd) {
103   CHECK(dex_location != nullptr) << "OatFileAssistant: null dex location";
104 
105   if (zip_fd < 0) {
106     CHECK_LE(oat_fd, 0) << "zip_fd must be provided with valid oat_fd. zip_fd=" << zip_fd
107       << " oat_fd=" << oat_fd;
108     CHECK_LE(vdex_fd, 0) << "zip_fd must be provided with valid vdex_fd. zip_fd=" << zip_fd
109       << " vdex_fd=" << vdex_fd;;
110   }
111 
112   dex_location_.assign(dex_location);
113 
114   if (load_executable_ && isa != kRuntimeISA) {
115     LOG(WARNING) << "OatFileAssistant: Load executable specified, "
116       << "but isa is not kRuntimeISA. Will not attempt to load executable.";
117     load_executable_ = false;
118   }
119 
120   // Get the odex filename.
121   std::string error_msg;
122   std::string odex_file_name;
123   if (DexLocationToOdexFilename(dex_location_, isa_, &odex_file_name, &error_msg)) {
124     odex_.Reset(odex_file_name, UseFdToReadFiles(), zip_fd, vdex_fd, oat_fd);
125   } else {
126     LOG(WARNING) << "Failed to determine odex file name: " << error_msg;
127   }
128 
129   if (!UseFdToReadFiles()) {
130     // Get the oat filename.
131     std::string oat_file_name;
132     if (DexLocationToOatFilename(dex_location_, isa_, &oat_file_name, &error_msg)) {
133       oat_.Reset(oat_file_name, /*use_fd=*/ false);
134     } else {
135       LOG(WARNING) << "Failed to determine oat file name for dex location "
136                    << dex_location_ << ": " << error_msg;
137     }
138   }
139 
140   // Check if the dex directory is writable.
141   // This will be needed in most uses of OatFileAssistant and so it's OK to
142   // compute it eagerly. (the only use which will not make use of it is
143   // OatFileAssistant::GetStatusDump())
144   size_t pos = dex_location_.rfind('/');
145   if (pos == std::string::npos) {
146     LOG(WARNING) << "Failed to determine dex file parent directory: " << dex_location_;
147   } else if (!UseFdToReadFiles()) {
148     // We cannot test for parent access when using file descriptors. That's ok
149     // because in this case we will always pick the odex file anyway.
150     std::string parent = dex_location_.substr(0, pos);
151     if (access(parent.c_str(), W_OK) == 0) {
152       dex_parent_writable_ = true;
153     } else {
154       VLOG(oat) << "Dex parent of " << dex_location_ << " is not writable: " << strerror(errno);
155     }
156   }
157 }
158 
UseFdToReadFiles()159 bool OatFileAssistant::UseFdToReadFiles() {
160   return zip_fd_ >= 0;
161 }
162 
IsInBootClassPath()163 bool OatFileAssistant::IsInBootClassPath() {
164   // Note: We check the current boot class path, regardless of the ISA
165   // specified by the user. This is okay, because the boot class path should
166   // be the same for all ISAs.
167   // TODO: Can we verify the boot class path is the same for all ISAs?
168   Runtime* runtime = Runtime::Current();
169   ClassLinker* class_linker = runtime->GetClassLinker();
170   const auto& boot_class_path = class_linker->GetBootClassPath();
171   for (size_t i = 0; i < boot_class_path.size(); i++) {
172     if (boot_class_path[i]->GetLocation() == dex_location_) {
173       VLOG(oat) << "Dex location " << dex_location_ << " is in boot class path";
174       return true;
175     }
176   }
177   return false;
178 }
179 
GetDexOptNeeded(CompilerFilter::Filter target,ClassLoaderContext * class_loader_context,const std::vector<int> & context_fds,bool profile_changed,bool downgrade)180 int OatFileAssistant::GetDexOptNeeded(CompilerFilter::Filter target,
181                                       ClassLoaderContext* class_loader_context,
182                                       const std::vector<int>& context_fds,
183                                       bool profile_changed,
184                                       bool downgrade) {
185   OatFileInfo& info = GetBestInfo();
186   DexOptNeeded dexopt_needed = info.GetDexOptNeeded(target,
187                                                     class_loader_context,
188                                                     context_fds,
189                                                     profile_changed,
190                                                     downgrade);
191   if (info.IsOatLocation() || dexopt_needed == kDex2OatFromScratch) {
192     return dexopt_needed;
193   }
194   return -dexopt_needed;
195 }
196 
IsUpToDate()197 bool OatFileAssistant::IsUpToDate() {
198   return GetBestInfo().Status() == kOatUpToDate;
199 }
200 
GetBestOatFile()201 std::unique_ptr<OatFile> OatFileAssistant::GetBestOatFile() {
202   return GetBestInfo().ReleaseFileForUse();
203 }
204 
GetStatusDump()205 std::string OatFileAssistant::GetStatusDump() {
206   std::ostringstream status;
207   bool oat_file_exists = false;
208   bool odex_file_exists = false;
209   if (oat_.Status() != kOatCannotOpen) {
210     // If we can open the file, Filename should not return null.
211     CHECK(oat_.Filename() != nullptr);
212 
213     oat_file_exists = true;
214     status << *oat_.Filename() << "[status=" << oat_.Status() << ", ";
215     const OatFile* file = oat_.GetFile();
216     if (file == nullptr) {
217       // If the file is null even though the status is not kOatCannotOpen, it
218       // means we must have a vdex file with no corresponding oat file. In
219       // this case we cannot determine the compilation filter. Indicate that
220       // we have only the vdex file instead.
221       status << "vdex-only";
222     } else {
223       status << "compilation_filter=" << CompilerFilter::NameOfFilter(file->GetCompilerFilter());
224     }
225   }
226 
227   if (odex_.Status() != kOatCannotOpen) {
228     // If we can open the file, Filename should not return null.
229     CHECK(odex_.Filename() != nullptr);
230 
231     odex_file_exists = true;
232     if (oat_file_exists) {
233       status << "] ";
234     }
235     status << *odex_.Filename() << "[status=" << odex_.Status() << ", ";
236     const OatFile* file = odex_.GetFile();
237     if (file == nullptr) {
238       status << "vdex-only";
239     } else {
240       status << "compilation_filter=" << CompilerFilter::NameOfFilter(file->GetCompilerFilter());
241     }
242   }
243 
244   if (!oat_file_exists && !odex_file_exists) {
245     status << "invalid[";
246   }
247 
248   status << "]";
249   return status.str();
250 }
251 
LoadDexFiles(const OatFile & oat_file,const char * dex_location)252 std::vector<std::unique_ptr<const DexFile>> OatFileAssistant::LoadDexFiles(
253     const OatFile &oat_file, const char *dex_location) {
254   std::vector<std::unique_ptr<const DexFile>> dex_files;
255   if (LoadDexFiles(oat_file, dex_location, &dex_files)) {
256     return dex_files;
257   } else {
258     return std::vector<std::unique_ptr<const DexFile>>();
259   }
260 }
261 
LoadDexFiles(const OatFile & oat_file,const std::string & dex_location,std::vector<std::unique_ptr<const DexFile>> * out_dex_files)262 bool OatFileAssistant::LoadDexFiles(
263     const OatFile &oat_file,
264     const std::string& dex_location,
265     std::vector<std::unique_ptr<const DexFile>>* out_dex_files) {
266   // Load the main dex file.
267   std::string error_msg;
268   const OatDexFile* oat_dex_file = oat_file.GetOatDexFile(
269       dex_location.c_str(), nullptr, &error_msg);
270   if (oat_dex_file == nullptr) {
271     LOG(WARNING) << error_msg;
272     return false;
273   }
274 
275   std::unique_ptr<const DexFile> dex_file = oat_dex_file->OpenDexFile(&error_msg);
276   if (dex_file.get() == nullptr) {
277     LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
278     return false;
279   }
280   out_dex_files->push_back(std::move(dex_file));
281 
282   // Load the rest of the multidex entries
283   for (size_t i = 1;; i++) {
284     std::string multidex_dex_location = DexFileLoader::GetMultiDexLocation(i, dex_location.c_str());
285     oat_dex_file = oat_file.GetOatDexFile(multidex_dex_location.c_str(), nullptr);
286     if (oat_dex_file == nullptr) {
287       // There are no more multidex entries to load.
288       break;
289     }
290 
291     dex_file = oat_dex_file->OpenDexFile(&error_msg);
292     if (dex_file.get() == nullptr) {
293       LOG(WARNING) << "Failed to open dex file from oat dex file: " << error_msg;
294       return false;
295     }
296     out_dex_files->push_back(std::move(dex_file));
297   }
298   return true;
299 }
300 
HasDexFiles()301 bool OatFileAssistant::HasDexFiles() {
302   ScopedTrace trace("HasDexFiles");
303   // Ensure GetRequiredDexChecksums has been run so that
304   // has_original_dex_files_ is initialized. We don't care about the result of
305   // GetRequiredDexChecksums.
306   GetRequiredDexChecksums();
307   return has_original_dex_files_;
308 }
309 
OdexFileStatus()310 OatFileAssistant::OatStatus OatFileAssistant::OdexFileStatus() {
311   return odex_.Status();
312 }
313 
OatFileStatus()314 OatFileAssistant::OatStatus OatFileAssistant::OatFileStatus() {
315   return oat_.Status();
316 }
317 
DexChecksumUpToDate(const VdexFile & file,std::string * error_msg)318 bool OatFileAssistant::DexChecksumUpToDate(const VdexFile& file, std::string* error_msg) {
319   ScopedTrace trace("DexChecksumUpToDate(vdex)");
320   const std::vector<uint32_t>* required_dex_checksums = GetRequiredDexChecksums();
321   if (required_dex_checksums == nullptr) {
322     LOG(WARNING) << "Required dex checksums not found. Assuming dex checksums are up to date.";
323     return true;
324   }
325 
326   uint32_t number_of_dex_files = file.GetVerifierDepsHeader().GetNumberOfDexFiles();
327   if (required_dex_checksums->size() != number_of_dex_files) {
328     *error_msg = StringPrintf("expected %zu dex files but found %u",
329                               required_dex_checksums->size(),
330                               number_of_dex_files);
331     return false;
332   }
333 
334   for (uint32_t i = 0; i < number_of_dex_files; i++) {
335     uint32_t expected_checksum = (*required_dex_checksums)[i];
336     uint32_t actual_checksum = file.GetLocationChecksum(i);
337     if (expected_checksum != actual_checksum) {
338       std::string dex = DexFileLoader::GetMultiDexLocation(i, dex_location_.c_str());
339       *error_msg = StringPrintf("Dex checksum does not match for dex: %s."
340                                 "Expected: %u, actual: %u",
341                                 dex.c_str(),
342                                 expected_checksum,
343                                 actual_checksum);
344       return false;
345     }
346   }
347 
348   return true;
349 }
350 
DexChecksumUpToDate(const OatFile & file,std::string * error_msg)351 bool OatFileAssistant::DexChecksumUpToDate(const OatFile& file, std::string* error_msg) {
352   ScopedTrace trace("DexChecksumUpToDate(oat)");
353   const std::vector<uint32_t>* required_dex_checksums = GetRequiredDexChecksums();
354   if (required_dex_checksums == nullptr) {
355     LOG(WARNING) << "Required dex checksums not found. Assuming dex checksums are up to date.";
356     return true;
357   }
358 
359   uint32_t number_of_dex_files = file.GetOatHeader().GetDexFileCount();
360   if (required_dex_checksums->size() != number_of_dex_files) {
361     *error_msg = StringPrintf("expected %zu dex files but found %u",
362                               required_dex_checksums->size(),
363                               number_of_dex_files);
364     return false;
365   }
366 
367   for (uint32_t i = 0; i < number_of_dex_files; i++) {
368     std::string dex = DexFileLoader::GetMultiDexLocation(i, dex_location_.c_str());
369     uint32_t expected_checksum = (*required_dex_checksums)[i];
370     const OatDexFile* oat_dex_file = file.GetOatDexFile(dex.c_str(), nullptr);
371     if (oat_dex_file == nullptr) {
372       *error_msg = StringPrintf("failed to find %s in %s", dex.c_str(), file.GetLocation().c_str());
373       return false;
374     }
375     uint32_t actual_checksum = oat_dex_file->GetDexFileLocationChecksum();
376     if (expected_checksum != actual_checksum) {
377       VLOG(oat) << "Dex checksum does not match for dex: " << dex
378         << ". Expected: " << expected_checksum
379         << ", Actual: " << actual_checksum;
380       return false;
381     }
382   }
383   return true;
384 }
385 
GivenOatFileStatus(const OatFile & file)386 OatFileAssistant::OatStatus OatFileAssistant::GivenOatFileStatus(const OatFile& file) {
387   // Verify the ART_USE_READ_BARRIER state.
388   // TODO: Don't fully reject files due to read barrier state. If they contain
389   // compiled code and are otherwise okay, we should return something like
390   // kOatRelocationOutOfDate. If they don't contain compiled code, the read
391   // barrier state doesn't matter.
392   const bool is_cc = file.GetOatHeader().IsConcurrentCopying();
393   constexpr bool kRuntimeIsCC = kUseReadBarrier;
394   if (is_cc != kRuntimeIsCC) {
395     return kOatCannotOpen;
396   }
397 
398   // Verify the dex checksum.
399   std::string error_msg;
400   VdexFile* vdex = file.GetVdexFile();
401   if (!DexChecksumUpToDate(*vdex, &error_msg)) {
402     LOG(ERROR) << error_msg;
403     return kOatDexOutOfDate;
404   }
405 
406   CompilerFilter::Filter current_compiler_filter = file.GetCompilerFilter();
407 
408   // Verify the image checksum
409   if (CompilerFilter::DependsOnImageChecksum(current_compiler_filter)) {
410     if (!ValidateBootClassPathChecksums(file)) {
411       VLOG(oat) << "Oat image checksum does not match image checksum.";
412       return kOatBootImageOutOfDate;
413     }
414   } else {
415     VLOG(oat) << "Image checksum test skipped for compiler filter " << current_compiler_filter;
416   }
417 
418   // zip_file_only_contains_uncompressed_dex_ is only set during fetching the dex checksums.
419   DCHECK(required_dex_checksums_attempted_);
420   if (only_load_system_executable_ &&
421       !LocationIsOnSystem(file.GetLocation().c_str()) &&
422       file.ContainsDexCode() &&
423       zip_file_only_contains_uncompressed_dex_) {
424     LOG(ERROR) << "Not loading "
425                << dex_location_
426                << ": oat file has dex code, but APK has uncompressed dex code";
427     return kOatDexOutOfDate;
428   }
429 
430   return kOatUpToDate;
431 }
432 
AnonymousDexVdexLocation(const std::vector<const DexFile::Header * > & headers,InstructionSet isa,uint32_t * location_checksum,std::string * dex_location,std::string * vdex_filename)433 bool OatFileAssistant::AnonymousDexVdexLocation(const std::vector<const DexFile::Header*>& headers,
434                                                 InstructionSet isa,
435                                                 /* out */ uint32_t* location_checksum,
436                                                 /* out */ std::string* dex_location,
437                                                 /* out */ std::string* vdex_filename) {
438   uint32_t checksum = adler32(0L, Z_NULL, 0);
439   for (const DexFile::Header* header : headers) {
440     checksum = adler32_combine(checksum,
441                                header->checksum_,
442                                header->file_size_ - DexFile::kNumNonChecksumBytes);
443   }
444   *location_checksum = checksum;
445 
446   const std::string& data_dir = Runtime::Current()->GetProcessDataDirectory();
447   if (data_dir.empty() || Runtime::Current()->IsZygote()) {
448     *dex_location = StringPrintf("%s%u", kAnonymousDexPrefix, checksum);
449     return false;
450   }
451   *dex_location = StringPrintf("%s/%s%u.jar", data_dir.c_str(), kAnonymousDexPrefix, checksum);
452 
453   std::string odex_filename;
454   std::string error_msg;
455   if (!DexLocationToOdexFilename(*dex_location, isa, &odex_filename, &error_msg)) {
456     LOG(WARNING) << "Could not get odex filename for " << *dex_location << ": " << error_msg;
457     return false;
458   }
459 
460   *vdex_filename = GetVdexFilename(odex_filename);
461   return true;
462 }
463 
IsAnonymousVdexBasename(const std::string & basename)464 bool OatFileAssistant::IsAnonymousVdexBasename(const std::string& basename) {
465   DCHECK(basename.find('/') == std::string::npos);
466   // `basename` must have format: <kAnonymousDexPrefix><checksum><kVdexExtension>
467   if (basename.size() < strlen(kAnonymousDexPrefix) + strlen(kVdexExtension) + 1 ||
468       !android::base::StartsWith(basename.c_str(), kAnonymousDexPrefix) ||
469       !android::base::EndsWith(basename, kVdexExtension)) {
470     return false;
471   }
472   // Check that all characters between the prefix and extension are decimal digits.
473   for (size_t i = strlen(kAnonymousDexPrefix); i < basename.size() - strlen(kVdexExtension); ++i) {
474     if (!std::isdigit(basename[i])) {
475       return false;
476     }
477   }
478   return true;
479 }
480 
DexLocationToOdexNames(const std::string & location,InstructionSet isa,std::string * odex_filename,std::string * oat_dir,std::string * isa_dir,std::string * error_msg)481 static bool DexLocationToOdexNames(const std::string& location,
482                                    InstructionSet isa,
483                                    std::string* odex_filename,
484                                    std::string* oat_dir,
485                                    std::string* isa_dir,
486                                    std::string* error_msg) {
487   CHECK(odex_filename != nullptr);
488   CHECK(error_msg != nullptr);
489 
490   // The odex file name is formed by replacing the dex_location extension with
491   // .odex and inserting an oat/<isa> directory. For example:
492   //   location = /foo/bar/baz.jar
493   //   odex_location = /foo/bar/oat/<isa>/baz.odex
494 
495   // Find the directory portion of the dex location and add the oat/<isa>
496   // directory.
497   size_t pos = location.rfind('/');
498   if (pos == std::string::npos) {
499     *error_msg = "Dex location " + location + " has no directory.";
500     return false;
501   }
502   std::string dir = location.substr(0, pos+1);
503   // Add the oat directory.
504   dir += "oat";
505   if (oat_dir != nullptr) {
506     *oat_dir = dir;
507   }
508   // Add the isa directory
509   dir += "/" + std::string(GetInstructionSetString(isa));
510   if (isa_dir != nullptr) {
511     *isa_dir = dir;
512   }
513 
514   // Get the base part of the file without the extension.
515   std::string file = location.substr(pos+1);
516   pos = file.rfind('.');
517   if (pos == std::string::npos) {
518     *error_msg = "Dex location " + location + " has no extension.";
519     return false;
520   }
521   std::string base = file.substr(0, pos);
522 
523   *odex_filename = dir + "/" + base + ".odex";
524   return true;
525 }
526 
DexLocationToOdexFilename(const std::string & location,InstructionSet isa,std::string * odex_filename,std::string * error_msg)527 bool OatFileAssistant::DexLocationToOdexFilename(const std::string& location,
528                                                  InstructionSet isa,
529                                                  std::string* odex_filename,
530                                                  std::string* error_msg) {
531   return DexLocationToOdexNames(location, isa, odex_filename, nullptr, nullptr, error_msg);
532 }
533 
DexLocationToOatFilename(const std::string & location,InstructionSet isa,std::string * oat_filename,std::string * error_msg)534 bool OatFileAssistant::DexLocationToOatFilename(const std::string& location,
535                                                 InstructionSet isa,
536                                                 std::string* oat_filename,
537                                                 std::string* error_msg) {
538   CHECK(oat_filename != nullptr);
539   CHECK(error_msg != nullptr);
540 
541   // If ANDROID_DATA is not set, return false instead of aborting.
542   // This can occur for preopt when using a class loader context.
543   if (GetAndroidDataSafe(error_msg).empty()) {
544     *error_msg = "GetAndroidDataSafe failed: " + *error_msg;
545     return false;
546   }
547 
548   std::string cache_dir = GetDalvikCache(GetInstructionSetString(isa));
549   if (cache_dir.empty()) {
550     *error_msg = "Dalvik cache directory does not exist";
551     return false;
552   }
553 
554   // TODO: The oat file assistant should be the definitive place for
555   // determining the oat file name from the dex location, not
556   // GetDalvikCacheFilename.
557   return GetDalvikCacheFilename(location.c_str(), cache_dir.c_str(), oat_filename, error_msg);
558 }
559 
GetRequiredDexChecksums()560 const std::vector<uint32_t>* OatFileAssistant::GetRequiredDexChecksums() {
561   if (!required_dex_checksums_attempted_) {
562     required_dex_checksums_attempted_ = true;
563     required_dex_checksums_found_ = false;
564     cached_required_dex_checksums_.clear();
565     std::string error_msg;
566     const ArtDexFileLoader dex_file_loader;
567     if (dex_file_loader.GetMultiDexChecksums(dex_location_.c_str(),
568                                              &cached_required_dex_checksums_,
569                                              &error_msg,
570                                              zip_fd_,
571                                              &zip_file_only_contains_uncompressed_dex_)) {
572       required_dex_checksums_found_ = true;
573       has_original_dex_files_ = true;
574     } else {
575       // This can happen if the original dex file has been stripped from the
576       // apk.
577       VLOG(oat) << "OatFileAssistant: " << error_msg;
578       has_original_dex_files_ = false;
579 
580       // Get the checksums from the odex if we can.
581       const OatFile* odex_file = odex_.GetFile();
582       if (odex_file != nullptr) {
583         required_dex_checksums_found_ = true;
584         for (size_t i = 0; i < odex_file->GetOatHeader().GetDexFileCount(); i++) {
585           std::string dex = DexFileLoader::GetMultiDexLocation(i, dex_location_.c_str());
586           const OatDexFile* odex_dex_file = odex_file->GetOatDexFile(dex.c_str(), nullptr);
587           if (odex_dex_file == nullptr) {
588             required_dex_checksums_found_ = false;
589             break;
590           }
591           cached_required_dex_checksums_.push_back(odex_dex_file->GetDexFileLocationChecksum());
592         }
593       }
594     }
595   }
596   return required_dex_checksums_found_ ? &cached_required_dex_checksums_ : nullptr;
597 }
598 
ValidateBootClassPathChecksums(const OatFile & oat_file)599 bool OatFileAssistant::ValidateBootClassPathChecksums(const OatFile& oat_file) {
600   // Get the checksums and the BCP from the oat file.
601   const char* oat_boot_class_path_checksums =
602       oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathChecksumsKey);
603   const char* oat_boot_class_path =
604       oat_file.GetOatHeader().GetStoreValueByKey(OatHeader::kBootClassPathKey);
605   if (oat_boot_class_path_checksums == nullptr || oat_boot_class_path == nullptr) {
606     return false;
607   }
608   std::string_view oat_boot_class_path_checksums_view(oat_boot_class_path_checksums);
609   std::string_view oat_boot_class_path_view(oat_boot_class_path);
610   if (oat_boot_class_path_view == cached_boot_class_path_ &&
611       oat_boot_class_path_checksums_view == cached_boot_class_path_checksums_) {
612     return true;
613   }
614 
615   Runtime* runtime = Runtime::Current();
616   std::string error_msg;
617   bool result = gc::space::ImageSpace::VerifyBootClassPathChecksums(
618       oat_boot_class_path_checksums_view,
619       oat_boot_class_path_view,
620       runtime->GetImageLocation(),
621       ArrayRef<const std::string>(runtime->GetBootClassPathLocations()),
622       ArrayRef<const std::string>(runtime->GetBootClassPath()),
623       isa_,
624       runtime->GetImageSpaceLoadingOrder(),
625       &error_msg);
626   if (!result) {
627     VLOG(oat) << "Failed to verify checksums of oat file " << oat_file.GetLocation()
628         << " error: " << error_msg;
629     return false;
630   }
631 
632   // This checksum has been validated, so save it.
633   cached_boot_class_path_ = oat_boot_class_path_view;
634   cached_boot_class_path_checksums_ = oat_boot_class_path_checksums_view;
635   return true;
636 }
637 
GetBestInfo()638 OatFileAssistant::OatFileInfo& OatFileAssistant::GetBestInfo() {
639   ScopedTrace trace("GetBestInfo");
640   // TODO(calin): Document the side effects of class loading when
641   // running dalvikvm command line.
642   if (dex_parent_writable_ || UseFdToReadFiles()) {
643     // If the parent of the dex file is writable it means that we can
644     // create the odex file. In this case we unconditionally pick the odex
645     // as the best oat file. This corresponds to the regular use case when
646     // apps gets installed or when they load private, secondary dex file.
647     // For apps on the system partition the odex location will not be
648     // writable and thus the oat location might be more up to date.
649     return odex_;
650   }
651 
652   // We cannot write to the odex location. This must be a system app.
653 
654   // If the oat location is usable take it.
655   if (oat_.IsUseable()) {
656     return oat_;
657   }
658 
659   // The oat file is not usable but the odex file might be up to date.
660   // This is an indication that we are dealing with an up to date prebuilt
661   // (that doesn't need relocation).
662   if (odex_.Status() == kOatUpToDate) {
663     return odex_;
664   }
665 
666   // We got into the worst situation here:
667   // - the oat location is not usable
668   // - the prebuild odex location is not up to date
669   // - and we don't have the original dex file anymore (stripped).
670   // Pick the odex if it exists, or the oat if not.
671   return (odex_.Status() == kOatCannotOpen) ? oat_ : odex_;
672 }
673 
OpenImageSpace(const OatFile * oat_file)674 std::unique_ptr<gc::space::ImageSpace> OatFileAssistant::OpenImageSpace(const OatFile* oat_file) {
675   DCHECK(oat_file != nullptr);
676   std::string art_file = ReplaceFileExtension(oat_file->GetLocation(), "art");
677   if (art_file.empty()) {
678     return nullptr;
679   }
680   std::string error_msg;
681   ScopedObjectAccess soa(Thread::Current());
682   std::unique_ptr<gc::space::ImageSpace> ret =
683       gc::space::ImageSpace::CreateFromAppImage(art_file.c_str(), oat_file, &error_msg);
684   if (ret == nullptr && (VLOG_IS_ON(image) || OS::FileExists(art_file.c_str()))) {
685     LOG(INFO) << "Failed to open app image " << art_file.c_str() << " " << error_msg;
686   }
687   return ret;
688 }
689 
OatFileInfo(OatFileAssistant * oat_file_assistant,bool is_oat_location)690 OatFileAssistant::OatFileInfo::OatFileInfo(OatFileAssistant* oat_file_assistant,
691                                            bool is_oat_location)
692   : oat_file_assistant_(oat_file_assistant), is_oat_location_(is_oat_location)
693 {}
694 
IsOatLocation()695 bool OatFileAssistant::OatFileInfo::IsOatLocation() {
696   return is_oat_location_;
697 }
698 
Filename()699 const std::string* OatFileAssistant::OatFileInfo::Filename() {
700   return filename_provided_ ? &filename_ : nullptr;
701 }
702 
IsUseable()703 bool OatFileAssistant::OatFileInfo::IsUseable() {
704   ScopedTrace trace("IsUseable");
705   switch (Status()) {
706     case kOatCannotOpen:
707     case kOatDexOutOfDate:
708     case kOatBootImageOutOfDate: return false;
709 
710     case kOatUpToDate: return true;
711   }
712   UNREACHABLE();
713 }
714 
Status()715 OatFileAssistant::OatStatus OatFileAssistant::OatFileInfo::Status() {
716   ScopedTrace trace("Status");
717   if (!status_attempted_) {
718     status_attempted_ = true;
719     const OatFile* file = GetFile();
720     if (file == nullptr) {
721       // Check to see if there is a vdex file we can make use of.
722       std::string error_msg;
723       std::string vdex_filename = GetVdexFilename(filename_);
724       std::unique_ptr<VdexFile> vdex;
725       if (use_fd_) {
726         if (vdex_fd_ >= 0) {
727           struct stat s;
728           int rc = TEMP_FAILURE_RETRY(fstat(vdex_fd_, &s));
729           if (rc == -1) {
730             error_msg = StringPrintf("Failed getting length of the vdex file %s.", strerror(errno));
731           } else {
732             vdex = VdexFile::Open(vdex_fd_,
733                                   s.st_size,
734                                   vdex_filename,
735                                   /*writable=*/ false,
736                                   /*low_4gb=*/ false,
737                                   /*unquicken=*/ false,
738                                   &error_msg);
739           }
740         }
741       } else {
742         vdex = VdexFile::Open(vdex_filename,
743                               /*writable=*/ false,
744                               /*low_4gb=*/ false,
745                               /*unquicken=*/ false,
746                               &error_msg);
747       }
748       if (vdex == nullptr) {
749         status_ = kOatCannotOpen;
750         VLOG(oat) << "unable to open vdex file " << vdex_filename << ": " << error_msg;
751       } else {
752         if (oat_file_assistant_->DexChecksumUpToDate(*vdex, &error_msg)) {
753           // The vdex file does not contain enough information to determine
754           // whether it is up to date with respect to the boot image, so we
755           // assume it is out of date.
756           VLOG(oat) << error_msg;
757           status_ = kOatBootImageOutOfDate;
758         } else {
759           status_ = kOatDexOutOfDate;
760         }
761       }
762     } else {
763       status_ = oat_file_assistant_->GivenOatFileStatus(*file);
764       VLOG(oat) << file->GetLocation() << " is " << status_
765           << " with filter " << file->GetCompilerFilter();
766     }
767   }
768   return status_;
769 }
770 
GetDexOptNeeded(CompilerFilter::Filter target,ClassLoaderContext * context,const std::vector<int> & context_fds,bool profile_changed,bool downgrade)771 OatFileAssistant::DexOptNeeded OatFileAssistant::OatFileInfo::GetDexOptNeeded(
772     CompilerFilter::Filter target,
773     ClassLoaderContext* context,
774     const std::vector<int>& context_fds,
775     bool profile_changed,
776     bool downgrade) {
777 
778   bool filter_okay = CompilerFilterIsOkay(target, profile_changed, downgrade);
779   bool class_loader_context_okay = ClassLoaderContextIsOkay(context, context_fds);
780 
781   // Only check the filter and relocation if the class loader context is ok.
782   // If it is not, we will return kDex2OatFromScratch as the compilation needs to be redone.
783   if (class_loader_context_okay) {
784     if (filter_okay && Status() == kOatUpToDate) {
785       // The oat file is in good shape as is.
786       return kNoDexOptNeeded;
787     }
788 
789     if (IsUseable()) {
790       return kDex2OatForFilter;
791     }
792 
793     if (Status() == kOatBootImageOutOfDate) {
794       return kDex2OatForBootImage;
795     }
796   }
797 
798   if (oat_file_assistant_->HasDexFiles()) {
799     return kDex2OatFromScratch;
800   } else {
801     // No dex file, there is nothing we need to do.
802     return kNoDexOptNeeded;
803   }
804 }
805 
GetFile()806 const OatFile* OatFileAssistant::OatFileInfo::GetFile() {
807   CHECK(!file_released_) << "GetFile called after oat file released.";
808   if (!load_attempted_) {
809     load_attempted_ = true;
810     if (filename_provided_) {
811       bool executable = oat_file_assistant_->load_executable_;
812       if (executable && oat_file_assistant_->only_load_system_executable_) {
813         executable = LocationIsOnSystem(filename_.c_str());
814       }
815       VLOG(oat) << "Loading " << filename_ << " with executable: " << executable;
816       std::string error_msg;
817       if (use_fd_) {
818         if (oat_fd_ >= 0 && vdex_fd_ >= 0) {
819           ArrayRef<const std::string> dex_locations(&oat_file_assistant_->dex_location_,
820                                                     /*size=*/ 1u);
821           file_.reset(OatFile::Open(zip_fd_,
822                                     vdex_fd_,
823                                     oat_fd_,
824                                     filename_.c_str(),
825                                     executable,
826                                     /*low_4gb=*/ false,
827                                     dex_locations,
828                                     /*reservation=*/ nullptr,
829                                     &error_msg));
830         }
831       } else {
832         file_.reset(OatFile::Open(/*zip_fd=*/ -1,
833                                   filename_.c_str(),
834                                   filename_.c_str(),
835                                   executable,
836                                   /*low_4gb=*/ false,
837                                   oat_file_assistant_->dex_location_,
838                                   &error_msg));
839       }
840       if (file_.get() == nullptr) {
841         VLOG(oat) << "OatFileAssistant test for existing oat file "
842           << filename_ << ": " << error_msg;
843       } else {
844         VLOG(oat) << "Successfully loaded " << filename_ << " with executable: " << executable;
845       }
846     }
847   }
848   return file_.get();
849 }
850 
CompilerFilterIsOkay(CompilerFilter::Filter target,bool profile_changed,bool downgrade)851 bool OatFileAssistant::OatFileInfo::CompilerFilterIsOkay(
852     CompilerFilter::Filter target, bool profile_changed, bool downgrade) {
853   const OatFile* file = GetFile();
854   if (file == nullptr) {
855     return false;
856   }
857 
858   CompilerFilter::Filter current = file->GetCompilerFilter();
859   if (profile_changed && CompilerFilter::DependsOnProfile(current)) {
860     VLOG(oat) << "Compiler filter not okay because Profile changed";
861     return false;
862   }
863   return downgrade ? !CompilerFilter::IsBetter(current, target) :
864     CompilerFilter::IsAsGoodAs(current, target);
865 }
866 
ClassLoaderContextIsOkay(ClassLoaderContext * context,const std::vector<int> & context_fds)867 bool OatFileAssistant::OatFileInfo::ClassLoaderContextIsOkay(ClassLoaderContext* context,
868                                                              const std::vector<int>& context_fds) {
869   const OatFile* file = GetFile();
870   if (file == nullptr) {
871     // No oat file means we have nothing to verify.
872     return true;
873   }
874 
875   if (!CompilerFilter::IsVerificationEnabled(file->GetCompilerFilter())) {
876     // If verification is not enabled we don't need to verify the class loader context and we
877     // assume it's ok.
878     return true;
879   }
880 
881 
882   if (context == nullptr) {
883     // TODO(calin): stop using null for the unkown contexts.
884     // b/148494302 introduces runtime encoding for unknown context which will make this possible.
885     VLOG(oat) << "ClassLoaderContext check failed: uknown(null) context";
886     return false;
887   }
888 
889   size_t dir_index = oat_file_assistant_->dex_location_.rfind('/');
890   std::string classpath_dir = (dir_index != std::string::npos)
891       ? oat_file_assistant_->dex_location_.substr(0, dir_index)
892       : "";
893 
894   if (!context->OpenDexFiles(oat_file_assistant_->isa_, classpath_dir, context_fds)) {
895     VLOG(oat) << "ClassLoaderContext check failed: dex files from the context could not be opened";
896     return false;
897   }
898 
899   const bool result = context->VerifyClassLoaderContextMatch(file->GetClassLoaderContext()) !=
900       ClassLoaderContext::VerificationResult::kMismatch;
901   if (!result) {
902     VLOG(oat) << "ClassLoaderContext check failed. Context was "
903               << file->GetClassLoaderContext()
904               << ". The expected context is " << context->EncodeContextForOatFile(classpath_dir);
905   }
906   return result;
907 }
908 
IsExecutable()909 bool OatFileAssistant::OatFileInfo::IsExecutable() {
910   const OatFile* file = GetFile();
911   return (file != nullptr && file->IsExecutable());
912 }
913 
Reset()914 void OatFileAssistant::OatFileInfo::Reset() {
915   load_attempted_ = false;
916   file_.reset();
917   status_attempted_ = false;
918 }
919 
Reset(const std::string & filename,bool use_fd,int zip_fd,int vdex_fd,int oat_fd)920 void OatFileAssistant::OatFileInfo::Reset(const std::string& filename,
921                                           bool use_fd,
922                                           int zip_fd,
923                                           int vdex_fd,
924                                           int oat_fd) {
925   filename_provided_ = true;
926   filename_ = filename;
927   use_fd_ = use_fd;
928   zip_fd_ = zip_fd;
929   vdex_fd_ = vdex_fd;
930   oat_fd_ = oat_fd;
931   Reset();
932 }
933 
ReleaseFile()934 std::unique_ptr<OatFile> OatFileAssistant::OatFileInfo::ReleaseFile() {
935   file_released_ = true;
936   return std::move(file_);
937 }
938 
ReleaseFileForUse()939 std::unique_ptr<OatFile> OatFileAssistant::OatFileInfo::ReleaseFileForUse() {
940   ScopedTrace trace("ReleaseFileForUse");
941   if (Status() == kOatUpToDate) {
942     return ReleaseFile();
943   }
944 
945   return std::unique_ptr<OatFile>();
946 }
947 
948 // TODO(calin): we could provide a more refined status here
949 // (e.g. run from uncompressed apk, run with vdex but not oat etc). It will allow us to
950 // track more experiments but adds extra complexity.
GetOptimizationStatus(const std::string & filename,InstructionSet isa,std::string * out_compilation_filter,std::string * out_compilation_reason)951 void OatFileAssistant::GetOptimizationStatus(
952     const std::string& filename,
953     InstructionSet isa,
954     std::string* out_compilation_filter,
955     std::string* out_compilation_reason) {
956   // It may not be possible to load an oat file executable (e.g., selinux restrictions). Load
957   // non-executable and check the status manually.
958   OatFileAssistant oat_file_assistant(filename.c_str(), isa, /*load_executable=*/ false);
959   std::unique_ptr<OatFile> oat_file = oat_file_assistant.GetBestOatFile();
960 
961   if (oat_file == nullptr) {
962     *out_compilation_filter = "run-from-apk";
963     *out_compilation_reason = "unknown";
964     return;
965   }
966 
967   OatStatus status = oat_file_assistant.GivenOatFileStatus(*oat_file);
968   const char* reason = oat_file->GetCompilationReason();
969   *out_compilation_reason = reason == nullptr ? "unknown" : reason;
970   switch (status) {
971     case OatStatus::kOatUpToDate:
972       *out_compilation_filter = CompilerFilter::NameOfFilter(oat_file->GetCompilerFilter());
973       return;
974 
975     case kOatCannotOpen:  // This should never happen, but be robust.
976       *out_compilation_filter = "error";
977       *out_compilation_reason = "error";
978       return;
979 
980     // kOatBootImageOutOfDate - The oat file is up to date with respect to the
981     // dex file, but is out of date with respect to the boot image.
982     case kOatBootImageOutOfDate:
983       FALLTHROUGH_INTENDED;
984     case kOatDexOutOfDate:
985       DCHECK(oat_file_assistant.HasDexFiles());
986       *out_compilation_filter = "run-from-apk-fallback";
987       return;
988   }
989   LOG(FATAL) << "Unreachable";
990   UNREACHABLE();
991 }
992 
993 }  // namespace art
994