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 #ifndef ART_RUNTIME_OAT_OAT_FILE_ASSISTANT_H_ 18 #define ART_RUNTIME_OAT_OAT_FILE_ASSISTANT_H_ 19 20 #include <cstdint> 21 #include <memory> 22 #include <optional> 23 #include <sstream> 24 #include <string> 25 #include <string_view> 26 #include <variant> 27 28 #include "arch/instruction_set.h" 29 #include "base/compiler_filter.h" 30 #include "base/macros.h" 31 #include "base/os.h" 32 #include "base/scoped_flock.h" 33 #include "base/unix_file/fd_file.h" 34 #include "class_loader_context.h" 35 #include "oat_file.h" 36 #include "oat_file_assistant_context.h" 37 38 namespace art HIDDEN { 39 40 namespace gc { 41 namespace space { 42 class ImageSpace; 43 } // namespace space 44 } // namespace gc 45 46 // Class for assisting with oat file management. 47 // 48 // This class collects common utilities for determining the status of an oat 49 // file on the device, updating the oat file, and loading the oat file. 50 // 51 // The oat file assistant is intended to be used with dex locations not on the 52 // boot class path. See the IsInBootClassPath method for a way to check if the 53 // dex location is in the boot class path. 54 class OatFileAssistant { 55 public: 56 enum DexOptNeeded { 57 // No dexopt should (or can) be done to update the apk/jar. 58 // Matches Java: dalvik.system.DexFile.NO_DEXOPT_NEEDED = 0 59 kNoDexOptNeeded = 0, 60 61 // dex2oat should be run to update the apk/jar from scratch. 62 // Matches Java: dalvik.system.DexFile.DEX2OAT_FROM_SCRATCH = 1 63 kDex2OatFromScratch = 1, 64 65 // dex2oat should be run to update the apk/jar because the existing code 66 // is out of date with respect to the boot image. 67 // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_BOOT_IMAGE 68 kDex2OatForBootImage = 2, 69 70 // dex2oat should be run to update the apk/jar because the existing code 71 // is out of date with respect to the target compiler filter. 72 // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_FILTER 73 kDex2OatForFilter = 3, 74 }; 75 76 enum OatStatus { 77 // kOatCannotOpen - The oat file cannot be opened, because it does not 78 // exist, is unreadable, or otherwise corrupted. 79 kOatCannotOpen, 80 81 // kOatDexOutOfDate - The oat file is out of date with respect to the dex file. 82 kOatDexOutOfDate, 83 84 // kOatBootImageOutOfDate - The oat file is up to date with respect to the 85 // dex file, but is out of date with respect to the boot image. 86 kOatBootImageOutOfDate, 87 88 // kOatContextOutOfDate - The context in the oat file is out of date with 89 // respect to the class loader context. 90 kOatContextOutOfDate, 91 92 // kOatUpToDate - The oat file is completely up to date with respect to 93 // the dex file and boot image. 94 kOatUpToDate, 95 }; 96 97 // A bit field to represent the conditions where dexopt should be performed. 98 struct DexOptTrigger { 99 // Dexopt should be performed if the target compiler filter is better than the current compiler 100 // filter. See `CompilerFilter::IsBetter`. 101 bool targetFilterIsBetter : 1; 102 // Dexopt should be performed if the target compiler filter is the same as the current compiler 103 // filter. 104 bool targetFilterIsSame : 1; 105 // Dexopt should be performed if the target compiler filter is worse than the current compiler 106 // filter. See `CompilerFilter::IsBetter`. 107 bool targetFilterIsWorse : 1; 108 // Dexopt should be performed if the current oat file was compiled without a primary image, 109 // and the runtime is now running with a primary image loaded from disk. 110 bool primaryBootImageBecomesUsable : 1; 111 // Dexopt should be performed if the APK is compressed and the current oat/vdex file doesn't 112 // contain dex code. 113 bool needExtraction : 1; 114 }; 115 116 // Represents the location of the current oat file and/or vdex file. 117 enum Location { 118 // Does not exist, or an error occurs. 119 kLocationNoneOrError = 0, 120 // In the global "dalvik-cache" folder. 121 kLocationOat = 1, 122 // In the "oat" folder next to the dex file. 123 kLocationOdex = 2, 124 // In the DM file. This means the only usable file is the vdex file. 125 kLocationDm = 3, 126 }; 127 128 // Represents the status of the current oat file and/or vdex file. 129 class DexOptStatus { 130 public: GetLocation()131 Location GetLocation() { return location_; } IsVdexUsable()132 bool IsVdexUsable() { return location_ != kLocationNoneOrError; } 133 134 private: 135 Location location_ = kLocationNoneOrError; 136 friend class OatFileAssistant; 137 }; 138 139 // Constructs an OatFileAssistant object to assist the oat file 140 // corresponding to the given dex location with the target instruction set. 141 // 142 // The dex_location must not be null and should remain available and 143 // unchanged for the duration of the lifetime of the OatFileAssistant object. 144 // Typically the dex_location is the absolute path to the original, 145 // un-optimized dex file. 146 // 147 // Note: Currently the dex_location must have an extension. 148 // TODO: Relax this restriction? 149 // 150 // The isa should be either the 32 bit or 64 bit variant for the current 151 // device. For example, on an arm device, use arm or arm64. An oat file can 152 // be loaded executable only if the ISA matches the current runtime. 153 // 154 // context should be the class loader context to check against, or null to skip the check. 155 // 156 // load_executable should be true if the caller intends to try and load 157 // executable code for this dex location. 158 // 159 // only_load_trusted_executable should be true if the caller intends to have 160 // only oat files from trusted locations loaded executable. See IsTrustedLocation() for 161 // details on trusted locations. 162 // 163 // runtime_options should be provided with all the required fields filled if the caller intends to 164 // use OatFileAssistant without a runtime. 165 EXPORT OatFileAssistant(const char* dex_location, 166 const InstructionSet isa, 167 ClassLoaderContext* context, 168 bool load_executable, 169 bool only_load_trusted_executable = false, 170 OatFileAssistantContext* ofa_context = nullptr); 171 172 // Similar to this(const char*, const InstructionSet, bool), however, if a valid zip_fd is 173 // provided, vdex, oat, and zip files will be read from vdex_fd, oat_fd and zip_fd respectively. 174 // Otherwise, dex_location will be used to construct necessary filenames. 175 EXPORT OatFileAssistant(const char* dex_location, 176 const InstructionSet isa, 177 ClassLoaderContext* context, 178 bool load_executable, 179 bool only_load_trusted_executable, 180 OatFileAssistantContext* ofa_context, 181 int vdex_fd, 182 int oat_fd, 183 int zip_fd); 184 185 // A convenient factory function that accepts ISA, class loader context, and compiler filter in 186 // strings. Returns the created instance and ClassLoaderContext on success, or returns nullptr and 187 // outputs an error message if it fails to parse the input strings. 188 // The returned ClassLoaderContext must live at least as long as the OatFileAssistant. 189 EXPORT static std::unique_ptr<OatFileAssistant> Create( 190 const std::string& filename, 191 const std::string& isa_str, 192 const std::optional<std::string>& context_str, 193 bool load_executable, 194 bool only_load_trusted_executable, 195 OatFileAssistantContext* ofa_context, 196 /*out*/ std::unique_ptr<ClassLoaderContext>* context, 197 /*out*/ std::string* error_msg); 198 199 // Returns true if the dex location refers to an element of the boot class 200 // path. 201 EXPORT bool IsInBootClassPath(); 202 203 // Return what action needs to be taken to produce up-to-date code for this 204 // dex location. If "downgrade" is set to false, it verifies if the current 205 // compiler filter is at least as good as an oat file generated with the 206 // given compiler filter otherwise, if its set to true, it checks whether 207 // the oat file generated with the target filter will be downgraded as 208 // compared to the current state. For example, if the current compiler filter is verify and the 209 // target filter is speed profile it will recommend to keep it in its current state. 210 // profile_changed should be true to indicate the profile has recently changed 211 // for this dex location. 212 // If the purpose of the dexopt is to downgrade the compiler filter, 213 // set downgrade to true. 214 // Returns a positive status code if the status refers to the oat file in 215 // the oat location. Returns a negative status code if the status refers to 216 // the oat file in the odex location. 217 // 218 // Deprecated. Use the other overload. 219 EXPORT int GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter, 220 bool profile_changed = false, 221 bool downgrade = false); 222 223 // Returns true if dexopt needs to be performed with respect to the given target compilation 224 // filter and dexopt trigger. Also returns the status of the current oat file and/or vdex file. 225 EXPORT bool GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter, 226 const DexOptTrigger dexopt_trigger, 227 /*out*/ DexOptStatus* dexopt_status); 228 229 // Returns true if there is up-to-date code for this dex location, 230 // irrespective of the compiler filter of the up-to-date code. 231 bool IsUpToDate(); 232 233 // Returns an oat file that can be used for loading dex files. 234 // Returns null if no suitable oat file was found. 235 // 236 // After this call, no other methods of the OatFileAssistant should be 237 // called, because access to the loaded oat file has been taken away from 238 // the OatFileAssistant object. 239 std::unique_ptr<OatFile> GetBestOatFile(); 240 241 // Returns a human readable description of the status of the code for the 242 // dex file. The returned description is for debugging purposes only. 243 std::string GetStatusDump(); 244 245 // Computes the optimization status of the given dex file. The result is 246 // returned via the two output parameters. 247 // - out_odex_location: the location of the (best) odex that will be used 248 // for loading. See GetBestInfo(). 249 // - out_compilation_filter: the level of optimizations (compiler filter) 250 // - out_compilation_reason: the optimization reason. The reason might 251 // be "unknown" if the compiler artifacts were not annotated during optimizations. 252 // - out_odex_status: a human readable refined status of the validity of the odex file. 253 // Possible values are: "up-to-date", "apk-more-recent", and "io-error-no-oat". 254 // 255 // This method will try to mimic the runtime effect of loading the dex file. 256 // For example, if there is no usable oat file, the compiler filter will be set 257 // to "run-from-apk". 258 EXPORT void GetOptimizationStatus(std::string* out_odex_location, 259 std::string* out_compilation_filter, 260 std::string* out_compilation_reason, 261 std::string* out_odex_status, 262 Location* out_location); 263 264 static void GetOptimizationStatus(const std::string& filename, 265 InstructionSet isa, 266 std::string* out_compilation_filter, 267 std::string* out_compilation_reason, 268 OatFileAssistantContext* ofa_context = nullptr); 269 270 // Open and returns an image space associated with the oat file. 271 static std::unique_ptr<gc::space::ImageSpace> OpenImageSpace(const OatFile* oat_file); 272 273 // Loads the dex files in the given oat file for the given dex location. 274 // The oat file should be up to date for the given dex location. 275 // This loads multiple dex files in the case of multidex. 276 // Returns an empty vector if no dex files for that location could be loaded 277 // from the oat file. 278 // 279 // The caller is responsible for freeing the dex_files returned, if any. The 280 // dex_files will only remain valid as long as the oat_file is valid. 281 static std::vector<std::unique_ptr<const DexFile>> LoadDexFiles( 282 const OatFile& oat_file, const char* dex_location); 283 284 // Same as `std::vector<std::unique_ptr<const DexFile>> LoadDexFiles(...)` with the difference: 285 // - puts the dex files in the given vector 286 // - returns whether or not all dex files were successfully opened 287 static bool LoadDexFiles(const OatFile& oat_file, 288 const std::string& dex_location, 289 std::vector<std::unique_ptr<const DexFile>>* out_dex_files); 290 291 // Returns whether this is an apk/zip wit a classes.dex entry, or nullopt if an error occurred. 292 EXPORT std::optional<bool> HasDexFiles(std::string* error_msg); 293 294 // If the dex file has been installed with a compiled oat file alongside 295 // it, the compiled oat file will have the extension .odex, and is referred 296 // to as the odex file. It is called odex for legacy reasons; the file is 297 // really an oat file. The odex file will often, but not always, have a 298 // patch delta of 0 and need to be relocated before use for the purposes of 299 // ASLR. The odex file is treated as if it were read-only. 300 // 301 // Returns the status of the odex file for the dex location. 302 OatStatus OdexFileStatus(); 303 304 // When the dex files is compiled on the target device, the oat file is the 305 // result. The oat file will have been relocated to some 306 // (possibly-out-of-date) offset for ASLR. 307 // 308 // Returns the status of the oat file for the dex location. 309 OatStatus OatFileStatus(); 310 GetBestStatus()311 OatStatus GetBestStatus() { 312 return GetBestInfo().Status(); 313 } 314 315 // Constructs the odex file name for the given dex location. 316 // Returns true on success, in which case odex_filename is set to the odex 317 // file name. 318 // Returns false on error, in which case error_msg describes the error and 319 // odex_filename is not changed. 320 // Neither odex_filename nor error_msg may be null. 321 EXPORT static bool DexLocationToOdexFilename(const std::string& location, 322 InstructionSet isa, 323 std::string* odex_filename, 324 std::string* error_msg); 325 326 // Constructs the oat file name for the given dex location. 327 // Returns true on success, in which case oat_filename is set to the oat 328 // file name. 329 // Returns false on error, in which case error_msg describes the error and 330 // oat_filename is not changed. 331 // Neither oat_filename nor error_msg may be null. 332 // 333 // Calling this function requires an active runtime. 334 static bool DexLocationToOatFilename(const std::string& location, 335 InstructionSet isa, 336 std::string* oat_filename, 337 std::string* error_msg); 338 339 // Same as above, but also takes `deny_art_apex_data_files` from input. 340 // 341 // Calling this function does not require an active runtime. 342 EXPORT static bool DexLocationToOatFilename(const std::string& location, 343 InstructionSet isa, 344 bool deny_art_apex_data_files, 345 std::string* oat_filename, 346 std::string* error_msg); 347 348 // Computes the dex location and vdex filename. If the data directory of the process 349 // is known, creates an absolute path in that directory and tries to infer path 350 // of a corresponding vdex file. Otherwise only creates a basename dex_location 351 // from the combined checksums. Returns true if all out-arguments have been set. 352 // 353 // Calling this function requires an active runtime. 354 static bool AnonymousDexVdexLocation(const std::vector<const DexFile::Header*>& dex_headers, 355 InstructionSet isa, 356 /* out */ std::string* dex_location, 357 /* out */ std::string* vdex_filename); 358 359 // Returns true if a filename (given as basename) is a name of a vdex for 360 // anonymous dex file(s) created by AnonymousDexVdexLocation. 361 EXPORT static bool IsAnonymousVdexBasename(const std::string& basename); 362 363 bool ClassLoaderContextIsOkay(const OatFile& oat_file) const; 364 365 // Validates the boot class path checksum of an OatFile. 366 EXPORT bool ValidateBootClassPathChecksums(const OatFile& oat_file); 367 368 // Validates the given bootclasspath and bootclasspath checksums found in an oat header. 369 static bool ValidateBootClassPathChecksums(OatFileAssistantContext* ofa_context, 370 InstructionSet isa, 371 std::string_view oat_checksums, 372 std::string_view oat_boot_class_path, 373 /*out*/ std::string* error_msg); 374 375 private: 376 class OatFileInfo { 377 public: 378 // Initially the info is for no file in particular. It will treat the 379 // file as out of date until Reset is called with a real filename to use 380 // the cache for. 381 // Pass true for is_oat_location if the information associated with this 382 // OatFileInfo is for the oat location, as opposed to the odex location. 383 OatFileInfo(OatFileAssistant* oat_file_assistant, bool is_oat_location); 384 385 bool IsOatLocation(); 386 387 const std::string* Filename(); 388 389 const char* DisplayFilename(); 390 391 // Returns true if this oat file can be used for running code. The oat 392 // file can be used for running code as long as it is not out of date with 393 // respect to the dex code or boot image. An oat file that is out of date 394 // with respect to relocation is considered useable, because it's possible 395 // to interpret the dex code rather than run the unrelocated compiled 396 // code. 397 bool IsUseable(); 398 399 // Returns the status of this oat file. 400 OatStatus Status(); 401 402 // Return the DexOptNeeded value for this oat file with respect to the given target compilation 403 // filter and dexopt trigger. 404 DexOptNeeded GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter, 405 const DexOptTrigger dexopt_trigger); 406 407 // Returns the loaded file. 408 // Loads the file if needed. Returns null if the file failed to load. 409 // The caller shouldn't clean up or free the returned pointer. 410 const OatFile* GetFile(); 411 412 // Returns true if the file is opened executable. 413 bool IsExecutable(); 414 415 // Clear any cached information about the file that depends on the 416 // contents of the file. This does not reset the provided filename. 417 void Reset(); 418 419 // Clear any cached information and switch to getting info about the oat 420 // file with the given filename. 421 void Reset(const std::string& filename, 422 bool use_fd, 423 int zip_fd = -1, 424 int vdex_fd = -1, 425 int oat_fd = -1); 426 427 // Release the loaded oat file for runtime use. 428 // Returns null if the oat file hasn't been loaded or is out of date. 429 // Ensures the returned file is not loaded executable if it has unuseable 430 // compiled code. 431 // 432 // After this call, no other methods of the OatFileInfo should be 433 // called, because access to the loaded oat file has been taken away from 434 // the OatFileInfo object. 435 std::unique_ptr<OatFile> ReleaseFileForUse(); 436 437 // Check if we should reject vdex containing cdex code as part of the cdex 438 // deprecation. 439 // TODO(b/256664509): Clean this up. 440 bool CheckDisableCompactDex(); 441 442 private: 443 // Returns true if the oat file is usable but at least one dexopt trigger is matched. This 444 // function should only be called if the oat file is usable. 445 bool ShouldRecompileForFilter(CompilerFilter::Filter target, 446 const DexOptTrigger dexopt_trigger); 447 448 // Release the loaded oat file. 449 // Returns null if the oat file hasn't been loaded. 450 // 451 // After this call, no other methods of the OatFileInfo should be 452 // called, because access to the loaded oat file has been taken away from 453 // the OatFileInfo object. 454 std::unique_ptr<OatFile> ReleaseFile(); 455 456 OatFileAssistant* oat_file_assistant_; 457 const bool is_oat_location_; 458 459 bool filename_provided_ = false; 460 std::string filename_; 461 462 int zip_fd_ = -1; 463 int oat_fd_ = -1; 464 int vdex_fd_ = -1; 465 bool use_fd_ = false; 466 467 bool load_attempted_ = false; 468 std::unique_ptr<OatFile> file_; 469 470 bool status_attempted_ = false; 471 OatStatus status_ = OatStatus::kOatCannotOpen; 472 473 // For debugging only. 474 // If this flag is set, the file has been released to the user and the 475 // OatFileInfo object is in a bad state and should no longer be used. 476 bool file_released_ = false; 477 }; 478 479 // Return info for the best oat file. 480 OatFileInfo& GetBestInfo(); 481 482 // Returns true when vdex/oat/odex files should be read from file descriptors. 483 // The method checks the value of zip_fd_, and if the value is valid, returns 484 // true. This is required to have a deterministic behavior around how different 485 // files are being read. 486 bool UseFdToReadFiles(); 487 488 // Returns true if the dex checksums in the given oat file are up to date 489 // with respect to the dex location. If the dex checksums are not up to 490 // date, error_msg is updated with a message describing the problem. 491 bool DexChecksumUpToDate(const OatFile& file, std::string* error_msg); 492 493 // Return the status for a given opened oat file with respect to the dex 494 // location. 495 OatStatus GivenOatFileStatus(const OatFile& file); 496 497 // Gets the dex checksum required for an up-to-date oat file. 498 // Returns cached result from GetMultiDexChecksum. 499 bool GetRequiredDexChecksum(std::optional<uint32_t>* checksum, std::string* error); 500 501 // Returns whether there is at least one boot image usable. 502 bool IsPrimaryBootImageUsable(); 503 504 // Returns the trigger for the deprecated overload of `GetDexOptNeeded`. 505 // 506 // Deprecated. Do not use in new code. 507 DexOptTrigger GetDexOptTrigger(CompilerFilter::Filter target_compiler_filter, 508 bool profile_changed, 509 bool downgrade); 510 511 // Returns the pointer to the owned or unowned instance of OatFileAssistantContext. GetOatFileAssistantContext()512 OatFileAssistantContext* GetOatFileAssistantContext() { 513 if (std::holds_alternative<OatFileAssistantContext*>(ofa_context_)) { 514 return std::get<OatFileAssistantContext*>(ofa_context_); 515 } else { 516 return std::get<std::unique_ptr<OatFileAssistantContext>>(ofa_context_).get(); 517 } 518 } 519 520 // The runtime options taken from the active runtime or the input. 521 // 522 // All member functions should get runtime options from this variable rather than referencing the 523 // active runtime. This is to allow OatFileAssistant to function without an active runtime. GetRuntimeOptions()524 const OatFileAssistantContext::RuntimeOptions& GetRuntimeOptions() { 525 return GetOatFileAssistantContext()->GetRuntimeOptions(); 526 } 527 528 // Returns whether the zip file only contains uncompressed dex. 529 bool ZipFileOnlyContainsUncompressedDex(); 530 531 // Returns the location of the given oat file. 532 Location GetLocation(OatFileInfo& info); 533 534 std::string dex_location_; 535 536 // The class loader context to check against, or null representing that the check should be 537 // skipped. 538 ClassLoaderContext* context_; 539 540 // Whether or not the parent directory of the dex file is writable. 541 bool dex_parent_writable_ = false; 542 543 // In a properly constructed OatFileAssistant object, isa_ should be either 544 // the 32 or 64 bit variant for the current device. 545 const InstructionSet isa_ = InstructionSet::kNone; 546 547 // Whether we will attempt to load oat files executable. 548 bool load_executable_ = false; 549 550 // Whether only oat files from trusted locations are loaded executable. 551 const bool only_load_trusted_executable_ = false; 552 553 // Cached value of whether the potential zip file only contains uncompressed dex. 554 // This should be accessed only by the ZipFileOnlyContainsUncompressedDex() method. 555 bool zip_file_only_contains_uncompressed_dex_ = true; 556 557 // Cached value of the required dex checksums. 558 // This should be accessed only by the GetRequiredDexChecksums() method. 559 std::optional<uint32_t> cached_required_dex_checksums_; 560 std::optional<std::string> cached_required_dex_checksums_error_; 561 bool required_dex_checksums_attempted_ = false; 562 563 // The AOT-compiled file of an app when the APK of the app is in /data. 564 OatFileInfo odex_; 565 // The AOT-compiled file of an app when the APK of the app is on a read-only partition 566 // (for example /system). 567 OatFileInfo oat_; 568 569 // The vdex-only file next to `odex_` when `odex_' cannot be used (for example 570 // it is out of date). 571 OatFileInfo vdex_for_odex_; 572 // The vdex-only file next to 'oat_` when `oat_' cannot be used (for example 573 // it is out of date). 574 OatFileInfo vdex_for_oat_; 575 576 // The vdex-only file next to the apk. 577 OatFileInfo dm_for_odex_; 578 OatFileInfo dm_for_oat_; 579 580 // File descriptor corresponding to apk, dex file, or zip. 581 int zip_fd_; 582 583 // Owned or unowned instance of OatFileAssistantContext. 584 std::variant<std::unique_ptr<OatFileAssistantContext>, OatFileAssistantContext*> ofa_context_; 585 586 friend class OatFileAssistantTest; 587 588 DISALLOW_COPY_AND_ASSIGN(OatFileAssistant); 589 }; 590 591 std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status); 592 593 } // namespace art 594 595 #endif // ART_RUNTIME_OAT_OAT_FILE_ASSISTANT_H_ 596