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