1 //===-- ObjectFileELF.h --------------------------------------- -*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #ifndef liblldb_ObjectFileELF_h_
10 #define liblldb_ObjectFileELF_h_
11 
12 #include <stdint.h>
13 
14 #include <vector>
15 
16 #include "lldb/Symbol/ObjectFile.h"
17 #include "lldb/Utility/ArchSpec.h"
18 #include "lldb/Utility/FileSpec.h"
19 #include "lldb/Utility/UUID.h"
20 #include "lldb/lldb-private.h"
21 
22 #include "ELFHeader.h"
23 
24 struct ELFNote {
25   elf::elf_word n_namesz;
26   elf::elf_word n_descsz;
27   elf::elf_word n_type;
28 
29   std::string n_name;
30 
31   ELFNote() : n_namesz(0), n_descsz(0), n_type(0) {}
32 
33   /// Parse an ELFNote entry from the given DataExtractor starting at position
34   /// \p offset.
35   ///
36   /// \param[in] data
37   ///    The DataExtractor to read from.
38   ///
39   /// \param[in,out] offset
40   ///    Pointer to an offset in the data.  On return the offset will be
41   ///    advanced by the number of bytes read.
42   ///
43   /// \return
44   ///    True if the ELFRel entry was successfully read and false otherwise.
45   bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
46 
47   size_t GetByteSize() const {
48     return 12 + llvm::alignTo(n_namesz, 4) + llvm::alignTo(n_descsz, 4);
49   }
50 };
51 
52 /// \class ObjectFileELF
53 /// Generic ELF object file reader.
54 ///
55 /// This class provides a generic ELF (32/64 bit) reader plugin implementing
56 /// the ObjectFile protocol.
57 class ObjectFileELF : public lldb_private::ObjectFile {
58 public:
59   ~ObjectFileELF() override;
60 
61   // Static Functions
62   static void Initialize();
63 
64   static void Terminate();
65 
66   static lldb_private::ConstString GetPluginNameStatic();
67 
68   static const char *GetPluginDescriptionStatic();
69 
70   static lldb_private::ObjectFile *
71   CreateInstance(const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp,
72                  lldb::offset_t data_offset, const lldb_private::FileSpec *file,
73                  lldb::offset_t file_offset, lldb::offset_t length);
74 
75   static lldb_private::ObjectFile *CreateMemoryInstance(
76       const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp,
77       const lldb::ProcessSP &process_sp, lldb::addr_t header_addr);
78 
79   static size_t GetModuleSpecifications(const lldb_private::FileSpec &file,
80                                         lldb::DataBufferSP &data_sp,
81                                         lldb::offset_t data_offset,
82                                         lldb::offset_t file_offset,
83                                         lldb::offset_t length,
84                                         lldb_private::ModuleSpecList &specs);
85 
86   static bool MagicBytesMatch(lldb::DataBufferSP &data_sp, lldb::addr_t offset,
87                               lldb::addr_t length);
88 
89   // PluginInterface protocol
90   lldb_private::ConstString GetPluginName() override;
91 
92   uint32_t GetPluginVersion() override;
93 
94   // ObjectFile Protocol.
95   bool ParseHeader() override;
96 
97   bool SetLoadAddress(lldb_private::Target &target, lldb::addr_t value,
98                       bool value_is_offset) override;
99 
100   lldb::ByteOrder GetByteOrder() const override;
101 
102   bool IsExecutable() const override;
103 
104   uint32_t GetAddressByteSize() const override;
105 
106   lldb_private::AddressClass GetAddressClass(lldb::addr_t file_addr) override;
107 
108   lldb_private::Symtab *GetSymtab() override;
109 
110   bool IsStripped() override;
111 
112   void CreateSections(lldb_private::SectionList &unified_section_list) override;
113 
114   void Dump(lldb_private::Stream *s) override;
115 
116   lldb_private::ArchSpec GetArchitecture() override;
117 
118   lldb_private::UUID GetUUID() override;
119 
120   lldb_private::FileSpecList GetDebugSymbolFilePaths() override;
121 
122   uint32_t GetDependentModules(lldb_private::FileSpecList &files) override;
123 
124   lldb_private::Address
125   GetImageInfoAddress(lldb_private::Target *target) override;
126 
127   lldb_private::Address GetEntryPointAddress() override;
128 
129   lldb_private::Address GetBaseAddress() override;
130 
131   ObjectFile::Type CalculateType() override;
132 
133   ObjectFile::Strata CalculateStrata() override;
134 
135   size_t ReadSectionData(lldb_private::Section *section,
136                          lldb::offset_t section_offset, void *dst,
137                          size_t dst_len) override;
138 
139   size_t ReadSectionData(lldb_private::Section *section,
140                          lldb_private::DataExtractor &section_data) override;
141 
142   llvm::ArrayRef<elf::ELFProgramHeader> ProgramHeaders();
143   lldb_private::DataExtractor GetSegmentData(const elf::ELFProgramHeader &H);
144 
145   llvm::StringRef
146   StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const override;
147 
148   void RelocateSection(lldb_private::Section *section) override;
149 
150 protected:
151 
152   std::vector<LoadableData>
153   GetLoadableData(lldb_private::Target &target) override;
154 
155 private:
156   ObjectFileELF(const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp,
157                 lldb::offset_t data_offset, const lldb_private::FileSpec *file,
158                 lldb::offset_t offset, lldb::offset_t length);
159 
160   ObjectFileELF(const lldb::ModuleSP &module_sp,
161                 lldb::DataBufferSP &header_data_sp,
162                 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr);
163 
164   typedef std::vector<elf::ELFProgramHeader> ProgramHeaderColl;
165 
166   struct ELFSectionHeaderInfo : public elf::ELFSectionHeader {
167     lldb_private::ConstString section_name;
168   };
169 
170   typedef std::vector<ELFSectionHeaderInfo> SectionHeaderColl;
171   typedef SectionHeaderColl::iterator SectionHeaderCollIter;
172   typedef SectionHeaderColl::const_iterator SectionHeaderCollConstIter;
173 
174   typedef std::vector<elf::ELFDynamic> DynamicSymbolColl;
175   typedef DynamicSymbolColl::iterator DynamicSymbolCollIter;
176   typedef DynamicSymbolColl::const_iterator DynamicSymbolCollConstIter;
177 
178   typedef std::map<lldb::addr_t, lldb_private::AddressClass>
179       FileAddressToAddressClassMap;
180 
181   /// Version of this reader common to all plugins based on this class.
182   static const uint32_t m_plugin_version = 1;
183   static const uint32_t g_core_uuid_magic;
184 
185   /// ELF file header.
186   elf::ELFHeader m_header;
187 
188   /// ELF build ID.
189   lldb_private::UUID m_uuid;
190 
191   /// ELF .gnu_debuglink file and crc data if available.
192   std::string m_gnu_debuglink_file;
193   uint32_t m_gnu_debuglink_crc;
194 
195   /// Collection of program headers.
196   ProgramHeaderColl m_program_headers;
197 
198   /// Collection of section headers.
199   SectionHeaderColl m_section_headers;
200 
201   /// Collection of symbols from the dynamic table.
202   DynamicSymbolColl m_dynamic_symbols;
203 
204   /// List of file specifications corresponding to the modules (shared
205   /// libraries) on which this object file depends.
206   mutable std::unique_ptr<lldb_private::FileSpecList> m_filespec_up;
207 
208   /// Cached value of the entry point for this module.
209   lldb_private::Address m_entry_point_address;
210 
211   /// The architecture detected from parsing elf file contents.
212   lldb_private::ArchSpec m_arch_spec;
213 
214   /// The address class for each symbol in the elf file
215   FileAddressToAddressClassMap m_address_class_map;
216 
217   /// Returns the index of the given section header.
218   size_t SectionIndex(const SectionHeaderCollIter &I);
219 
220   /// Returns the index of the given section header.
221   size_t SectionIndex(const SectionHeaderCollConstIter &I) const;
222 
223   // Parses the ELF program headers.
224   static size_t GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
225                                      lldb_private::DataExtractor &object_data,
226                                      const elf::ELFHeader &header);
227 
228   // Finds PT_NOTE segments and calculates their crc sum.
229   static uint32_t
230   CalculateELFNotesSegmentsCRC32(const ProgramHeaderColl &program_headers,
231                                  lldb_private::DataExtractor &data);
232 
233   /// Parses all section headers present in this object file and populates
234   /// m_program_headers.  This method will compute the header list only once.
235   /// Returns true iff the headers have been successfully parsed.
236   bool ParseProgramHeaders();
237 
238   /// Parses all section headers present in this object file and populates
239   /// m_section_headers.  This method will compute the header list only once.
240   /// Returns the number of headers parsed.
241   size_t ParseSectionHeaders();
242 
243   lldb::SectionType GetSectionType(const ELFSectionHeaderInfo &H) const;
244 
245   static void ParseARMAttributes(lldb_private::DataExtractor &data,
246                                  uint64_t length,
247                                  lldb_private::ArchSpec &arch_spec);
248 
249   /// Parses the elf section headers and returns the uuid, debug link name,
250   /// crc, archspec.
251   static size_t GetSectionHeaderInfo(SectionHeaderColl &section_headers,
252                                      lldb_private::DataExtractor &object_data,
253                                      const elf::ELFHeader &header,
254                                      lldb_private::UUID &uuid,
255                                      std::string &gnu_debuglink_file,
256                                      uint32_t &gnu_debuglink_crc,
257                                      lldb_private::ArchSpec &arch_spec);
258 
259   /// Scans the dynamic section and locates all dependent modules (shared
260   /// libraries) populating m_filespec_up.  This method will compute the
261   /// dependent module list only once.  Returns the number of dependent
262   /// modules parsed.
263   size_t ParseDependentModules();
264 
265   /// Parses the dynamic symbol table and populates m_dynamic_symbols.  The
266   /// vector retains the order as found in the object file.  Returns the
267   /// number of dynamic symbols parsed.
268   size_t ParseDynamicSymbols();
269 
270   /// Populates m_symtab_up will all non-dynamic linker symbols.  This method
271   /// will parse the symbols only once.  Returns the number of symbols parsed.
272   unsigned ParseSymbolTable(lldb_private::Symtab *symbol_table,
273                             lldb::user_id_t start_id,
274                             lldb_private::Section *symtab);
275 
276   /// Helper routine for ParseSymbolTable().
277   unsigned ParseSymbols(lldb_private::Symtab *symbol_table,
278                         lldb::user_id_t start_id,
279                         lldb_private::SectionList *section_list,
280                         const size_t num_symbols,
281                         const lldb_private::DataExtractor &symtab_data,
282                         const lldb_private::DataExtractor &strtab_data);
283 
284   /// Scans the relocation entries and adds a set of artificial symbols to the
285   /// given symbol table for each PLT slot.  Returns the number of symbols
286   /// added.
287   unsigned ParseTrampolineSymbols(lldb_private::Symtab *symbol_table,
288                                   lldb::user_id_t start_id,
289                                   const ELFSectionHeaderInfo *rela_hdr,
290                                   lldb::user_id_t section_id);
291 
292   void ParseUnwindSymbols(lldb_private::Symtab *symbol_table,
293                           lldb_private::DWARFCallFrameInfo *eh_frame);
294 
295   /// Relocates debug sections
296   unsigned RelocateDebugSections(const elf::ELFSectionHeader *rel_hdr,
297                                  lldb::user_id_t rel_id,
298                                  lldb_private::Symtab *thetab);
299 
300   unsigned ApplyRelocations(lldb_private::Symtab *symtab,
301                             const elf::ELFHeader *hdr,
302                             const elf::ELFSectionHeader *rel_hdr,
303                             const elf::ELFSectionHeader *symtab_hdr,
304                             const elf::ELFSectionHeader *debug_hdr,
305                             lldb_private::DataExtractor &rel_data,
306                             lldb_private::DataExtractor &symtab_data,
307                             lldb_private::DataExtractor &debug_data,
308                             lldb_private::Section *rel_section);
309 
310   /// Loads the section name string table into m_shstr_data.  Returns the
311   /// number of bytes constituting the table.
312   size_t GetSectionHeaderStringTable();
313 
314   /// Utility method for looking up a section given its name.  Returns the
315   /// index of the corresponding section or zero if no section with the given
316   /// name can be found (note that section indices are always 1 based, and so
317   /// section index 0 is never valid).
318   lldb::user_id_t GetSectionIndexByName(const char *name);
319 
320   // Returns the ID of the first section that has the given type.
321   lldb::user_id_t GetSectionIndexByType(unsigned type);
322 
323   /// Returns the section header with the given id or NULL.
324   const ELFSectionHeaderInfo *GetSectionHeaderByIndex(lldb::user_id_t id);
325 
326   /// \name  ELF header dump routines
327   //@{
328   static void DumpELFHeader(lldb_private::Stream *s,
329                             const elf::ELFHeader &header);
330 
331   static void DumpELFHeader_e_ident_EI_DATA(lldb_private::Stream *s,
332                                             unsigned char ei_data);
333 
334   static void DumpELFHeader_e_type(lldb_private::Stream *s,
335                                    elf::elf_half e_type);
336   //@}
337 
338   /// \name ELF program header dump routines
339   //@{
340   void DumpELFProgramHeaders(lldb_private::Stream *s);
341 
342   static void DumpELFProgramHeader(lldb_private::Stream *s,
343                                    const elf::ELFProgramHeader &ph);
344 
345   static void DumpELFProgramHeader_p_type(lldb_private::Stream *s,
346                                           elf::elf_word p_type);
347 
348   static void DumpELFProgramHeader_p_flags(lldb_private::Stream *s,
349                                            elf::elf_word p_flags);
350   //@}
351 
352   /// \name ELF section header dump routines
353   //@{
354   void DumpELFSectionHeaders(lldb_private::Stream *s);
355 
356   static void DumpELFSectionHeader(lldb_private::Stream *s,
357                                    const ELFSectionHeaderInfo &sh);
358 
359   static void DumpELFSectionHeader_sh_type(lldb_private::Stream *s,
360                                            elf::elf_word sh_type);
361 
362   static void DumpELFSectionHeader_sh_flags(lldb_private::Stream *s,
363                                             elf::elf_xword sh_flags);
364   //@}
365 
366   /// ELF dependent module dump routine.
367   void DumpDependentModules(lldb_private::Stream *s);
368 
369   const elf::ELFDynamic *FindDynamicSymbol(unsigned tag);
370 
371   unsigned PLTRelocationType();
372 
373   static lldb_private::Status
374   RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
375                               lldb_private::ArchSpec &arch_spec,
376                               lldb_private::UUID &uuid);
377 
378   bool AnySegmentHasPhysicalAddress();
379 };
380 
381 #endif // liblldb_ObjectFileELF_h_
382