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