Home | History | Annotate | Download | only in runtime
      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_FILE_ASSISTANT_H_
     18 #define ART_RUNTIME_OAT_FILE_ASSISTANT_H_
     19 
     20 #include <cstdint>
     21 #include <memory>
     22 #include <sstream>
     23 #include <string>
     24 
     25 #include "arch/instruction_set.h"
     26 #include "base/scoped_flock.h"
     27 #include "base/unix_file/fd_file.h"
     28 #include "compiler_filter.h"
     29 #include "class_loader_context.h"
     30 #include "oat_file.h"
     31 #include "os.h"
     32 
     33 namespace art {
     34 
     35 namespace gc {
     36 namespace space {
     37 class ImageSpace;
     38 }  // namespace space
     39 }  // namespace gc
     40 
     41 // Class for assisting with oat file management.
     42 //
     43 // This class collects common utilities for determining the status of an oat
     44 // file on the device, updating the oat file, and loading the oat file.
     45 //
     46 // The oat file assistant is intended to be used with dex locations not on the
     47 // boot class path. See the IsInBootClassPath method for a way to check if the
     48 // dex location is in the boot class path.
     49 class OatFileAssistant {
     50  public:
     51   // The default compile filter to use when optimizing dex file at load time if they
     52   // are out of date.
     53   static const CompilerFilter::Filter kDefaultCompilerFilterForDexLoading =
     54       CompilerFilter::kQuicken;
     55 
     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     // dex2oat should be run to update the apk/jar because the existing code
     76     // is not relocated to match the boot image.
     77     // Matches Java: dalvik.system.DexFile.DEX2OAT_FOR_RELOCATION
     78     kDex2OatForRelocation = 4,
     79   };
     80 
     81   enum OatStatus {
     82     // kOatCannotOpen - The oat file cannot be opened, because it does not
     83     // exist, is unreadable, or otherwise corrupted.
     84     kOatCannotOpen,
     85 
     86     // kOatDexOutOfDate - The oat file is out of date with respect to the dex file.
     87     kOatDexOutOfDate,
     88 
     89     // kOatBootImageOutOfDate - The oat file is up to date with respect to the
     90     // dex file, but is out of date with respect to the boot image.
     91     kOatBootImageOutOfDate,
     92 
     93     // kOatRelocationOutOfDate - The oat file is up to date with respect to
     94     // the dex file and boot image, but contains compiled code that has the
     95     // wrong patch delta with respect to the boot image. Patchoat should be
     96     // run on the oat file to update the patch delta of the compiled code to
     97     // match the boot image.
     98     kOatRelocationOutOfDate,
     99 
    100     // kOatUpToDate - The oat file is completely up to date with respect to
    101     // the dex file and boot image.
    102     kOatUpToDate,
    103   };
    104 
    105   // Constructs an OatFileAssistant object to assist the oat file
    106   // corresponding to the given dex location with the target instruction set.
    107   //
    108   // The dex_location must not be null and should remain available and
    109   // unchanged for the duration of the lifetime of the OatFileAssistant object.
    110   // Typically the dex_location is the absolute path to the original,
    111   // un-optimized dex file.
    112   //
    113   // Note: Currently the dex_location must have an extension.
    114   // TODO: Relax this restriction?
    115   //
    116   // The isa should be either the 32 bit or 64 bit variant for the current
    117   // device. For example, on an arm device, use arm or arm64. An oat file can
    118   // be loaded executable only if the ISA matches the current runtime.
    119   //
    120   // load_executable should be true if the caller intends to try and load
    121   // executable code for this dex location.
    122   OatFileAssistant(const char* dex_location,
    123                    const InstructionSet isa,
    124                    bool load_executable);
    125 
    126   ~OatFileAssistant();
    127 
    128   // Returns true if the dex location refers to an element of the boot class
    129   // path.
    130   bool IsInBootClassPath();
    131 
    132   // Obtains a lock on the target oat file.
    133   // Only one OatFileAssistant object can hold the lock for a target oat file
    134   // at a time. The Lock is released automatically when the OatFileAssistant
    135   // object goes out of scope. The Lock() method must not be called if the
    136   // lock has already been acquired.
    137   //
    138   // Returns true on success.
    139   // Returns false on error, in which case error_msg will contain more
    140   // information on the error.
    141   //
    142   // The 'error_msg' argument must not be null.
    143   //
    144   // This is intended to be used to avoid race conditions when multiple
    145   // processes generate oat files, such as when a foreground Activity and
    146   // a background Service both use DexClassLoaders pointing to the same dex
    147   // file.
    148   bool Lock(std::string* error_msg);
    149 
    150   // Return what action needs to be taken to produce up-to-date code for this
    151   // dex location. If "downgrade" is set to false, it verifies if the current
    152   // compiler filter is at least as good as an oat file generated with the
    153   // given compiler filter otherwise, if its set to true, it checks whether
    154   // the oat file generated with the target filter will be downgraded as
    155   // compared to the current state. For example, if the current compiler filter is
    156   // quicken, and target filter is verify, it will recommend to dexopt, while
    157   // if the target filter is speed profile, it will recommend to keep it in its
    158   // current state.
    159   // profile_changed should be true to indicate the profile has recently changed
    160   // for this dex location.
    161   // If the purpose of the dexopt is to downgrade the compiler filter,
    162   // set downgrade to true.
    163   // Returns a positive status code if the status refers to the oat file in
    164   // the oat location. Returns a negative status code if the status refers to
    165   // the oat file in the odex location.
    166   int GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter,
    167                       bool profile_changed = false,
    168                       bool downgrade = false,
    169                       ClassLoaderContext* context = nullptr);
    170 
    171   // Returns true if there is up-to-date code for this dex location,
    172   // irrespective of the compiler filter of the up-to-date code.
    173   bool IsUpToDate();
    174 
    175   // Return code used when attempting to generate updated code.
    176   enum ResultOfAttemptToUpdate {
    177     kUpdateFailed,        // We tried making the code up to date, but
    178                           // encountered an unexpected failure.
    179     kUpdateNotAttempted,  // We wanted to update the code, but determined we
    180                           // should not make the attempt.
    181     kUpdateSucceeded      // We successfully made the code up to date
    182                           // (possibly by doing nothing).
    183   };
    184 
    185   // Attempts to generate or relocate the oat file as needed to make it up to
    186   // date based on the current runtime and compiler options.
    187   // profile_changed should be true to indicate the profile has recently
    188   // changed for this dex location.
    189   //
    190   // If the dex files need to be made up to date, class_loader_context will be
    191   // passed to dex2oat.
    192   //
    193   // Returns the result of attempting to update the code.
    194   //
    195   // If the result is not kUpdateSucceeded, the value of error_msg will be set
    196   // to a string describing why there was a failure or the update was not
    197   // attempted. error_msg must not be null.
    198   ResultOfAttemptToUpdate MakeUpToDate(bool profile_changed,
    199                                        ClassLoaderContext* class_loader_context,
    200                                        std::string* error_msg);
    201 
    202   // Returns an oat file that can be used for loading dex files.
    203   // Returns null if no suitable oat file was found.
    204   //
    205   // After this call, no other methods of the OatFileAssistant should be
    206   // called, because access to the loaded oat file has been taken away from
    207   // the OatFileAssistant object.
    208   std::unique_ptr<OatFile> GetBestOatFile();
    209 
    210   // Returns a human readable description of the status of the code for the
    211   // dex file. The returned description is for debugging purposes only.
    212   std::string GetStatusDump();
    213 
    214   // Open and returns an image space associated with the oat file.
    215   static std::unique_ptr<gc::space::ImageSpace> OpenImageSpace(const OatFile* oat_file);
    216 
    217   // Loads the dex files in the given oat file for the given dex location.
    218   // The oat file should be up to date for the given dex location.
    219   // This loads multiple dex files in the case of multidex.
    220   // Returns an empty vector if no dex files for that location could be loaded
    221   // from the oat file.
    222   //
    223   // The caller is responsible for freeing the dex_files returned, if any. The
    224   // dex_files will only remain valid as long as the oat_file is valid.
    225   static std::vector<std::unique_ptr<const DexFile>> LoadDexFiles(
    226       const OatFile& oat_file, const char* dex_location);
    227 
    228   // Same as `std::vector<std::unique_ptr<const DexFile>> LoadDexFiles(...)` with the difference:
    229   //   - puts the dex files in the given vector
    230   //   - returns whether or not all dex files were successfully opened
    231   static bool LoadDexFiles(const OatFile& oat_file,
    232                            const std::string& dex_location,
    233                            std::vector<std::unique_ptr<const DexFile>>* out_dex_files);
    234 
    235   // Returns true if there are dex files in the original dex location that can
    236   // be compiled with dex2oat for this dex location.
    237   // Returns false if there is no original dex file, or if the original dex
    238   // file is an apk/zip without a classes.dex entry.
    239   bool HasOriginalDexFiles();
    240 
    241   // If the dex file has been installed with a compiled oat file alongside
    242   // it, the compiled oat file will have the extension .odex, and is referred
    243   // to as the odex file. It is called odex for legacy reasons; the file is
    244   // really an oat file. The odex file will often, but not always, have a
    245   // patch delta of 0 and need to be relocated before use for the purposes of
    246   // ASLR. The odex file is treated as if it were read-only.
    247   //
    248   // Returns the status of the odex file for the dex location.
    249   OatStatus OdexFileStatus();
    250 
    251   // When the dex files is compiled on the target device, the oat file is the
    252   // result. The oat file will have been relocated to some
    253   // (possibly-out-of-date) offset for ASLR.
    254   //
    255   // Returns the status of the oat file for the dex location.
    256   OatStatus OatFileStatus();
    257 
    258   // Executes dex2oat using the current runtime configuration overridden with
    259   // the given arguments. This does not check to see if dex2oat is enabled in
    260   // the runtime configuration.
    261   // Returns true on success.
    262   //
    263   // If there is a failure, the value of error_msg will be set to a string
    264   // describing why there was failure. error_msg must not be null.
    265   //
    266   // TODO: The OatFileAssistant probably isn't the right place to have this
    267   // function.
    268   static bool Dex2Oat(const std::vector<std::string>& args, std::string* error_msg);
    269 
    270   // Constructs the odex file name for the given dex location.
    271   // Returns true on success, in which case odex_filename is set to the odex
    272   // file name.
    273   // Returns false on error, in which case error_msg describes the error and
    274   // odex_filename is not changed.
    275   // Neither odex_filename nor error_msg may be null.
    276   static bool DexLocationToOdexFilename(const std::string& location,
    277                                         InstructionSet isa,
    278                                         std::string* odex_filename,
    279                                         std::string* error_msg);
    280 
    281   // Constructs the oat file name for the given dex location.
    282   // Returns true on success, in which case oat_filename is set to the oat
    283   // file name.
    284   // Returns false on error, in which case error_msg describes the error and
    285   // oat_filename is not changed.
    286   // Neither oat_filename nor error_msg may be null.
    287   static bool DexLocationToOatFilename(const std::string& location,
    288                                        InstructionSet isa,
    289                                        std::string* oat_filename,
    290                                        std::string* error_msg);
    291 
    292  private:
    293   struct ImageInfo {
    294     uint32_t oat_checksum = 0;
    295     uintptr_t oat_data_begin = 0;
    296     int32_t patch_delta = 0;
    297     std::string location;
    298 
    299     static std::unique_ptr<ImageInfo> GetRuntimeImageInfo(InstructionSet isa,
    300                                                           std::string* error_msg);
    301   };
    302 
    303   class OatFileInfo {
    304    public:
    305     // Initially the info is for no file in particular. It will treat the
    306     // file as out of date until Reset is called with a real filename to use
    307     // the cache for.
    308     // Pass true for is_oat_location if the information associated with this
    309     // OatFileInfo is for the oat location, as opposed to the odex location.
    310     OatFileInfo(OatFileAssistant* oat_file_assistant, bool is_oat_location);
    311 
    312     bool IsOatLocation();
    313 
    314     const std::string* Filename();
    315 
    316     // Returns true if this oat file can be used for running code. The oat
    317     // file can be used for running code as long as it is not out of date with
    318     // respect to the dex code or boot image. An oat file that is out of date
    319     // with respect to relocation is considered useable, because it's possible
    320     // to interpret the dex code rather than run the unrelocated compiled
    321     // code.
    322     bool IsUseable();
    323 
    324     // Returns the status of this oat file.
    325     OatStatus Status();
    326 
    327     // Return the DexOptNeeded value for this oat file with respect to the
    328     // given target_compilation_filter.
    329     // profile_changed should be true to indicate the profile has recently
    330     // changed for this dex location.
    331     // downgrade should be true if the purpose of dexopt is to downgrade the
    332     // compiler filter.
    333     DexOptNeeded GetDexOptNeeded(CompilerFilter::Filter target_compiler_filter,
    334                                  bool profile_changed,
    335                                  bool downgrade,
    336                                  ClassLoaderContext* context);
    337 
    338     // Returns the loaded file.
    339     // Loads the file if needed. Returns null if the file failed to load.
    340     // The caller shouldn't clean up or free the returned pointer.
    341     const OatFile* GetFile();
    342 
    343     // Returns true if the file is opened executable.
    344     bool IsExecutable();
    345 
    346     // Clear any cached information about the file that depends on the
    347     // contents of the file. This does not reset the provided filename.
    348     void Reset();
    349 
    350     // Clear any cached information and switch to getting info about the oat
    351     // file with the given filename.
    352     void Reset(const std::string& filename);
    353 
    354     // Release the loaded oat file for runtime use.
    355     // Returns null if the oat file hasn't been loaded or is out of date.
    356     // Ensures the returned file is not loaded executable if it has unuseable
    357     // compiled code.
    358     //
    359     // After this call, no other methods of the OatFileInfo should be
    360     // called, because access to the loaded oat file has been taken away from
    361     // the OatFileInfo object.
    362     std::unique_ptr<OatFile> ReleaseFileForUse();
    363 
    364    private:
    365     // Returns true if the compiler filter used to generate the file is at
    366     // least as good as the given target filter. profile_changed should be
    367     // true to indicate the profile has recently changed for this dex
    368     // location.
    369     // downgrade should be true if the purpose of dexopt is to downgrade the
    370     // compiler filter.
    371     bool CompilerFilterIsOkay(CompilerFilter::Filter target, bool profile_changed, bool downgrade);
    372 
    373     bool ClassLoaderContextIsOkay(ClassLoaderContext* context);
    374 
    375     // Release the loaded oat file.
    376     // Returns null if the oat file hasn't been loaded.
    377     //
    378     // After this call, no other methods of the OatFileInfo should be
    379     // called, because access to the loaded oat file has been taken away from
    380     // the OatFileInfo object.
    381     std::unique_ptr<OatFile> ReleaseFile();
    382 
    383     OatFileAssistant* oat_file_assistant_;
    384     const bool is_oat_location_;
    385 
    386     bool filename_provided_ = false;
    387     std::string filename_;
    388 
    389     bool load_attempted_ = false;
    390     std::unique_ptr<OatFile> file_;
    391 
    392     bool status_attempted_ = false;
    393     OatStatus status_ = OatStatus::kOatCannotOpen;
    394 
    395     // For debugging only.
    396     // If this flag is set, the file has been released to the user and the
    397     // OatFileInfo object is in a bad state and should no longer be used.
    398     bool file_released_ = false;
    399   };
    400 
    401   // Generate the oat file for the given info from the dex file using the
    402   // current runtime compiler options, the specified filter and class loader
    403   // context.
    404   // This does not check the current status before attempting to generate the
    405   // oat file.
    406   //
    407   // If the result is not kUpdateSucceeded, the value of error_msg will be set
    408   // to a string describing why there was a failure or the update was not
    409   // attempted. error_msg must not be null.
    410   ResultOfAttemptToUpdate GenerateOatFileNoChecks(OatFileInfo& info,
    411                                                   CompilerFilter::Filter target,
    412                                                   const ClassLoaderContext* class_loader_context,
    413                                                   std::string* error_msg);
    414 
    415   // Return info for the best oat file.
    416   OatFileInfo& GetBestInfo();
    417 
    418   // Returns true if the dex checksums in the given vdex file are up to date
    419   // with respect to the dex location. If the dex checksums are not up to
    420   // date, error_msg is updated with a message describing the problem.
    421   bool DexChecksumUpToDate(const VdexFile& file, std::string* error_msg);
    422 
    423   // Returns true if the dex checksums in the given oat file are up to date
    424   // with respect to the dex location. If the dex checksums are not up to
    425   // date, error_msg is updated with a message describing the problem.
    426   bool DexChecksumUpToDate(const OatFile& file, std::string* error_msg);
    427 
    428   // Return the status for a given opened oat file with respect to the dex
    429   // location.
    430   OatStatus GivenOatFileStatus(const OatFile& file);
    431 
    432   // Returns the current image location.
    433   // Returns an empty string if the image location could not be retrieved.
    434   //
    435   // TODO: This method should belong with an image file manager, not
    436   // the oat file assistant.
    437   static std::string ImageLocation();
    438 
    439   // Gets the dex checksums required for an up-to-date oat file.
    440   // Returns cached_required_dex_checksums if the required checksums were
    441   // located. Returns null if the required checksums were not found.  The
    442   // caller shouldn't clean up or free the returned pointer.  This sets the
    443   // has_original_dex_files_ field to true if the checksums were found for the
    444   // dex_location_ dex file.
    445   const std::vector<uint32_t>* GetRequiredDexChecksums();
    446 
    447   // Returns the loaded image info.
    448   // Loads the image info if needed. Returns null if the image info failed
    449   // to load.
    450   // The caller shouldn't clean up or free the returned pointer.
    451   const ImageInfo* GetImageInfo();
    452 
    453   // To implement Lock(), we lock a dummy file where the oat file would go
    454   // (adding ".flock" to the target file name) and retain the lock for the
    455   // remaining lifetime of the OatFileAssistant object.
    456   ScopedFlock flock_;
    457 
    458   std::string dex_location_;
    459 
    460   // Whether or not the parent directory of the dex file is writable.
    461   bool dex_parent_writable_ = false;
    462 
    463   // In a properly constructed OatFileAssistant object, isa_ should be either
    464   // the 32 or 64 bit variant for the current device.
    465   const InstructionSet isa_ = kNone;
    466 
    467   // Whether we will attempt to load oat files executable.
    468   bool load_executable_ = false;
    469 
    470   // Cached value of the required dex checksums.
    471   // This should be accessed only by the GetRequiredDexChecksums() method.
    472   std::vector<uint32_t> cached_required_dex_checksums_;
    473   bool required_dex_checksums_attempted_ = false;
    474   bool required_dex_checksums_found_;
    475   bool has_original_dex_files_;
    476 
    477   OatFileInfo odex_;
    478   OatFileInfo oat_;
    479 
    480   // Cached value of the image info.
    481   // Use the GetImageInfo method rather than accessing these directly.
    482   // TODO: The image info should probably be moved out of the oat file
    483   // assistant to an image file manager.
    484   bool image_info_load_attempted_ = false;
    485   std::unique_ptr<ImageInfo> cached_image_info_;
    486 
    487   friend class OatFileAssistantTest;
    488 
    489   DISALLOW_COPY_AND_ASSIGN(OatFileAssistant);
    490 };
    491 
    492 std::ostream& operator << (std::ostream& stream, const OatFileAssistant::OatStatus status);
    493 
    494 }  // namespace art
    495 
    496 #endif  // ART_RUNTIME_OAT_FILE_ASSISTANT_H_
    497