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