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