1 /*
2  * Copyright (C) 2012 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_ELF_FILE_IMPL_H_
18 #define ART_RUNTIME_ELF_FILE_IMPL_H_
19 
20 #include <map>
21 #include <memory>
22 #include <type_traits>
23 #include <vector>
24 
25 // Explicitly include our own elf.h to avoid Linux and other dependencies.
26 #include "./elf.h"
27 #include "mem_map.h"
28 
29 namespace art {
30 
31 extern "C" {
32   struct JITCodeEntry;
33 }
34 
35 template <typename ElfTypes>
36 class ElfFileImpl {
37  public:
38   using Elf_Addr = typename ElfTypes::Addr;
39   using Elf_Off = typename ElfTypes::Off;
40   using Elf_Half = typename ElfTypes::Half;
41   using Elf_Word = typename ElfTypes::Word;
42   using Elf_Sword = typename ElfTypes::Sword;
43   using Elf_Ehdr = typename ElfTypes::Ehdr;
44   using Elf_Shdr = typename ElfTypes::Shdr;
45   using Elf_Sym = typename ElfTypes::Sym;
46   using Elf_Rel = typename ElfTypes::Rel;
47   using Elf_Rela = typename ElfTypes::Rela;
48   using Elf_Phdr = typename ElfTypes::Phdr;
49   using Elf_Dyn = typename ElfTypes::Dyn;
50 
51   static ElfFileImpl* Open(File* file,
52                            bool writable,
53                            bool program_header_only,
54                            bool low_4gb,
55                            std::string* error_msg,
56                            uint8_t* requested_base = nullptr);
57   static ElfFileImpl* Open(File* file,
58                            int mmap_prot,
59                            int mmap_flags,
60                            bool low_4gb,
61                            std::string* error_msg);
62   ~ElfFileImpl();
63 
GetFilePath()64   const std::string& GetFilePath() const {
65     return file_path_;
66   }
67 
Begin()68   uint8_t* Begin() const {
69     return map_->Begin();
70   }
71 
End()72   uint8_t* End() const {
73     return map_->End();
74   }
75 
Size()76   size_t Size() const {
77     return map_->Size();
78   }
79 
80   Elf_Ehdr& GetHeader() const;
81 
82   Elf_Word GetProgramHeaderNum() const;
83   Elf_Phdr* GetProgramHeader(Elf_Word) const;
84 
85   Elf_Word GetSectionHeaderNum() const;
86   Elf_Shdr* GetSectionHeader(Elf_Word) const;
87   Elf_Shdr* FindSectionByType(Elf_Word type) const;
88   Elf_Shdr* FindSectionByName(const std::string& name) const;
89 
90   Elf_Shdr* GetSectionNameStringSection() const;
91 
92   // Find .dynsym using .hash for more efficient lookup than FindSymbolAddress.
93   const uint8_t* FindDynamicSymbolAddress(const std::string& symbol_name) const;
94 
95   static bool IsSymbolSectionType(Elf_Word section_type);
96   Elf_Word GetSymbolNum(Elf_Shdr&) const;
97   Elf_Sym* GetSymbol(Elf_Word section_type, Elf_Word i) const;
98 
99   // Find address of symbol in specified table, returning 0 if it is
100   // not found. See FindSymbolByName for an explanation of build_map.
101   Elf_Addr FindSymbolAddress(Elf_Word section_type,
102                              const std::string& symbol_name,
103                              bool build_map);
104 
105   // Lookup a string given string section and offset. Returns null for special 0 offset.
106   const char* GetString(Elf_Shdr&, Elf_Word) const;
107 
108   Elf_Word GetDynamicNum() const;
109   Elf_Dyn& GetDynamic(Elf_Word) const;
110 
111   Elf_Word GetRelNum(Elf_Shdr&) const;
112   Elf_Rel& GetRel(Elf_Shdr&, Elf_Word) const;
113 
114   Elf_Word GetRelaNum(Elf_Shdr&) const;
115   Elf_Rela& GetRela(Elf_Shdr&, Elf_Word) const;
116 
117   // Retrieves the expected size when the file is loaded at runtime. Returns true if successful.
118   bool GetLoadedSize(size_t* size, std::string* error_msg) const;
119 
120   // Load segments into memory based on PT_LOAD program headers.
121   // executable is true at run time, false at compile time.
122   bool Load(File* file, bool executable, bool low_4gb, std::string* error_msg);
123 
124   bool Fixup(Elf_Addr base_address);
125   bool FixupDynamic(Elf_Addr base_address);
126   bool FixupSectionHeaders(Elf_Addr base_address);
127   bool FixupProgramHeaders(Elf_Addr base_address);
128   bool FixupSymbols(Elf_Addr base_address, bool dynamic);
129   bool FixupRelocations(Elf_Addr base_address);
130   bool FixupDebugSections(Elf_Addr base_address_delta);
131   bool ApplyOatPatchesTo(const char* target_section_name, Elf_Addr base_address_delta);
132   static void ApplyOatPatches(const uint8_t* patches, const uint8_t* patches_end, Elf_Addr delta,
133                               uint8_t* to_patch, const uint8_t* to_patch_end);
134 
135   bool Strip(File* file, std::string* error_msg);
136 
137  private:
138   ElfFileImpl(File* file, bool writable, bool program_header_only, uint8_t* requested_base);
139 
140   bool Setup(File* file, int prot, int flags, bool low_4gb, std::string* error_msg);
141 
142   bool SetMap(File* file, MemMap* map, std::string* error_msg);
143 
144   uint8_t* GetProgramHeadersStart() const;
145   uint8_t* GetSectionHeadersStart() const;
146   Elf_Phdr& GetDynamicProgramHeader() const;
147   Elf_Dyn* GetDynamicSectionStart() const;
148   Elf_Sym* GetSymbolSectionStart(Elf_Word section_type) const;
149   const char* GetStringSectionStart(Elf_Word section_type) const;
150   Elf_Rel* GetRelSectionStart(Elf_Shdr&) const;
151   Elf_Rela* GetRelaSectionStart(Elf_Shdr&) const;
152   Elf_Word* GetHashSectionStart() const;
153   Elf_Word GetHashBucketNum() const;
154   Elf_Word GetHashChainNum() const;
155   Elf_Word GetHashBucket(size_t i, bool* ok) const;
156   Elf_Word GetHashChain(size_t i, bool* ok) const;
157 
158   typedef std::map<std::string, Elf_Sym*> SymbolTable;
159   SymbolTable** GetSymbolTable(Elf_Word section_type);
160 
161   bool ValidPointer(const uint8_t* start) const;
162 
163   const Elf_Sym* FindDynamicSymbol(const std::string& symbol_name) const;
164 
165   // Check that certain sections and their dependencies exist.
166   bool CheckSectionsExist(File* file, std::string* error_msg) const;
167 
168   // Check that the link of the first section links to the second section.
169   bool CheckSectionsLinked(const uint8_t* source, const uint8_t* target) const;
170 
171   // Check whether the offset is in range, and set to target to Begin() + offset if OK.
172   bool CheckAndSet(Elf32_Off offset, const char* label, uint8_t** target, std::string* error_msg);
173 
174   // Find symbol in specified table, returning null if it is not found.
175   //
176   // If build_map is true, builds a map to speed repeated access. The
177   // map does not included untyped symbol values (aka STT_NOTYPE)
178   // since they can contain duplicates. If build_map is false, the map
179   // will be used if it was already created. Typically build_map
180   // should be set unless only a small number of symbols will be
181   // looked up.
182   Elf_Sym* FindSymbolByName(Elf_Word section_type,
183                             const std::string& symbol_name,
184                             bool build_map);
185 
186   Elf_Phdr* FindProgamHeaderByType(Elf_Word type) const;
187 
188   Elf_Dyn* FindDynamicByType(Elf_Sword type) const;
189   Elf_Word FindDynamicValueByType(Elf_Sword type) const;
190 
191   // Lookup a string by section type. Returns null for special 0 offset.
192   const char* GetString(Elf_Word section_type, Elf_Word) const;
193 
194   const std::string file_path_;
195   const bool writable_;
196   const bool program_header_only_;
197 
198   // ELF header mapping. If program_header_only_ is false, will
199   // actually point to the entire elf file.
200   std::unique_ptr<MemMap> map_;
201   Elf_Ehdr* header_;
202   std::vector<MemMap*> segments_;
203 
204   // Pointer to start of first PT_LOAD program segment after Load()
205   // when program_header_only_ is true.
206   uint8_t* base_address_;
207 
208   // The program header should always available but use GetProgramHeadersStart() to be sure.
209   uint8_t* program_headers_start_;
210 
211   // Conditionally available values. Use accessors to ensure they exist if they are required.
212   uint8_t* section_headers_start_;
213   Elf_Phdr* dynamic_program_header_;
214   Elf_Dyn* dynamic_section_start_;
215   Elf_Sym* symtab_section_start_;
216   Elf_Sym* dynsym_section_start_;
217   char* strtab_section_start_;
218   char* dynstr_section_start_;
219   Elf_Word* hash_section_start_;
220 
221   SymbolTable* symtab_symbol_table_;
222   SymbolTable* dynsym_symbol_table_;
223 
224   // Override the 'base' p_vaddr in the first LOAD segment with this value (if non-null).
225   uint8_t* requested_base_;
226 
227   DISALLOW_COPY_AND_ASSIGN(ElfFileImpl);
228 };
229 
230 }  // namespace art
231 
232 #endif  // ART_RUNTIME_ELF_FILE_IMPL_H_
233