Home | History | Annotate | Download | only in linker
      1 /*
      2  * Copyright (C) 2011 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_DEX2OAT_LINKER_OAT_WRITER_H_
     18 #define ART_DEX2OAT_LINKER_OAT_WRITER_H_
     19 
     20 #include <stdint.h>
     21 #include <cstddef>
     22 #include <memory>
     23 #include <vector>
     24 
     25 #include "base/array_ref.h"
     26 #include "base/dchecked_vector.h"
     27 #include "base/os.h"
     28 #include "base/safe_map.h"
     29 #include "compiler.h"
     30 #include "debug/debug_info.h"
     31 #include "dex/compact_dex_level.h"
     32 #include "dex/method_reference.h"
     33 #include "dex/string_reference.h"
     34 #include "dex/type_reference.h"
     35 #include "linker/relative_patcher.h"  // For RelativePatcherTargetProvider.
     36 #include "mem_map.h"
     37 #include "mirror/class.h"
     38 #include "oat.h"
     39 
     40 namespace art {
     41 
     42 class BitVector;
     43 class CompiledMethod;
     44 class CompilerDriver;
     45 class DexContainer;
     46 class ProfileCompilationInfo;
     47 class TimingLogger;
     48 class TypeLookupTable;
     49 class VdexFile;
     50 class ZipEntry;
     51 
     52 namespace debug {
     53 struct MethodDebugInfo;
     54 }  // namespace debug
     55 
     56 namespace verifier {
     57 class VerifierDeps;
     58 }  // namespace verifier
     59 
     60 namespace linker {
     61 
     62 class ImageWriter;
     63 class MultiOatRelativePatcher;
     64 class OutputStream;
     65 
     66 // OatHeader         variable length with count of D OatDexFiles
     67 //
     68 // TypeLookupTable[0] one descriptor to class def index hash table for each OatDexFile.
     69 // TypeLookupTable[1]
     70 // ...
     71 // TypeLookupTable[D]
     72 //
     73 // ClassOffsets[0]   one table of OatClass offsets for each class def for each OatDexFile.
     74 // ClassOffsets[1]
     75 // ...
     76 // ClassOffsets[D]
     77 //
     78 // OatClass[0]       one variable sized OatClass for each of C DexFile::ClassDefs
     79 // OatClass[1]       contains OatClass entries with class status, offsets to code, etc.
     80 // ...
     81 // OatClass[C]
     82 //
     83 // MethodBssMapping  one variable sized MethodBssMapping for each dex file, optional.
     84 // MethodBssMapping
     85 // ...
     86 // MethodBssMapping
     87 //
     88 // VmapTable         one variable sized VmapTable blob (CodeInfo or QuickeningInfo).
     89 // VmapTable         VmapTables are deduplicated.
     90 // ...
     91 // VmapTable
     92 //
     93 // MethodInfo        one variable sized blob with MethodInfo.
     94 // MethodInfo        MethodInfos are deduplicated.
     95 // ...
     96 // MethodInfo
     97 //
     98 // OatDexFile[0]     one variable sized OatDexFile with offsets to Dex and OatClasses
     99 // OatDexFile[1]
    100 // ...
    101 // OatDexFile[D]
    102 //
    103 // padding           if necessary so that the following code will be page aligned
    104 //
    105 // OatMethodHeader   fixed size header for a CompiledMethod including the size of the MethodCode.
    106 // MethodCode        one variable sized blob with the code of a CompiledMethod.
    107 // OatMethodHeader   (OatMethodHeader, MethodCode) pairs are deduplicated.
    108 // MethodCode
    109 // ...
    110 // OatMethodHeader
    111 // MethodCode
    112 //
    113 class OatWriter {
    114  public:
    115   enum class CreateTypeLookupTable {
    116     kCreate,
    117     kDontCreate,
    118     kDefault = kCreate
    119   };
    120 
    121   OatWriter(bool compiling_boot_image,
    122             TimingLogger* timings,
    123             ProfileCompilationInfo* info,
    124             CompactDexLevel compact_dex_level);
    125 
    126   // To produce a valid oat file, the user must first add sources with any combination of
    127   //   - AddDexFileSource(),
    128   //   - AddZippedDexFilesSource(),
    129   //   - AddRawDexFileSource(),
    130   //   - AddVdexDexFilesSource().
    131   // Then the user must call in order
    132   //   - WriteAndOpenDexFiles()
    133   //   - Initialize()
    134   //   - WriteVerifierDeps()
    135   //   - WriteQuickeningInfo()
    136   //   - WriteChecksumsAndVdexHeader()
    137   //   - PrepareLayout(),
    138   //   - WriteRodata(),
    139   //   - WriteCode(),
    140   //   - WriteHeader().
    141 
    142   // Add dex file source(s) from a file, either a plain dex file or
    143   // a zip file with one or more dex files.
    144   bool AddDexFileSource(
    145       const char* filename,
    146       const char* location,
    147       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
    148   // Add dex file source(s) from a zip file specified by a file handle.
    149   bool AddZippedDexFilesSource(
    150       File&& zip_fd,
    151       const char* location,
    152       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
    153   // Add dex file source from raw memory.
    154   bool AddRawDexFileSource(
    155       const ArrayRef<const uint8_t>& data,
    156       const char* location,
    157       uint32_t location_checksum,
    158       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
    159   // Add dex file source(s) from a vdex file.
    160   bool AddVdexDexFilesSource(
    161       const VdexFile& vdex_file,
    162       const char* location,
    163       CreateTypeLookupTable create_type_lookup_table = CreateTypeLookupTable::kDefault);
    164   dchecked_vector<std::string> GetSourceLocations() const;
    165 
    166   // Write raw dex files to the vdex file, mmap the file and open the dex files from it.
    167   // Supporting data structures are written into the .rodata section of the oat file.
    168   // The `verify` setting dictates whether the dex file verifier should check the dex files.
    169   // This is generally the case, and should only be false for tests.
    170   // If `update_input_vdex` is true, then this method won't actually write the dex files,
    171   // and the compiler will just re-use the existing vdex file.
    172   bool WriteAndOpenDexFiles(File* vdex_file,
    173                             OutputStream* oat_rodata,
    174                             InstructionSet instruction_set,
    175                             const InstructionSetFeatures* instruction_set_features,
    176                             SafeMap<std::string, std::string>* key_value_store,
    177                             bool verify,
    178                             bool update_input_vdex,
    179                             CopyOption copy_dex_files,
    180                             /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
    181                             /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files);
    182   bool WriteQuickeningInfo(OutputStream* vdex_out);
    183   bool WriteVerifierDeps(OutputStream* vdex_out, verifier::VerifierDeps* verifier_deps);
    184   bool WriteChecksumsAndVdexHeader(OutputStream* vdex_out);
    185   // Initialize the writer with the given parameters.
    186   void Initialize(const CompilerDriver* compiler,
    187                   ImageWriter* image_writer,
    188                   const std::vector<const DexFile*>& dex_files) {
    189     compiler_driver_ = compiler;
    190     image_writer_ = image_writer;
    191     dex_files_ = &dex_files;
    192   }
    193 
    194   // Prepare layout of remaining data.
    195   void PrepareLayout(MultiOatRelativePatcher* relative_patcher);
    196   // Write the rest of .rodata section (ClassOffsets[], OatClass[], maps).
    197   bool WriteRodata(OutputStream* out);
    198   // Write the code to the .text section.
    199   bool WriteCode(OutputStream* out);
    200   // Write the oat header. This finalizes the oat file.
    201   bool WriteHeader(OutputStream* out,
    202                    uint32_t image_file_location_oat_checksum,
    203                    uintptr_t image_file_location_oat_begin,
    204                    int32_t image_patch_delta);
    205 
    206   // Returns whether the oat file has an associated image.
    207   bool HasImage() const {
    208     // Since the image is being created at the same time as the oat file,
    209     // check if there's an image writer.
    210     return image_writer_ != nullptr;
    211   }
    212 
    213   bool HasBootImage() const {
    214     return compiling_boot_image_;
    215   }
    216 
    217   const OatHeader& GetOatHeader() const {
    218     return *oat_header_;
    219   }
    220 
    221   size_t GetOatSize() const {
    222     return oat_size_;
    223   }
    224 
    225   size_t GetBssSize() const {
    226     return bss_size_;
    227   }
    228 
    229   size_t GetBssMethodsOffset() const {
    230     return bss_methods_offset_;
    231   }
    232 
    233   size_t GetBssRootsOffset() const {
    234     return bss_roots_offset_;
    235   }
    236 
    237   size_t GetVdexSize() const {
    238     return vdex_size_;
    239   }
    240 
    241   size_t GetOatDataOffset() const {
    242     return oat_data_offset_;
    243   }
    244 
    245   ~OatWriter();
    246 
    247   debug::DebugInfo GetDebugInfo() const;
    248 
    249   const CompilerDriver* GetCompilerDriver() const {
    250     return compiler_driver_;
    251   }
    252 
    253  private:
    254   class DexFileSource;
    255   class OatClassHeader;
    256   class OatClass;
    257   class OatDexFile;
    258 
    259   // The function VisitDexMethods() below iterates through all the methods in all
    260   // the compiled dex files in order of their definitions. The method visitor
    261   // classes provide individual bits of processing for each of the passes we need to
    262   // first collect the data we want to write to the oat file and then, in later passes,
    263   // to actually write it.
    264   class DexMethodVisitor;
    265   class OatDexMethodVisitor;
    266   class InitBssLayoutMethodVisitor;
    267   class InitOatClassesMethodVisitor;
    268   class LayoutCodeMethodVisitor;
    269   class LayoutReserveOffsetCodeMethodVisitor;
    270   struct OrderedMethodData;
    271   class OrderedMethodVisitor;
    272   class InitCodeMethodVisitor;
    273   class InitMapMethodVisitor;
    274   class InitMethodInfoVisitor;
    275   class InitImageMethodVisitor;
    276   class WriteCodeMethodVisitor;
    277   class WriteMapMethodVisitor;
    278   class WriteMethodInfoVisitor;
    279   class WriteQuickeningInfoMethodVisitor;
    280   class WriteQuickeningInfoOffsetsMethodVisitor;
    281 
    282   // Visit all the methods in all the compiled dex files in their definition order
    283   // with a given DexMethodVisitor.
    284   bool VisitDexMethods(DexMethodVisitor* visitor);
    285 
    286   // If `update_input_vdex` is true, then this method won't actually write the dex files,
    287   // and the compiler will just re-use the existing vdex file.
    288   bool WriteDexFiles(OutputStream* out,
    289                      File* file,
    290                      bool update_input_vdex,
    291                      CopyOption copy_dex_files);
    292   bool WriteDexFile(OutputStream* out,
    293                     File* file,
    294                     OatDexFile* oat_dex_file,
    295                     bool update_input_vdex);
    296   bool SeekToDexFile(OutputStream* out, File* file, OatDexFile* oat_dex_file);
    297   bool LayoutAndWriteDexFile(OutputStream* out, OatDexFile* oat_dex_file);
    298   bool WriteDexFile(OutputStream* out,
    299                     File* file,
    300                     OatDexFile* oat_dex_file,
    301                     ZipEntry* dex_file);
    302   bool WriteDexFile(OutputStream* out,
    303                     File* file,
    304                     OatDexFile* oat_dex_file,
    305                     File* dex_file);
    306   bool WriteDexFile(OutputStream* out,
    307                     OatDexFile* oat_dex_file,
    308                     const uint8_t* dex_file,
    309                     bool update_input_vdex);
    310   bool OpenDexFiles(File* file,
    311                     bool verify,
    312                     /*out*/ std::vector<std::unique_ptr<MemMap>>* opened_dex_files_map,
    313                     /*out*/ std::vector<std::unique_ptr<const DexFile>>* opened_dex_files);
    314 
    315   size_t InitOatHeader(InstructionSet instruction_set,
    316                        const InstructionSetFeatures* instruction_set_features,
    317                        uint32_t num_dex_files,
    318                        SafeMap<std::string, std::string>* key_value_store);
    319   size_t InitClassOffsets(size_t offset);
    320   size_t InitOatClasses(size_t offset);
    321   size_t InitOatMaps(size_t offset);
    322   size_t InitIndexBssMappings(size_t offset);
    323   size_t InitOatDexFiles(size_t offset);
    324   size_t InitOatCode(size_t offset);
    325   size_t InitOatCodeDexFiles(size_t offset);
    326   void InitBssLayout(InstructionSet instruction_set);
    327 
    328   size_t WriteClassOffsets(OutputStream* out, size_t file_offset, size_t relative_offset);
    329   size_t WriteClasses(OutputStream* out, size_t file_offset, size_t relative_offset);
    330   size_t WriteMaps(OutputStream* out, size_t file_offset, size_t relative_offset);
    331   size_t WriteIndexBssMappings(OutputStream* out, size_t file_offset, size_t relative_offset);
    332   size_t WriteOatDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset);
    333   size_t WriteCode(OutputStream* out, size_t file_offset, size_t relative_offset);
    334   size_t WriteCodeDexFiles(OutputStream* out, size_t file_offset, size_t relative_offset);
    335 
    336   bool RecordOatDataOffset(OutputStream* out);
    337   bool WriteTypeLookupTables(OutputStream* oat_rodata,
    338                              const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files);
    339   bool WriteDexLayoutSections(OutputStream* oat_rodata,
    340                               const std::vector<std::unique_ptr<const DexFile>>& opened_dex_files);
    341   bool WriteCodeAlignment(OutputStream* out, uint32_t aligned_code_delta);
    342   bool WriteUpTo16BytesAlignment(OutputStream* out, uint32_t size, uint32_t* stat);
    343   void SetMultiOatRelativePatcherAdjustment();
    344   void CloseSources();
    345 
    346   bool MayHaveCompiledMethods() const;
    347 
    348   bool VdexWillContainDexFiles() const {
    349     return dex_files_ != nullptr && extract_dex_files_into_vdex_;
    350   }
    351 
    352   // Find the address of the GcRoot<String> in the InternTable for a boot image string.
    353   const uint8_t* LookupBootImageInternTableSlot(const DexFile& dex_file,
    354                                                 dex::StringIndex string_idx);
    355   // Find the address of the ClassTable::TableSlot for a boot image class.
    356   const uint8_t* LookupBootImageClassTableSlot(const DexFile& dex_file, dex::TypeIndex type_idx);
    357 
    358   enum class WriteState {
    359     kAddingDexFileSources,
    360     kPrepareLayout,
    361     kWriteRoData,
    362     kWriteText,
    363     kWriteHeader,
    364     kDone
    365   };
    366 
    367   WriteState write_state_;
    368   TimingLogger* timings_;
    369 
    370   std::vector<std::unique_ptr<File>> raw_dex_files_;
    371   std::vector<std::unique_ptr<ZipArchive>> zip_archives_;
    372   std::vector<std::unique_ptr<ZipEntry>> zipped_dex_files_;
    373 
    374   // Using std::list<> which doesn't move elements around on push/emplace_back().
    375   // We need this because we keep plain pointers to the strings' c_str().
    376   std::list<std::string> zipped_dex_file_locations_;
    377 
    378   dchecked_vector<debug::MethodDebugInfo> method_info_;
    379 
    380   const CompilerDriver* compiler_driver_;
    381   ImageWriter* image_writer_;
    382   const bool compiling_boot_image_;
    383   // Whether the dex files being compiled are going to be extracted to the vdex.
    384   bool extract_dex_files_into_vdex_;
    385 
    386   // note OatFile does not take ownership of the DexFiles
    387   const std::vector<const DexFile*>* dex_files_;
    388 
    389   // Size required for Vdex data structures.
    390   size_t vdex_size_;
    391 
    392   // Offset of section holding Dex files inside Vdex.
    393   size_t vdex_dex_files_offset_;
    394 
    395   // Offset of section holding shared dex data section in the Vdex.
    396   size_t vdex_dex_shared_data_offset_;
    397 
    398   // Offset of section holding VerifierDeps inside Vdex.
    399   size_t vdex_verifier_deps_offset_;
    400 
    401   // Offset of section holding quickening info inside Vdex.
    402   size_t vdex_quickening_info_offset_;
    403 
    404   // Size required for Oat data structures.
    405   size_t oat_size_;
    406 
    407   // The start of the required .bss section.
    408   size_t bss_start_;
    409 
    410   // The size of the required .bss section holding the DexCache data and GC roots.
    411   size_t bss_size_;
    412 
    413   // The offset of the methods in .bss section.
    414   size_t bss_methods_offset_;
    415 
    416   // The offset of the GC roots in .bss section.
    417   size_t bss_roots_offset_;
    418 
    419   // Map for recording references to ArtMethod entries in .bss.
    420   SafeMap<const DexFile*, BitVector> bss_method_entry_references_;
    421 
    422   // Map for recording references to GcRoot<mirror::Class> entries in .bss.
    423   SafeMap<const DexFile*, BitVector> bss_type_entry_references_;
    424 
    425   // Map for recording references to GcRoot<mirror::String> entries in .bss.
    426   SafeMap<const DexFile*, BitVector> bss_string_entry_references_;
    427 
    428   // Map for allocating ArtMethod entries in .bss. Indexed by MethodReference for the target
    429   // method in the dex file with the "method reference value comparator" for deduplication.
    430   // The value is the target offset for patching, starting at `bss_start_ + bss_methods_offset_`.
    431   SafeMap<MethodReference, size_t, MethodReferenceValueComparator> bss_method_entries_;
    432 
    433   // Map for allocating Class entries in .bss. Indexed by TypeReference for the source
    434   // type in the dex file with the "type value comparator" for deduplication. The value
    435   // is the target offset for patching, starting at `bss_start_ + bss_roots_offset_`.
    436   SafeMap<TypeReference, size_t, TypeReferenceValueComparator> bss_type_entries_;
    437 
    438   // Map for allocating String entries in .bss. Indexed by StringReference for the source
    439   // string in the dex file with the "string value comparator" for deduplication. The value
    440   // is the target offset for patching, starting at `bss_start_ + bss_roots_offset_`.
    441   SafeMap<StringReference, size_t, StringReferenceValueComparator> bss_string_entries_;
    442 
    443   // Whether boot image tables should be mapped to the .bss. This is needed for compiled
    444   // code that reads from these tables with PC-relative instructions.
    445   bool map_boot_image_tables_to_bss_;
    446 
    447   // Offset of the oat data from the start of the mmapped region of the elf file.
    448   size_t oat_data_offset_;
    449 
    450   // Fake OatDexFiles to hold type lookup tables for the compiler.
    451   std::vector<std::unique_ptr<art::OatDexFile>> type_lookup_table_oat_dex_files_;
    452 
    453   // data to write
    454   std::unique_ptr<OatHeader> oat_header_;
    455   dchecked_vector<OatDexFile> oat_dex_files_;
    456   dchecked_vector<OatClassHeader> oat_class_headers_;
    457   dchecked_vector<OatClass> oat_classes_;
    458   std::unique_ptr<const std::vector<uint8_t>> jni_dlsym_lookup_;
    459   std::unique_ptr<const std::vector<uint8_t>> quick_generic_jni_trampoline_;
    460   std::unique_ptr<const std::vector<uint8_t>> quick_imt_conflict_trampoline_;
    461   std::unique_ptr<const std::vector<uint8_t>> quick_resolution_trampoline_;
    462   std::unique_ptr<const std::vector<uint8_t>> quick_to_interpreter_bridge_;
    463 
    464   // output stats
    465   uint32_t size_vdex_header_;
    466   uint32_t size_vdex_checksums_;
    467   uint32_t size_dex_file_alignment_;
    468   uint32_t size_executable_offset_alignment_;
    469   uint32_t size_oat_header_;
    470   uint32_t size_oat_header_key_value_store_;
    471   uint32_t size_dex_file_;
    472   uint32_t size_verifier_deps_;
    473   uint32_t size_verifier_deps_alignment_;
    474   uint32_t size_quickening_info_;
    475   uint32_t size_quickening_info_alignment_;
    476   uint32_t size_interpreter_to_interpreter_bridge_;
    477   uint32_t size_interpreter_to_compiled_code_bridge_;
    478   uint32_t size_jni_dlsym_lookup_;
    479   uint32_t size_quick_generic_jni_trampoline_;
    480   uint32_t size_quick_imt_conflict_trampoline_;
    481   uint32_t size_quick_resolution_trampoline_;
    482   uint32_t size_quick_to_interpreter_bridge_;
    483   uint32_t size_trampoline_alignment_;
    484   uint32_t size_method_header_;
    485   uint32_t size_code_;
    486   uint32_t size_code_alignment_;
    487   uint32_t size_relative_call_thunks_;
    488   uint32_t size_misc_thunks_;
    489   uint32_t size_vmap_table_;
    490   uint32_t size_method_info_;
    491   uint32_t size_oat_dex_file_location_size_;
    492   uint32_t size_oat_dex_file_location_data_;
    493   uint32_t size_oat_dex_file_location_checksum_;
    494   uint32_t size_oat_dex_file_offset_;
    495   uint32_t size_oat_dex_file_class_offsets_offset_;
    496   uint32_t size_oat_dex_file_lookup_table_offset_;
    497   uint32_t size_oat_dex_file_dex_layout_sections_offset_;
    498   uint32_t size_oat_dex_file_dex_layout_sections_;
    499   uint32_t size_oat_dex_file_dex_layout_sections_alignment_;
    500   uint32_t size_oat_dex_file_method_bss_mapping_offset_;
    501   uint32_t size_oat_dex_file_type_bss_mapping_offset_;
    502   uint32_t size_oat_dex_file_string_bss_mapping_offset_;
    503   uint32_t size_oat_lookup_table_alignment_;
    504   uint32_t size_oat_lookup_table_;
    505   uint32_t size_oat_class_offsets_alignment_;
    506   uint32_t size_oat_class_offsets_;
    507   uint32_t size_oat_class_type_;
    508   uint32_t size_oat_class_status_;
    509   uint32_t size_oat_class_method_bitmaps_;
    510   uint32_t size_oat_class_method_offsets_;
    511   uint32_t size_method_bss_mappings_;
    512   uint32_t size_type_bss_mappings_;
    513   uint32_t size_string_bss_mappings_;
    514 
    515   // The helper for processing relative patches is external so that we can patch across oat files.
    516   MultiOatRelativePatcher* relative_patcher_;
    517 
    518   // The locations of absolute patches relative to the start of the executable section.
    519   dchecked_vector<uintptr_t> absolute_patch_locations_;
    520 
    521   // Profile info used to generate new layout of files.
    522   ProfileCompilationInfo* profile_compilation_info_;
    523 
    524   // Compact dex level that is generated.
    525   CompactDexLevel compact_dex_level_;
    526 
    527   using OrderedMethodList = std::vector<OrderedMethodData>;
    528 
    529   // List of compiled methods, sorted by the order defined in OrderedMethodData.
    530   // Methods can be inserted more than once in case of duplicated methods.
    531   // This pointer is only non-null after InitOatCodeDexFiles succeeds.
    532   std::unique_ptr<OrderedMethodList> ordered_methods_;
    533 
    534   // Container of shared dex data.
    535   std::unique_ptr<DexContainer> dex_container_;
    536 
    537   DISALLOW_COPY_AND_ASSIGN(OatWriter);
    538 };
    539 
    540 }  // namespace linker
    541 }  // namespace art
    542 
    543 #endif  // ART_DEX2OAT_LINKER_OAT_WRITER_H_
    544