blob: a2febba9f9c743028dfcd3e5803935454844f4b3 [file] [log] [blame]
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001//===-- ObjectFileELF.cpp ------------------------------------- -*- C++ -*-===//
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002//
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#include "ObjectFileELF.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <algorithm>
Kate Stoneb9c1b512016-09-06 20:57:50 +000013#include <cassert>
Tamas Berghammer9fa11472015-10-27 10:43:27 +000014#include <unordered_map>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015
Stephen Wilson2ab0a582011-01-15 00:08:44 +000016#include "lldb/Core/ArchSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000017#include "lldb/Core/DataBuffer.h"
Stephen Wilsonf325ba92010-07-13 23:07:23 +000018#include "lldb/Core/FileSpecList.h"
Ed Mastec113ff82013-12-02 17:49:13 +000019#include "lldb/Core/Log.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000020#include "lldb/Core/Module.h"
Greg Claytonf4d6de62013-04-24 22:29:28 +000021#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000022#include "lldb/Core/PluginManager.h"
23#include "lldb/Core/Section.h"
Todd Fiala4339f3a2014-03-25 19:29:09 +000024#include "lldb/Core/Timer.h"
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +000025#include "lldb/Symbol/DWARFCallFrameInfo.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000026#include "lldb/Symbol/SymbolContext.h"
Steve Pucci9e02dac2014-02-06 19:02:19 +000027#include "lldb/Target/SectionLoadList.h"
Ed Maste54803652013-10-11 17:39:07 +000028#include "lldb/Target/Target.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000029#include "lldb/Utility/Error.h"
30#include "lldb/Utility/Stream.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000031
Stephen Wilson499b40e2011-03-30 16:07:05 +000032#include "llvm/ADT/PointerUnion.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000033#include "llvm/ADT/StringRef.h"
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +000034#include "llvm/Support/ARMBuildAttributes.h"
Zachary Turner736d4d82014-06-25 05:42:32 +000035#include "llvm/Support/MathExtras.h"
Sagar Thakurad5b55a2016-05-24 14:52:50 +000036#include "llvm/Support/MipsABIFlags.h"
Stephen Wilson499b40e2011-03-30 16:07:05 +000037
Kate Stoneb9c1b512016-09-06 20:57:50 +000038#define CASE_AND_STREAM(s, def, width) \
39 case def: \
40 s->Printf("%-*s", width, #def); \
41 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000042
Chris Lattner30fdc8d2010-06-08 16:52:24 +000043using namespace lldb;
44using namespace lldb_private;
Stephen Wilsonf325ba92010-07-13 23:07:23 +000045using namespace elf;
46using namespace llvm::ELF;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047
Stephen Wilson499b40e2011-03-30 16:07:05 +000048namespace {
Todd Fialab91de782014-06-27 16:52:49 +000049
50// ELF note owner definitions
51const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";
Kate Stoneb9c1b512016-09-06 20:57:50 +000052const char *const LLDB_NT_OWNER_GNU = "GNU";
53const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";
54const char *const LLDB_NT_OWNER_CSR = "csr";
Tamas Berghammerdb037d92015-03-18 10:36:27 +000055const char *const LLDB_NT_OWNER_ANDROID = "Android";
Kate Stoneb9c1b512016-09-06 20:57:50 +000056const char *const LLDB_NT_OWNER_CORE = "CORE";
57const char *const LLDB_NT_OWNER_LINUX = "LINUX";
Todd Fialab91de782014-06-27 16:52:49 +000058
59// ELF note type definitions
Kate Stoneb9c1b512016-09-06 20:57:50 +000060const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01;
Todd Fialab91de782014-06-27 16:52:49 +000061const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4;
62
Kate Stoneb9c1b512016-09-06 20:57:50 +000063const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;
64const elf_word LLDB_NT_GNU_ABI_SIZE = 16;
Todd Fialab91de782014-06-27 16:52:49 +000065
66const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03;
67
Kate Stoneb9c1b512016-09-06 20:57:50 +000068const elf_word LLDB_NT_NETBSD_ABI_TAG = 0x01;
69const elf_word LLDB_NT_NETBSD_ABI_SIZE = 4;
Todd Fialab91de782014-06-27 16:52:49 +000070
71// GNU ABI note OS constants
Kate Stoneb9c1b512016-09-06 20:57:50 +000072const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00;
73const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01;
Todd Fialab91de782014-06-27 16:52:49 +000074const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02;
75
Greg Claytonb704b692015-10-28 18:04:38 +000076// LLDB_NT_OWNER_CORE and LLDB_NT_OWNER_LINUX note contants
Kate Stoneb9c1b512016-09-06 20:57:50 +000077#define NT_PRSTATUS 1
78#define NT_PRFPREG 2
79#define NT_PRPSINFO 3
80#define NT_TASKSTRUCT 4
81#define NT_AUXV 6
82#define NT_SIGINFO 0x53494749
83#define NT_FILE 0x46494c45
84#define NT_PRXFPREG 0x46e62b7f
85#define NT_PPC_VMX 0x100
86#define NT_PPC_SPE 0x101
87#define NT_PPC_VSX 0x102
88#define NT_386_TLS 0x200
89#define NT_386_IOPERM 0x201
90#define NT_X86_XSTATE 0x202
91#define NT_S390_HIGH_GPRS 0x300
92#define NT_S390_TIMER 0x301
93#define NT_S390_TODCMP 0x302
94#define NT_S390_TODPREG 0x303
95#define NT_S390_CTRS 0x304
96#define NT_S390_PREFIX 0x305
97#define NT_S390_LAST_BREAK 0x306
98#define NT_S390_SYSTEM_CALL 0x307
99#define NT_S390_TDB 0x308
100#define NT_S390_VXRS_LOW 0x309
101#define NT_S390_VXRS_HIGH 0x30a
102#define NT_ARM_VFP 0x400
103#define NT_ARM_TLS 0x401
104#define NT_ARM_HW_BREAK 0x402
105#define NT_ARM_HW_WATCH 0x403
106#define NT_ARM_SYSTEM_CALL 0x404
107#define NT_METAG_CBUF 0x500
108#define NT_METAG_RPIPE 0x501
109#define NT_METAG_TLS 0x502
Greg Claytonb704b692015-10-28 18:04:38 +0000110
Stephen Wilson499b40e2011-03-30 16:07:05 +0000111//===----------------------------------------------------------------------===//
112/// @class ELFRelocation
113/// @brief Generic wrapper for ELFRel and ELFRela.
114///
115/// This helper class allows us to parse both ELFRel and ELFRela relocation
116/// entries in a generic manner.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000117class ELFRelocation {
Stephen Wilson499b40e2011-03-30 16:07:05 +0000118public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000119 /// Constructs an ELFRelocation entry with a personality as given by @p
120 /// type.
121 ///
122 /// @param type Either DT_REL or DT_RELA. Any other value is invalid.
123 ELFRelocation(unsigned type);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000124
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125 ~ELFRelocation();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000126
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 static unsigned RelocType32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 static unsigned RelocType64(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 static unsigned RelocSymbol32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 static unsigned RelocSymbol64(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 static unsigned RelocOffset32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 static unsigned RelocOffset64(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 static unsigned RelocAddend32(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 static unsigned RelocAddend64(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000144
Stephen Wilson499b40e2011-03-30 16:07:05 +0000145private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000146 typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;
Stephen Wilson499b40e2011-03-30 16:07:05 +0000147
Kate Stoneb9c1b512016-09-06 20:57:50 +0000148 RelocUnion reloc;
Stephen Wilson499b40e2011-03-30 16:07:05 +0000149};
150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151ELFRelocation::ELFRelocation(unsigned type) {
152 if (type == DT_REL || type == SHT_REL)
153 reloc = new ELFRel();
154 else if (type == DT_RELA || type == SHT_RELA)
155 reloc = new ELFRela();
156 else {
157 assert(false && "unexpected relocation type");
158 reloc = static_cast<ELFRel *>(NULL);
159 }
Stephen Wilson499b40e2011-03-30 16:07:05 +0000160}
161
Kate Stoneb9c1b512016-09-06 20:57:50 +0000162ELFRelocation::~ELFRelocation() {
163 if (reloc.is<ELFRel *>())
164 delete reloc.get<ELFRel *>();
165 else
166 delete reloc.get<ELFRela *>();
Stephen Wilson499b40e2011-03-30 16:07:05 +0000167}
168
Kate Stoneb9c1b512016-09-06 20:57:50 +0000169bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,
170 lldb::offset_t *offset) {
171 if (reloc.is<ELFRel *>())
172 return reloc.get<ELFRel *>()->Parse(data, offset);
173 else
174 return reloc.get<ELFRela *>()->Parse(data, offset);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000175}
176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {
178 if (rel.reloc.is<ELFRel *>())
179 return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>());
180 else
181 return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000182}
183
Kate Stoneb9c1b512016-09-06 20:57:50 +0000184unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {
185 if (rel.reloc.is<ELFRel *>())
186 return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>());
187 else
188 return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000189}
190
Kate Stoneb9c1b512016-09-06 20:57:50 +0000191unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {
192 if (rel.reloc.is<ELFRel *>())
193 return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>());
194 else
195 return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000196}
197
Kate Stoneb9c1b512016-09-06 20:57:50 +0000198unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {
199 if (rel.reloc.is<ELFRel *>())
200 return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>());
201 else
202 return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000203}
204
Kate Stoneb9c1b512016-09-06 20:57:50 +0000205unsigned ELFRelocation::RelocOffset32(const ELFRelocation &rel) {
206 if (rel.reloc.is<ELFRel *>())
207 return rel.reloc.get<ELFRel *>()->r_offset;
208 else
209 return rel.reloc.get<ELFRela *>()->r_offset;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000210}
211
Kate Stoneb9c1b512016-09-06 20:57:50 +0000212unsigned ELFRelocation::RelocOffset64(const ELFRelocation &rel) {
213 if (rel.reloc.is<ELFRel *>())
214 return rel.reloc.get<ELFRel *>()->r_offset;
215 else
216 return rel.reloc.get<ELFRela *>()->r_offset;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000217}
218
Kate Stoneb9c1b512016-09-06 20:57:50 +0000219unsigned ELFRelocation::RelocAddend32(const ELFRelocation &rel) {
220 if (rel.reloc.is<ELFRel *>())
221 return 0;
222 else
223 return rel.reloc.get<ELFRela *>()->r_addend;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000224}
225
Kate Stoneb9c1b512016-09-06 20:57:50 +0000226unsigned ELFRelocation::RelocAddend64(const ELFRelocation &rel) {
227 if (rel.reloc.is<ELFRel *>())
228 return 0;
229 else
230 return rel.reloc.get<ELFRela *>()->r_addend;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000231}
232
Stephen Wilson499b40e2011-03-30 16:07:05 +0000233} // end anonymous namespace
234
Kate Stoneb9c1b512016-09-06 20:57:50 +0000235bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {
236 // Read all fields.
237 if (data.GetU32(offset, &n_namesz, 3) == NULL)
238 return false;
Ed Mastec113ff82013-12-02 17:49:13 +0000239
Kate Stoneb9c1b512016-09-06 20:57:50 +0000240 // The name field is required to be nul-terminated, and n_namesz
241 // includes the terminating nul in observed implementations (contrary
242 // to the ELF-64 spec). A special case is needed for cores generated
243 // by some older Linux versions, which write a note named "CORE"
244 // without a nul terminator and n_namesz = 4.
245 if (n_namesz == 4) {
246 char buf[4];
247 if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)
248 return false;
249 if (strncmp(buf, "CORE", 4) == 0) {
250 n_name = "CORE";
251 *offset += 4;
252 return true;
Ed Mastec113ff82013-12-02 17:49:13 +0000253 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 }
Ed Mastec113ff82013-12-02 17:49:13 +0000255
Kate Stoneb9c1b512016-09-06 20:57:50 +0000256 const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));
257 if (cstr == NULL) {
258 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
259 if (log)
260 log->Printf("Failed to parse note name lacking nul terminator");
Ed Mastec113ff82013-12-02 17:49:13 +0000261
Kate Stoneb9c1b512016-09-06 20:57:50 +0000262 return false;
263 }
264 n_name = cstr;
265 return true;
Ed Mastec113ff82013-12-02 17:49:13 +0000266}
267
Kate Stoneb9c1b512016-09-06 20:57:50 +0000268static uint32_t kalimbaVariantFromElfFlags(const elf::elf_word e_flags) {
269 const uint32_t dsp_rev = e_flags & 0xFF;
270 uint32_t kal_arch_variant = LLDB_INVALID_CPUTYPE;
271 switch (dsp_rev) {
272 // TODO(mg11) Support more variants
273 case 10:
274 kal_arch_variant = llvm::Triple::KalimbaSubArch_v3;
275 break;
276 case 14:
277 kal_arch_variant = llvm::Triple::KalimbaSubArch_v4;
278 break;
279 case 17:
280 case 20:
281 kal_arch_variant = llvm::Triple::KalimbaSubArch_v5;
282 break;
283 default:
284 break;
285 }
286 return kal_arch_variant;
Matthew Gardiner5f675792014-08-27 12:09:39 +0000287}
288
Kate Stoneb9c1b512016-09-06 20:57:50 +0000289static uint32_t mipsVariantFromElfFlags(const elf::elf_word e_flags,
290 uint32_t endian) {
291 const uint32_t mips_arch = e_flags & llvm::ELF::EF_MIPS_ARCH;
292 uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000293
Kate Stoneb9c1b512016-09-06 20:57:50 +0000294 switch (mips_arch) {
295 case llvm::ELF::EF_MIPS_ARCH_1:
296 case llvm::ELF::EF_MIPS_ARCH_2:
297 case llvm::ELF::EF_MIPS_ARCH_32:
298 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
299 : ArchSpec::eMIPSSubType_mips32;
300 case llvm::ELF::EF_MIPS_ARCH_32R2:
301 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el
302 : ArchSpec::eMIPSSubType_mips32r2;
303 case llvm::ELF::EF_MIPS_ARCH_32R6:
304 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el
305 : ArchSpec::eMIPSSubType_mips32r6;
306 case llvm::ELF::EF_MIPS_ARCH_3:
307 case llvm::ELF::EF_MIPS_ARCH_4:
308 case llvm::ELF::EF_MIPS_ARCH_5:
309 case llvm::ELF::EF_MIPS_ARCH_64:
310 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
311 : ArchSpec::eMIPSSubType_mips64;
312 case llvm::ELF::EF_MIPS_ARCH_64R2:
313 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el
314 : ArchSpec::eMIPSSubType_mips64r2;
315 case llvm::ELF::EF_MIPS_ARCH_64R6:
316 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el
317 : ArchSpec::eMIPSSubType_mips64r6;
318 default:
319 break;
320 }
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000321
Kate Stoneb9c1b512016-09-06 20:57:50 +0000322 return arch_variant;
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000323}
324
Kate Stoneb9c1b512016-09-06 20:57:50 +0000325static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {
326 if (header.e_machine == llvm::ELF::EM_MIPS)
327 return mipsVariantFromElfFlags(header.e_flags, header.e_ident[EI_DATA]);
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000328
Kate Stoneb9c1b512016-09-06 20:57:50 +0000329 return llvm::ELF::EM_CSR_KALIMBA == header.e_machine
330 ? kalimbaVariantFromElfFlags(header.e_flags)
331 : LLDB_INVALID_CPUTYPE;
Matthew Gardiner5f675792014-08-27 12:09:39 +0000332}
333
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000334//! The kalimba toolchain identifies a code section as being
335//! one with the SHT_PROGBITS set in the section sh_type and the top
336//! bit in the 32-bit address field set.
337static lldb::SectionType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000338kalimbaSectionType(const elf::ELFHeader &header,
339 const elf::ELFSectionHeader &sect_hdr) {
340 if (llvm::ELF::EM_CSR_KALIMBA != header.e_machine) {
Matthew Gardiner6e7b0a02014-10-15 08:21:54 +0000341 return eSectionTypeOther;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 }
343
344 if (llvm::ELF::SHT_NOBITS == sect_hdr.sh_type) {
345 return eSectionTypeZeroFill;
346 }
347
348 if (llvm::ELF::SHT_PROGBITS == sect_hdr.sh_type) {
349 const lldb::addr_t KAL_CODE_BIT = 1 << 31;
350 return KAL_CODE_BIT & sect_hdr.sh_addr ? eSectionTypeCode
351 : eSectionTypeData;
352 }
353
354 return eSectionTypeOther;
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000355}
356
Todd Fiala4339f3a2014-03-25 19:29:09 +0000357// Arbitrary constant used as UUID prefix for core files.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000359
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000360//------------------------------------------------------------------
361// Static methods.
362//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000363void ObjectFileELF::Initialize() {
364 PluginManager::RegisterPlugin(GetPluginNameStatic(),
365 GetPluginDescriptionStatic(), CreateInstance,
366 CreateMemoryInstance, GetModuleSpecifications);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000367}
368
Kate Stoneb9c1b512016-09-06 20:57:50 +0000369void ObjectFileELF::Terminate() {
370 PluginManager::UnregisterPlugin(CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000371}
372
Kate Stoneb9c1b512016-09-06 20:57:50 +0000373lldb_private::ConstString ObjectFileELF::GetPluginNameStatic() {
374 static ConstString g_name("elf");
375 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000376}
377
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378const char *ObjectFileELF::GetPluginDescriptionStatic() {
379 return "ELF object file reader.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000380}
381
Kate Stoneb9c1b512016-09-06 20:57:50 +0000382ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp,
383 DataBufferSP &data_sp,
384 lldb::offset_t data_offset,
385 const lldb_private::FileSpec *file,
386 lldb::offset_t file_offset,
387 lldb::offset_t length) {
388 if (!data_sp) {
389 data_sp = file->MemoryMapFileContentsIfLocal(file_offset, length);
390 data_offset = 0;
391 }
392
393 if (data_sp &&
394 data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
395 const uint8_t *magic = data_sp->GetBytes() + data_offset;
396 if (ELFHeader::MagicBytesMatch(magic)) {
397 // Update the data to contain the entire file if it doesn't already
398 if (data_sp->GetByteSize() < length) {
Greg Clayton736888c2015-02-23 23:47:09 +0000399 data_sp = file->MemoryMapFileContentsIfLocal(file_offset, length);
Greg Clayton5ce9c562013-02-06 17:22:03 +0000400 data_offset = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000401 magic = data_sp->GetBytes();
402 }
403 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
404 if (address_size == 4 || address_size == 8) {
405 std::unique_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF(
406 module_sp, data_sp, data_offset, file, file_offset, length));
407 ArchSpec spec;
408 if (objfile_ap->GetArchitecture(spec) &&
409 objfile_ap->SetModulesArchitecture(spec))
410 return objfile_ap.release();
411 }
Greg Clayton5ce9c562013-02-06 17:22:03 +0000412 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000413 }
414 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000415}
416
Kate Stoneb9c1b512016-09-06 20:57:50 +0000417ObjectFile *ObjectFileELF::CreateMemoryInstance(
418 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
419 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
420 if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) {
421 const uint8_t *magic = data_sp->GetBytes();
422 if (ELFHeader::MagicBytesMatch(magic)) {
423 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
424 if (address_size == 4 || address_size == 8) {
425 std::auto_ptr<ObjectFileELF> objfile_ap(
426 new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));
427 ArchSpec spec;
428 if (objfile_ap->GetArchitecture(spec) &&
429 objfile_ap->SetModulesArchitecture(spec))
430 return objfile_ap.release();
431 }
Andrew MacPherson17220c12014-03-05 10:12:43 +0000432 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000433 }
434 return NULL;
Greg Claytonc9660542012-02-05 02:38:54 +0000435}
436
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp,
438 lldb::addr_t data_offset,
439 lldb::addr_t data_length) {
440 if (data_sp &&
441 data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
442 const uint8_t *magic = data_sp->GetBytes() + data_offset;
443 return ELFHeader::MagicBytesMatch(magic);
444 }
445 return false;
Michael Sartain9f0013d2013-05-17 00:20:21 +0000446}
Greg Claytonc9660542012-02-05 02:38:54 +0000447
Michael Sartain9f4517a2013-07-03 01:52:14 +0000448/*
449 * crc function from http://svnweb.freebsd.org/base/head/sys/libkern/crc32.c
450 *
451 * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or
452 * code or tables extracted from it, as desired without restriction.
453 */
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454static uint32_t calc_crc32(uint32_t crc, const void *buf, size_t size) {
455 static const uint32_t g_crc32_tab[] = {
456 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
457 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
458 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
459 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
460 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
461 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
462 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
463 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
464 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
465 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
466 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
467 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
468 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
469 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
470 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
471 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
472 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
473 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
474 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
475 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
476 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
477 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
478 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
479 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
480 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
481 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
482 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
483 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
484 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
485 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
486 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
487 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
488 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
489 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
490 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
491 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
492 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
493 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
494 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
495 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
496 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
497 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
498 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};
499 const uint8_t *p = (const uint8_t *)buf;
Michael Sartain9f4517a2013-07-03 01:52:14 +0000500
Kate Stoneb9c1b512016-09-06 20:57:50 +0000501 crc = crc ^ ~0U;
502 while (size--)
503 crc = g_crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
504 return crc ^ ~0U;
Michael Sartain9f4517a2013-07-03 01:52:14 +0000505}
506
Kate Stoneb9c1b512016-09-06 20:57:50 +0000507static uint32_t calc_gnu_debuglink_crc32(const void *buf, size_t size) {
508 return calc_crc32(0U, buf, size);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000509}
510
Kate Stoneb9c1b512016-09-06 20:57:50 +0000511uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32(
512 const ProgramHeaderColl &program_headers, DataExtractor &object_data) {
513 typedef ProgramHeaderCollConstIter Iter;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000514
Kate Stoneb9c1b512016-09-06 20:57:50 +0000515 uint32_t core_notes_crc = 0;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000516
Kate Stoneb9c1b512016-09-06 20:57:50 +0000517 for (Iter I = program_headers.begin(); I != program_headers.end(); ++I) {
518 if (I->p_type == llvm::ELF::PT_NOTE) {
519 const elf_off ph_offset = I->p_offset;
520 const size_t ph_size = I->p_filesz;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000521
Kate Stoneb9c1b512016-09-06 20:57:50 +0000522 DataExtractor segment_data;
523 if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {
524 // The ELF program header contained incorrect data,
525 // probably corefile is incomplete or corrupted.
526 break;
527 }
Todd Fiala4339f3a2014-03-25 19:29:09 +0000528
Kate Stoneb9c1b512016-09-06 20:57:50 +0000529 core_notes_crc = calc_crc32(core_notes_crc, segment_data.GetDataStart(),
530 segment_data.GetByteSize());
Todd Fiala4339f3a2014-03-25 19:29:09 +0000531 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000532 }
Todd Fiala4339f3a2014-03-25 19:29:09 +0000533
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 return core_notes_crc;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000535}
536
Kate Stoneb9c1b512016-09-06 20:57:50 +0000537static const char *OSABIAsCString(unsigned char osabi_byte) {
538#define _MAKE_OSABI_CASE(x) \
539 case x: \
540 return #x
541 switch (osabi_byte) {
542 _MAKE_OSABI_CASE(ELFOSABI_NONE);
543 _MAKE_OSABI_CASE(ELFOSABI_HPUX);
544 _MAKE_OSABI_CASE(ELFOSABI_NETBSD);
545 _MAKE_OSABI_CASE(ELFOSABI_GNU);
546 _MAKE_OSABI_CASE(ELFOSABI_HURD);
547 _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);
548 _MAKE_OSABI_CASE(ELFOSABI_AIX);
549 _MAKE_OSABI_CASE(ELFOSABI_IRIX);
550 _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);
551 _MAKE_OSABI_CASE(ELFOSABI_TRU64);
552 _MAKE_OSABI_CASE(ELFOSABI_MODESTO);
553 _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);
554 _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);
555 _MAKE_OSABI_CASE(ELFOSABI_NSK);
556 _MAKE_OSABI_CASE(ELFOSABI_AROS);
557 _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);
558 _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);
559 _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);
560 _MAKE_OSABI_CASE(ELFOSABI_ARM);
561 _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);
562 default:
563 return "<unknown-osabi>";
564 }
Todd Fialab91de782014-06-27 16:52:49 +0000565#undef _MAKE_OSABI_CASE
566}
567
Ed Mastef6a13122015-06-05 13:03:08 +0000568//
569// WARNING : This function is being deprecated
570// It's functionality has moved to ArchSpec::SetArchitecture
571// This function is only being kept to validate the move.
572//
573// TODO : Remove this function
Kate Stoneb9c1b512016-09-06 20:57:50 +0000574static bool GetOsFromOSABI(unsigned char osabi_byte,
575 llvm::Triple::OSType &ostype) {
576 switch (osabi_byte) {
577 case ELFOSABI_AIX:
578 ostype = llvm::Triple::OSType::AIX;
579 break;
580 case ELFOSABI_FREEBSD:
581 ostype = llvm::Triple::OSType::FreeBSD;
582 break;
583 case ELFOSABI_GNU:
584 ostype = llvm::Triple::OSType::Linux;
585 break;
586 case ELFOSABI_NETBSD:
587 ostype = llvm::Triple::OSType::NetBSD;
588 break;
589 case ELFOSABI_OPENBSD:
590 ostype = llvm::Triple::OSType::OpenBSD;
591 break;
592 case ELFOSABI_SOLARIS:
593 ostype = llvm::Triple::OSType::Solaris;
594 break;
595 default:
596 ostype = llvm::Triple::OSType::UnknownOS;
597 }
598 return ostype != llvm::Triple::OSType::UnknownOS;
Todd Fialab91de782014-06-27 16:52:49 +0000599}
600
Kate Stoneb9c1b512016-09-06 20:57:50 +0000601size_t ObjectFileELF::GetModuleSpecifications(
602 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
603 lldb::offset_t data_offset, lldb::offset_t file_offset,
604 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
605 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
Todd Fialab91de782014-06-27 16:52:49 +0000606
Kate Stoneb9c1b512016-09-06 20:57:50 +0000607 const size_t initial_count = specs.GetSize();
Michael Sartainc836ae72013-05-23 20:57:03 +0000608
Kate Stoneb9c1b512016-09-06 20:57:50 +0000609 if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
610 DataExtractor data;
611 data.SetData(data_sp);
612 elf::ELFHeader header;
Pavel Labath23ccc292017-01-31 23:09:46 +0000613 lldb::offset_t header_offset = data_offset;
614 if (header.Parse(data, &header_offset)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000615 if (data_sp) {
616 ModuleSpec spec(file);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000617
Kate Stoneb9c1b512016-09-06 20:57:50 +0000618 const uint32_t sub_type = subTypeFromElfHeader(header);
619 spec.GetArchitecture().SetArchitecture(
620 eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000621
Kate Stoneb9c1b512016-09-06 20:57:50 +0000622 if (spec.GetArchitecture().IsValid()) {
623 llvm::Triple::OSType ostype;
624 llvm::Triple::VendorType vendor;
625 llvm::Triple::OSType spec_ostype =
626 spec.GetArchitecture().GetTriple().getOS();
Todd Fialab91de782014-06-27 16:52:49 +0000627
Kate Stoneb9c1b512016-09-06 20:57:50 +0000628 if (log)
629 log->Printf("ObjectFileELF::%s file '%s' module OSABI: %s",
630 __FUNCTION__, file.GetPath().c_str(),
631 OSABIAsCString(header.e_ident[EI_OSABI]));
Ed Mastef6a13122015-06-05 13:03:08 +0000632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 // SetArchitecture should have set the vendor to unknown
634 vendor = spec.GetArchitecture().GetTriple().getVendor();
635 assert(vendor == llvm::Triple::UnknownVendor);
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +0000636 UNUSED_IF_ASSERT_DISABLED(vendor);
Ed Mastef6a13122015-06-05 13:03:08 +0000637
Kate Stoneb9c1b512016-09-06 20:57:50 +0000638 //
639 // Validate it is ok to remove GetOsFromOSABI
640 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
641 assert(spec_ostype == ostype);
642 if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
643 if (log)
644 log->Printf("ObjectFileELF::%s file '%s' set ELF module OS type "
645 "from ELF header OSABI.",
646 __FUNCTION__, file.GetPath().c_str());
647 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000648
Pavel Labath23ccc292017-01-31 23:09:46 +0000649 // In case there is header extension in the section #0, the header
650 // we parsed above could have sentinel values for e_phnum, e_shnum,
651 // and e_shstrndx. In this case we need to reparse the header
652 // with a bigger data source to get the actual values.
653 size_t section_header_end = header.e_shoff + header.e_shentsize;
654 if (header.HasHeaderExtension() &&
655 section_header_end > data_sp->GetByteSize()) {
656 data_sp = file.MemoryMapFileContentsIfLocal (file_offset,
657 section_header_end);
658 data.SetData(data_sp);
659 lldb::offset_t header_offset = data_offset;
660 header.Parse(data, &header_offset);
661 }
662
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 // Try to get the UUID from the section list. Usually that's at the
664 // end, so
665 // map the file in if we don't have it already.
Pavel Labath23ccc292017-01-31 23:09:46 +0000666 section_header_end =
Kate Stoneb9c1b512016-09-06 20:57:50 +0000667 header.e_shoff + header.e_shnum * header.e_shentsize;
668 if (section_header_end > data_sp->GetByteSize()) {
669 data_sp = file.MemoryMapFileContentsIfLocal(file_offset,
670 section_header_end);
671 data.SetData(data_sp);
672 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000673
Kate Stoneb9c1b512016-09-06 20:57:50 +0000674 uint32_t gnu_debuglink_crc = 0;
675 std::string gnu_debuglink_file;
676 SectionHeaderColl section_headers;
677 lldb_private::UUID &uuid = spec.GetUUID();
Michael Sartain9f4517a2013-07-03 01:52:14 +0000678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 using namespace std::placeholders;
680 const SetDataFunction set_data =
681 std::bind(&ObjectFileELF::SetData, std::cref(data), _1, _2, _3);
682 GetSectionHeaderInfo(section_headers, set_data, header, uuid,
683 gnu_debuglink_file, gnu_debuglink_crc,
684 spec.GetArchitecture());
Ravitheja Addepally15f89c42016-01-19 12:55:21 +0000685
Kate Stoneb9c1b512016-09-06 20:57:50 +0000686 llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
Todd Fialab91de782014-06-27 16:52:49 +0000687
Kate Stoneb9c1b512016-09-06 20:57:50 +0000688 if (log)
689 log->Printf("ObjectFileELF::%s file '%s' module set to triple: %s "
690 "(architecture %s)",
691 __FUNCTION__, file.GetPath().c_str(),
692 spec_triple.getTriple().c_str(),
693 spec.GetArchitecture().GetArchitectureName());
Todd Fialab91de782014-06-27 16:52:49 +0000694
Kate Stoneb9c1b512016-09-06 20:57:50 +0000695 if (!uuid.IsValid()) {
696 uint32_t core_notes_crc = 0;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 if (!gnu_debuglink_crc) {
699 lldb_private::Timer scoped_timer(
700 LLVM_PRETTY_FUNCTION,
701 "Calculating module crc32 %s with size %" PRIu64 " KiB",
702 file.GetLastPathComponent().AsCString(),
703 (file.GetByteSize() - file_offset) / 1024);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 // For core files - which usually don't happen to have a
706 // gnu_debuglink,
707 // and are pretty bulky - calculating whole contents crc32 would
708 // be too much of luxury.
709 // Thus we will need to fallback to something simpler.
710 if (header.e_type == llvm::ELF::ET_CORE) {
711 size_t program_headers_end =
712 header.e_phoff + header.e_phnum * header.e_phentsize;
713 if (program_headers_end > data_sp->GetByteSize()) {
714 data_sp = file.MemoryMapFileContentsIfLocal(
715 file_offset, program_headers_end);
716 data.SetData(data_sp);
Michael Sartain9f0013d2013-05-17 00:20:21 +0000717 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 ProgramHeaderColl program_headers;
719 GetProgramHeaderInfo(program_headers, set_data, header);
Michael Sartainc836ae72013-05-23 20:57:03 +0000720
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 size_t segment_data_end = 0;
722 for (ProgramHeaderCollConstIter I = program_headers.begin();
723 I != program_headers.end(); ++I) {
724 segment_data_end = std::max<unsigned long long>(
725 I->p_offset + I->p_filesz, segment_data_end);
726 }
727
728 if (segment_data_end > data_sp->GetByteSize()) {
729 data_sp = file.MemoryMapFileContentsIfLocal(file_offset,
730 segment_data_end);
731 data.SetData(data_sp);
732 }
733
734 core_notes_crc =
735 CalculateELFNotesSegmentsCRC32(program_headers, data);
736 } else {
737 // Need to map entire file into memory to calculate the crc.
738 data_sp =
739 file.MemoryMapFileContentsIfLocal(file_offset, SIZE_MAX);
740 data.SetData(data_sp);
741 gnu_debuglink_crc = calc_gnu_debuglink_crc32(
742 data.GetDataStart(), data.GetByteSize());
743 }
744 }
745 if (gnu_debuglink_crc) {
746 // Use 4 bytes of crc from the .gnu_debuglink section.
747 uint32_t uuidt[4] = {gnu_debuglink_crc, 0, 0, 0};
748 uuid.SetBytes(uuidt, sizeof(uuidt));
749 } else if (core_notes_crc) {
750 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
751 // it look different form
752 // .gnu_debuglink crc followed by 4 bytes of note segments crc.
753 uint32_t uuidt[4] = {g_core_uuid_magic, core_notes_crc, 0, 0};
754 uuid.SetBytes(uuidt, sizeof(uuidt));
755 }
756 }
757
758 specs.Append(spec);
759 }
760 }
761 }
762 }
763
764 return specs.GetSize() - initial_count;
Greg Claytonf4d6de62013-04-24 22:29:28 +0000765}
766
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000767//------------------------------------------------------------------
768// PluginInterface protocol
769//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000770lldb_private::ConstString ObjectFileELF::GetPluginName() {
771 return GetPluginNameStatic();
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000772}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000773
Kate Stoneb9c1b512016-09-06 20:57:50 +0000774uint32_t ObjectFileELF::GetPluginVersion() { return m_plugin_version; }
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000775//------------------------------------------------------------------
776// ObjectFile protocol
777//------------------------------------------------------------------
778
Kate Stoneb9c1b512016-09-06 20:57:50 +0000779ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
780 DataBufferSP &data_sp, lldb::offset_t data_offset,
781 const FileSpec *file, lldb::offset_t file_offset,
782 lldb::offset_t length)
783 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
784 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
785 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
786 m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
787 if (file)
788 m_file = *file;
789 ::memset(&m_header, 0, sizeof(m_header));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000790}
791
Kate Stoneb9c1b512016-09-06 20:57:50 +0000792ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
793 DataBufferSP &header_data_sp,
794 const lldb::ProcessSP &process_sp,
795 addr_t header_addr)
796 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
797 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
798 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
799 m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
800 ::memset(&m_header, 0, sizeof(m_header));
Andrew MacPherson17220c12014-03-05 10:12:43 +0000801}
802
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803ObjectFileELF::~ObjectFileELF() {}
804
805bool ObjectFileELF::IsExecutable() const {
806 return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000807}
808
Kate Stoneb9c1b512016-09-06 20:57:50 +0000809bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
810 bool value_is_offset) {
811 ModuleSP module_sp = GetModule();
812 if (module_sp) {
813 size_t num_loaded_sections = 0;
814 SectionList *section_list = GetSectionList();
815 if (section_list) {
816 if (!value_is_offset) {
817 bool found_offset = false;
818 for (size_t i = 0, count = GetProgramHeaderCount(); i < count; ++i) {
819 const elf::ELFProgramHeader *header = GetProgramHeaderByIndex(i);
820 if (header == nullptr)
821 continue;
Jim Ingham5aee1622010-08-09 23:31:02 +0000822
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 if (header->p_type != PT_LOAD || header->p_offset != 0)
824 continue;
Tamas Berghammerf2561842015-06-30 10:41:23 +0000825
Kate Stoneb9c1b512016-09-06 20:57:50 +0000826 value = value - header->p_vaddr;
827 found_offset = true;
828 break;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000829 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 if (!found_offset)
831 return false;
832 }
833
834 const size_t num_sections = section_list->GetSize();
835 size_t sect_idx = 0;
836
837 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
838 // Iterate through the object file sections to find all
839 // of the sections that have SHF_ALLOC in their flag bits.
840 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
841 if (section_sp && section_sp->Test(SHF_ALLOC)) {
842 lldb::addr_t load_addr = section_sp->GetFileAddress();
843 // We don't want to update the load address of a section with type
844 // eSectionTypeAbsoluteAddress as they already have the absolute load
845 // address
846 // already specified
847 if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
848 load_addr += value;
849
850 // On 32-bit systems the load address have to fit into 4 bytes. The
851 // rest of
852 // the bytes are the overflow from the addition.
853 if (GetAddressByteSize() == 4)
854 load_addr &= 0xFFFFFFFF;
855
856 if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
857 load_addr))
858 ++num_loaded_sections;
859 }
860 }
861 return num_loaded_sections > 0;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000862 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000863 }
864 return false;
865}
866
867ByteOrder ObjectFileELF::GetByteOrder() const {
868 if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
869 return eByteOrderBig;
870 if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
871 return eByteOrderLittle;
872 return eByteOrderInvalid;
873}
874
875uint32_t ObjectFileELF::GetAddressByteSize() const {
876 return m_data.GetAddressByteSize();
877}
878
879AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
880 Symtab *symtab = GetSymtab();
881 if (!symtab)
882 return eAddressClassUnknown;
883
884 // The address class is determined based on the symtab. Ask it from the object
885 // file what
886 // contains the symtab information.
887 ObjectFile *symtab_objfile = symtab->GetObjectFile();
888 if (symtab_objfile != nullptr && symtab_objfile != this)
889 return symtab_objfile->GetAddressClass(file_addr);
890
891 auto res = ObjectFile::GetAddressClass(file_addr);
892 if (res != eAddressClassCode)
893 return res;
894
895 auto ub = m_address_class_map.upper_bound(file_addr);
896 if (ub == m_address_class_map.begin()) {
897 // No entry in the address class map before the address. Return
898 // default address class for an address in a code section.
899 return eAddressClassCode;
900 }
901
902 // Move iterator to the address class entry preceding address
903 --ub;
904
905 return ub->second;
906}
907
908size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
909 return std::distance(m_section_headers.begin(), I) + 1u;
910}
911
912size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
913 return std::distance(m_section_headers.begin(), I) + 1u;
914}
915
916bool ObjectFileELF::ParseHeader() {
917 lldb::offset_t offset = 0;
918 if (!m_header.Parse(m_data, &offset))
Tamas Berghammer42ecef32015-08-24 10:21:55 +0000919 return false;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000920
Kate Stoneb9c1b512016-09-06 20:57:50 +0000921 if (!IsInMemory())
Tamas Berghammerf2561842015-06-30 10:41:23 +0000922 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000923
924 // For in memory object files m_data might not contain the full object file.
925 // Try to load it
926 // until the end of the "Section header table" what is at the end of the ELF
927 // file.
928 addr_t file_size = m_header.e_shoff + m_header.e_shnum * m_header.e_shentsize;
929 if (m_data.GetByteSize() < file_size) {
930 ProcessSP process_sp(m_process_wp.lock());
931 if (!process_sp)
932 return false;
933
934 DataBufferSP data_sp = ReadMemory(process_sp, m_memory_addr, file_size);
935 if (!data_sp)
936 return false;
937 m_data.SetData(data_sp, 0, file_size);
938 }
939
940 return true;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000941}
942
Kate Stoneb9c1b512016-09-06 20:57:50 +0000943bool ObjectFileELF::GetUUID(lldb_private::UUID *uuid) {
944 // Need to parse the section list to get the UUIDs, so make sure that's been
945 // done.
946 if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000947 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000948
949 if (m_uuid.IsValid()) {
950 // We have the full build id uuid.
951 *uuid = m_uuid;
952 return true;
953 } else if (GetType() == ObjectFile::eTypeCoreFile) {
954 uint32_t core_notes_crc = 0;
955
956 if (!ParseProgramHeaders())
957 return false;
958
959 core_notes_crc = CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
960
961 if (core_notes_crc) {
962 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
963 // look different form .gnu_debuglink crc - followed by 4 bytes of note
964 // segments crc.
965 uint32_t uuidt[4] = {g_core_uuid_magic, core_notes_crc, 0, 0};
966 m_uuid.SetBytes(uuidt, sizeof(uuidt));
967 }
968 } else {
969 if (!m_gnu_debuglink_crc)
970 m_gnu_debuglink_crc =
971 calc_gnu_debuglink_crc32(m_data.GetDataStart(), m_data.GetByteSize());
972 if (m_gnu_debuglink_crc) {
973 // Use 4 bytes of crc from the .gnu_debuglink section.
974 uint32_t uuidt[4] = {m_gnu_debuglink_crc, 0, 0, 0};
975 m_uuid.SetBytes(uuidt, sizeof(uuidt));
976 }
977 }
978
979 if (m_uuid.IsValid()) {
980 *uuid = m_uuid;
981 return true;
982 }
983
984 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000985}
986
Kate Stoneb9c1b512016-09-06 20:57:50 +0000987lldb_private::FileSpecList ObjectFileELF::GetDebugSymbolFilePaths() {
988 FileSpecList file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 if (!m_gnu_debuglink_file.empty()) {
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000991 FileSpec file_spec(m_gnu_debuglink_file, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000992 file_spec_list.Append(file_spec);
993 }
994 return file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000995}
996
Kate Stoneb9c1b512016-09-06 20:57:50 +0000997uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
998 size_t num_modules = ParseDependentModules();
999 uint32_t num_specs = 0;
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001000
Kate Stoneb9c1b512016-09-06 20:57:50 +00001001 for (unsigned i = 0; i < num_modules; ++i) {
1002 if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
1003 num_specs++;
1004 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001005
Kate Stoneb9c1b512016-09-06 20:57:50 +00001006 return num_specs;
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001007}
1008
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009Address ObjectFileELF::GetImageInfoAddress(Target *target) {
1010 if (!ParseDynamicSymbols())
Stephen Wilson2ab0a582011-01-15 00:08:44 +00001011 return Address();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001012
1013 SectionList *section_list = GetSectionList();
1014 if (!section_list)
1015 return Address();
1016
1017 // Find the SHT_DYNAMIC (.dynamic) section.
1018 SectionSP dynsym_section_sp(
1019 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
1020 if (!dynsym_section_sp)
1021 return Address();
1022 assert(dynsym_section_sp->GetObjectFile() == this);
1023
1024 user_id_t dynsym_id = dynsym_section_sp->GetID();
1025 const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
1026 if (!dynsym_hdr)
1027 return Address();
1028
1029 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
1030 ELFDynamic &symbol = m_dynamic_symbols[i];
1031
1032 if (symbol.d_tag == DT_DEBUG) {
1033 // Compute the offset as the number of previous entries plus the
1034 // size of d_tag.
1035 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
1036 return Address(dynsym_section_sp, offset);
1037 }
1038 // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
1039 // exists in non-PIE.
1040 else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
1041 symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
1042 target) {
1043 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
1044 addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
1045 if (dyn_base == LLDB_INVALID_ADDRESS)
1046 return Address();
1047
1048 Error error;
1049 if (symbol.d_tag == DT_MIPS_RLD_MAP) {
1050 // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
1051 Address addr;
1052 if (target->ReadPointerFromMemory(dyn_base + offset, false, error,
1053 addr))
1054 return addr;
1055 }
1056 if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
1057 // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
1058 // relative to the address of the tag.
1059 uint64_t rel_offset;
1060 rel_offset = target->ReadUnsignedIntegerFromMemory(
1061 dyn_base + offset, false, GetAddressByteSize(), UINT64_MAX, error);
1062 if (error.Success() && rel_offset != UINT64_MAX) {
1063 Address addr;
1064 addr_t debug_ptr_address =
1065 dyn_base + (offset - GetAddressByteSize()) + rel_offset;
1066 addr.SetOffset(debug_ptr_address);
1067 return addr;
1068 }
1069 }
1070 }
1071 }
1072
1073 return Address();
Stephen Wilson2ab0a582011-01-15 00:08:44 +00001074}
1075
Kate Stoneb9c1b512016-09-06 20:57:50 +00001076lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
1077 if (m_entry_point_address.IsValid())
Stephen Wilsond126c8c2011-03-08 04:12:15 +00001078 return m_entry_point_address;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001079
1080 if (!ParseHeader() || !IsExecutable())
1081 return m_entry_point_address;
1082
1083 SectionList *section_list = GetSectionList();
1084 addr_t offset = m_header.e_entry;
1085
1086 if (!section_list)
1087 m_entry_point_address.SetOffset(offset);
1088 else
1089 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
1090 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00001091}
1092
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001093//----------------------------------------------------------------------
1094// ParseDependentModules
1095//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001096size_t ObjectFileELF::ParseDependentModules() {
1097 if (m_filespec_ap.get())
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001098 return m_filespec_ap->GetSize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001099
1100 m_filespec_ap.reset(new FileSpecList());
1101
1102 if (!ParseSectionHeaders())
1103 return 0;
1104
1105 SectionList *section_list = GetSectionList();
1106 if (!section_list)
1107 return 0;
1108
1109 // Find the SHT_DYNAMIC section.
1110 Section *dynsym =
1111 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
1112 .get();
1113 if (!dynsym)
1114 return 0;
1115 assert(dynsym->GetObjectFile() == this);
1116
1117 const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
1118 if (!header)
1119 return 0;
1120 // sh_link: section header index of string table used by entries in the
1121 // section.
1122 Section *dynstr = section_list->FindSectionByID(header->sh_link + 1).get();
1123 if (!dynstr)
1124 return 0;
1125
1126 DataExtractor dynsym_data;
1127 DataExtractor dynstr_data;
1128 if (ReadSectionData(dynsym, dynsym_data) &&
1129 ReadSectionData(dynstr, dynstr_data)) {
1130 ELFDynamic symbol;
1131 const lldb::offset_t section_size = dynsym_data.GetByteSize();
1132 lldb::offset_t offset = 0;
1133
1134 // The only type of entries we are concerned with are tagged DT_NEEDED,
1135 // yielding the name of a required library.
1136 while (offset < section_size) {
1137 if (!symbol.Parse(dynsym_data, &offset))
1138 break;
1139
1140 if (symbol.d_tag != DT_NEEDED)
1141 continue;
1142
1143 uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
1144 const char *lib_name = dynstr_data.PeekCStr(str_index);
1145 m_filespec_ap->Append(FileSpec(lib_name, true));
1146 }
1147 }
1148
1149 return m_filespec_ap->GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001150}
1151
1152//----------------------------------------------------------------------
Todd Fiala4339f3a2014-03-25 19:29:09 +00001153// GetProgramHeaderInfo
1154//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001155size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
1156 const SetDataFunction &set_data,
1157 const ELFHeader &header) {
1158 // We have already parsed the program headers
1159 if (!program_headers.empty())
Todd Fiala4339f3a2014-03-25 19:29:09 +00001160 return program_headers.size();
1161
Kate Stoneb9c1b512016-09-06 20:57:50 +00001162 // If there are no program headers to read we are done.
1163 if (header.e_phnum == 0)
1164 return 0;
1165
1166 program_headers.resize(header.e_phnum);
1167 if (program_headers.size() != header.e_phnum)
1168 return 0;
1169
1170 const size_t ph_size = header.e_phnum * header.e_phentsize;
1171 const elf_off ph_offset = header.e_phoff;
1172 DataExtractor data;
1173 if (set_data(data, ph_offset, ph_size) != ph_size)
1174 return 0;
1175
1176 uint32_t idx;
1177 lldb::offset_t offset;
1178 for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
1179 if (program_headers[idx].Parse(data, &offset) == false)
1180 break;
1181 }
1182
1183 if (idx < program_headers.size())
1184 program_headers.resize(idx);
1185
1186 return program_headers.size();
Todd Fiala4339f3a2014-03-25 19:29:09 +00001187}
1188
1189//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001190// ParseProgramHeaders
1191//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192size_t ObjectFileELF::ParseProgramHeaders() {
1193 using namespace std::placeholders;
1194 return GetProgramHeaderInfo(
1195 m_program_headers,
1196 std::bind(&ObjectFileELF::SetDataWithReadMemoryFallback, this, _1, _2,
1197 _3),
1198 m_header);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001199}
1200
Todd Fialab91de782014-06-27 16:52:49 +00001201lldb_private::Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001202ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
1203 lldb_private::ArchSpec &arch_spec,
1204 lldb_private::UUID &uuid) {
1205 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1206 Error error;
Todd Fialab91de782014-06-27 16:52:49 +00001207
Kate Stoneb9c1b512016-09-06 20:57:50 +00001208 lldb::offset_t offset = 0;
Michael Sartainc836ae72013-05-23 20:57:03 +00001209
Kate Stoneb9c1b512016-09-06 20:57:50 +00001210 while (true) {
1211 // Parse the note header. If this fails, bail out.
1212 const lldb::offset_t note_offset = offset;
1213 ELFNote note = ELFNote();
1214 if (!note.Parse(data, &offset)) {
1215 // We're done.
1216 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001217 }
Todd Fialab91de782014-06-27 16:52:49 +00001218
Kate Stoneb9c1b512016-09-06 20:57:50 +00001219 if (log)
1220 log->Printf("ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1221 __FUNCTION__, note.n_name.c_str(), note.n_type);
1222
1223 // Process FreeBSD ELF notes.
1224 if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1225 (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
1226 (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
1227 // Pull out the min version info.
1228 uint32_t version_info;
1229 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1230 error.SetErrorString("failed to read FreeBSD ABI note payload");
1231 return error;
1232 }
1233
1234 // Convert the version info into a major/minor number.
1235 const uint32_t version_major = version_info / 100000;
1236 const uint32_t version_minor = (version_info / 1000) % 100;
1237
1238 char os_name[32];
1239 snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1240 version_major, version_minor);
1241
1242 // Set the elf OS version to FreeBSD. Also clear the vendor.
1243 arch_spec.GetTriple().setOSName(os_name);
1244 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1245
1246 if (log)
1247 log->Printf("ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1248 ".%" PRIu32,
1249 __FUNCTION__, version_major, version_minor,
1250 static_cast<uint32_t>(version_info % 1000));
1251 }
1252 // Process GNU ELF notes.
1253 else if (note.n_name == LLDB_NT_OWNER_GNU) {
1254 switch (note.n_type) {
1255 case LLDB_NT_GNU_ABI_TAG:
1256 if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1257 // Pull out the min OS version supporting the ABI.
1258 uint32_t version_info[4];
1259 if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1260 nullptr) {
1261 error.SetErrorString("failed to read GNU ABI note payload");
1262 return error;
1263 }
1264
1265 // Set the OS per the OS field.
1266 switch (version_info[0]) {
1267 case LLDB_NT_GNU_ABI_OS_LINUX:
1268 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1269 arch_spec.GetTriple().setVendor(
1270 llvm::Triple::VendorType::UnknownVendor);
1271 if (log)
1272 log->Printf(
1273 "ObjectFileELF::%s detected Linux, min version %" PRIu32
1274 ".%" PRIu32 ".%" PRIu32,
1275 __FUNCTION__, version_info[1], version_info[2],
1276 version_info[3]);
1277 // FIXME we have the minimal version number, we could be propagating
1278 // that. version_info[1] = OS Major, version_info[2] = OS Minor,
1279 // version_info[3] = Revision.
1280 break;
1281 case LLDB_NT_GNU_ABI_OS_HURD:
1282 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1283 arch_spec.GetTriple().setVendor(
1284 llvm::Triple::VendorType::UnknownVendor);
1285 if (log)
1286 log->Printf("ObjectFileELF::%s detected Hurd (unsupported), min "
1287 "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1288 __FUNCTION__, version_info[1], version_info[2],
1289 version_info[3]);
1290 break;
1291 case LLDB_NT_GNU_ABI_OS_SOLARIS:
1292 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1293 arch_spec.GetTriple().setVendor(
1294 llvm::Triple::VendorType::UnknownVendor);
1295 if (log)
1296 log->Printf(
1297 "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1298 ".%" PRIu32 ".%" PRIu32,
1299 __FUNCTION__, version_info[1], version_info[2],
1300 version_info[3]);
1301 break;
1302 default:
1303 if (log)
1304 log->Printf(
1305 "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1306 ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1307 __FUNCTION__, version_info[0], version_info[1],
1308 version_info[2], version_info[3]);
1309 break;
1310 }
1311 }
1312 break;
1313
1314 case LLDB_NT_GNU_BUILD_ID_TAG:
1315 // Only bother processing this if we don't already have the uuid set.
1316 if (!uuid.IsValid()) {
1317 // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
1318 // build-id of a different
1319 // length. Accept it as long as it's at least 4 bytes as it will be
1320 // better than our own crc32.
1321 if (note.n_descsz >= 4 && note.n_descsz <= 20) {
1322 uint8_t uuidbuf[20];
1323 if (data.GetU8(&offset, &uuidbuf, note.n_descsz) == nullptr) {
1324 error.SetErrorString("failed to read GNU_BUILD_ID note payload");
1325 return error;
1326 }
1327
1328 // Save the build id as the UUID for the module.
1329 uuid.SetBytes(uuidbuf, note.n_descsz);
1330 }
1331 }
1332 break;
1333 }
1334 }
1335 // Process NetBSD ELF notes.
1336 else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
1337 (note.n_type == LLDB_NT_NETBSD_ABI_TAG) &&
1338 (note.n_descsz == LLDB_NT_NETBSD_ABI_SIZE)) {
1339 // Pull out the min version info.
1340 uint32_t version_info;
1341 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1342 error.SetErrorString("failed to read NetBSD ABI note payload");
1343 return error;
1344 }
1345
1346 // Set the elf OS version to NetBSD. Also clear the vendor.
1347 arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
1348 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1349
1350 if (log)
1351 log->Printf(
1352 "ObjectFileELF::%s detected NetBSD, min version constant %" PRIu32,
1353 __FUNCTION__, version_info);
1354 }
1355 // Process CSR kalimba notes
1356 else if ((note.n_type == LLDB_NT_GNU_ABI_TAG) &&
1357 (note.n_name == LLDB_NT_OWNER_CSR)) {
1358 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1359 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::CSR);
1360
1361 // TODO At some point the description string could be processed.
1362 // It could provide a steer towards the kalimba variant which
1363 // this ELF targets.
1364 if (note.n_descsz) {
1365 const char *cstr =
1366 data.GetCStr(&offset, llvm::alignTo(note.n_descsz, 4));
1367 (void)cstr;
1368 }
1369 } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1370 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1371 arch_spec.GetTriple().setEnvironment(
1372 llvm::Triple::EnvironmentType::Android);
1373 } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1374 // This is sometimes found in core files and usually contains extended
1375 // register info
1376 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1377 } else if (note.n_name == LLDB_NT_OWNER_CORE) {
1378 // Parse the NT_FILE to look for stuff in paths to shared libraries
1379 // As the contents look like this in a 64 bit ELF core file:
1380 // count = 0x000000000000000a (10)
1381 // page_size = 0x0000000000001000 (4096)
1382 // Index start end file_ofs path
1383 // ===== ------------------ ------------------ ------------------
1384 // -------------------------------------
1385 // [ 0] 0x0000000000400000 0x0000000000401000 0x0000000000000000
1386 // /tmp/a.out
1387 // [ 1] 0x0000000000600000 0x0000000000601000 0x0000000000000000
1388 // /tmp/a.out
1389 // [ 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001
1390 // /tmp/a.out
1391 // [ 3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000
1392 // /lib/x86_64-linux-gnu/libc-2.19.so
1393 // [ 4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb
1394 // /lib/x86_64-linux-gnu/libc-2.19.so
1395 // [ 5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba
1396 // /lib/x86_64-linux-gnu/libc-2.19.so
1397 // [ 6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be
1398 // /lib/x86_64-linux-gnu/libc-2.19.so
1399 // [ 7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000
1400 // /lib/x86_64-linux-gnu/ld-2.19.so
1401 // [ 8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022
1402 // /lib/x86_64-linux-gnu/ld-2.19.so
1403 // [ 9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023
1404 // /lib/x86_64-linux-gnu/ld-2.19.so
1405 // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
1406 // uint32_t
1407 // For reference: see readelf source code (in binutils).
1408 if (note.n_type == NT_FILE) {
1409 uint64_t count = data.GetAddress(&offset);
1410 const char *cstr;
1411 data.GetAddress(&offset); // Skip page size
1412 offset += count * 3 *
1413 data.GetAddressByteSize(); // Skip all start/end/file_ofs
1414 for (size_t i = 0; i < count; ++i) {
1415 cstr = data.GetCStr(&offset);
1416 if (cstr == nullptr) {
1417 error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
1418 "at an offset after the end "
1419 "(GetCStr returned nullptr)",
1420 __FUNCTION__);
1421 return error;
1422 }
1423 llvm::StringRef path(cstr);
Richard Chamberlaina0c82e12016-10-13 12:11:00 +00001424 if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001425 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1426 break;
1427 }
1428 }
1429 }
1430 }
1431
1432 // Calculate the offset of the next note just in case "offset" has been used
1433 // to poke at the contents of the note data
1434 offset = note_offset + note.GetByteSize();
1435 }
1436
1437 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001438}
Michael Sartaina7499c92013-07-01 19:45:50 +00001439
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
1441 ArchSpec &arch_spec) {
1442 lldb::offset_t Offset = 0;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001443
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 uint8_t FormatVersion = data.GetU8(&Offset);
1445 if (FormatVersion != llvm::ARMBuildAttrs::Format_Version)
1446 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001447
Kate Stoneb9c1b512016-09-06 20:57:50 +00001448 Offset = Offset + sizeof(uint32_t); // Section Length
1449 llvm::StringRef VendorName = data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001450
Kate Stoneb9c1b512016-09-06 20:57:50 +00001451 if (VendorName != "aeabi")
1452 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001453
Kate Stoneb9c1b512016-09-06 20:57:50 +00001454 if (arch_spec.GetTriple().getEnvironment() ==
1455 llvm::Triple::UnknownEnvironment)
1456 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001457
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 while (Offset < length) {
1459 uint8_t Tag = data.GetU8(&Offset);
1460 uint32_t Size = data.GetU32(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001461
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462 if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1463 continue;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001464
Kate Stoneb9c1b512016-09-06 20:57:50 +00001465 while (Offset < length) {
1466 uint64_t Tag = data.GetULEB128(&Offset);
1467 switch (Tag) {
1468 default:
1469 if (Tag < 32)
1470 data.GetULEB128(&Offset);
1471 else if (Tag % 2 == 0)
1472 data.GetULEB128(&Offset);
1473 else
1474 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001475
Kate Stoneb9c1b512016-09-06 20:57:50 +00001476 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001477
Kate Stoneb9c1b512016-09-06 20:57:50 +00001478 case llvm::ARMBuildAttrs::CPU_raw_name:
1479 case llvm::ARMBuildAttrs::CPU_name:
1480 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001481
Kate Stoneb9c1b512016-09-06 20:57:50 +00001482 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 case llvm::ARMBuildAttrs::ABI_VFP_args: {
1485 uint64_t VFPArgs = data.GetULEB128(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001486
Kate Stoneb9c1b512016-09-06 20:57:50 +00001487 if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1488 if (arch_spec.GetTriple().getEnvironment() ==
1489 llvm::Triple::UnknownEnvironment ||
1490 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1491 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001492
Kate Stoneb9c1b512016-09-06 20:57:50 +00001493 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1494 } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1495 if (arch_spec.GetTriple().getEnvironment() ==
1496 llvm::Triple::UnknownEnvironment ||
1497 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1498 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001499
Kate Stoneb9c1b512016-09-06 20:57:50 +00001500 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001501 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001502
1503 break;
1504 }
1505 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001506 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001507 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001508}
Todd Fialab91de782014-06-27 16:52:49 +00001509
Michael Sartaina7499c92013-07-01 19:45:50 +00001510//----------------------------------------------------------------------
1511// GetSectionHeaderInfo
1512//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001513size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
1514 const SetDataFunction &set_data,
1515 const elf::ELFHeader &header,
1516 lldb_private::UUID &uuid,
1517 std::string &gnu_debuglink_file,
1518 uint32_t &gnu_debuglink_crc,
1519 ArchSpec &arch_spec) {
1520 // Don't reparse the section headers if we already did that.
1521 if (!section_headers.empty())
1522 return section_headers.size();
Todd Fiala6477ea82014-07-11 15:13:33 +00001523
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524 // Only initialize the arch_spec to okay defaults if they're not already set.
1525 // We'll refine this with note data as we parse the notes.
1526 if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1527 llvm::Triple::OSType ostype;
1528 llvm::Triple::OSType spec_ostype;
1529 const uint32_t sub_type = subTypeFromElfHeader(header);
1530 arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1531 header.e_ident[EI_OSABI]);
Alexander Shaposhnikova08ba422016-12-05 18:42:21 +00001532
1533 // Validate if it is ok to remove GetOsFromOSABI.
1534 // Note, that now the OS is determined based on EI_OSABI flag and
1535 // the info extracted from ELF notes (see RefineModuleDetailsFromNote).
1536 // However in some cases that still might be not enough: for example
1537 // a shared library might not have any notes at all
1538 // and have EI_OSABI flag set to System V,
1539 // as result the OS will be set to UnknownOS.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001540 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1541 spec_ostype = arch_spec.GetTriple().getOS();
1542 assert(spec_ostype == ostype);
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001543 UNUSED_IF_ASSERT_DISABLED(spec_ostype);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544 }
1545
1546 if (arch_spec.GetMachine() == llvm::Triple::mips ||
1547 arch_spec.GetMachine() == llvm::Triple::mipsel ||
1548 arch_spec.GetMachine() == llvm::Triple::mips64 ||
1549 arch_spec.GetMachine() == llvm::Triple::mips64el) {
1550 switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1551 case llvm::ELF::EF_MIPS_MICROMIPS:
1552 arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
1553 break;
1554 case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1555 arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
1556 break;
1557 case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1558 arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
1559 break;
1560 default:
1561 break;
Todd Fialab91de782014-06-27 16:52:49 +00001562 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001563 }
Todd Fialab91de782014-06-27 16:52:49 +00001564
Kate Stoneb9c1b512016-09-06 20:57:50 +00001565 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1566 arch_spec.GetMachine() == llvm::Triple::thumb) {
1567 if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1568 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1569 else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1570 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1571 }
Jaydeep Patil501a7812015-07-16 03:51:55 +00001572
Kate Stoneb9c1b512016-09-06 20:57:50 +00001573 // If there are no section headers we are done.
1574 if (header.e_shnum == 0)
Michael Sartaina7499c92013-07-01 19:45:50 +00001575 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001576
1577 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1578
1579 section_headers.resize(header.e_shnum);
1580 if (section_headers.size() != header.e_shnum)
1581 return 0;
1582
1583 const size_t sh_size = header.e_shnum * header.e_shentsize;
1584 const elf_off sh_offset = header.e_shoff;
1585 DataExtractor sh_data;
1586 if (set_data(sh_data, sh_offset, sh_size) != sh_size)
1587 return 0;
1588
1589 uint32_t idx;
1590 lldb::offset_t offset;
1591 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
1592 if (section_headers[idx].Parse(sh_data, &offset) == false)
1593 break;
1594 }
1595 if (idx < section_headers.size())
1596 section_headers.resize(idx);
1597
1598 const unsigned strtab_idx = header.e_shstrndx;
1599 if (strtab_idx && strtab_idx < section_headers.size()) {
1600 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1601 const size_t byte_size = sheader.sh_size;
1602 const Elf64_Off offset = sheader.sh_offset;
1603 lldb_private::DataExtractor shstr_data;
1604
1605 if (set_data(shstr_data, offset, byte_size) == byte_size) {
1606 for (SectionHeaderCollIter I = section_headers.begin();
1607 I != section_headers.end(); ++I) {
1608 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1609 const ELFSectionHeaderInfo &sheader = *I;
1610 const uint64_t section_size =
1611 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1612 ConstString name(shstr_data.PeekCStr(I->sh_name));
1613
1614 I->section_name = name;
1615
1616 if (arch_spec.IsMIPS()) {
1617 uint32_t arch_flags = arch_spec.GetFlags();
1618 DataExtractor data;
1619 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1620
1621 if (section_size && (set_data(data, sheader.sh_offset,
1622 section_size) == section_size)) {
1623 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1624 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1625 arch_flags |= data.GetU32(&offset);
1626
1627 // The floating point ABI is at offset 7
1628 offset = 7;
1629 switch (data.GetU8(&offset)) {
1630 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1631 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
1632 break;
1633 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1634 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
1635 break;
1636 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1637 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
1638 break;
1639 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1640 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
1641 break;
1642 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1643 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
1644 break;
1645 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1646 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
1647 break;
1648 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1649 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
1650 break;
1651 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1652 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
1653 break;
1654 }
1655 }
1656 }
1657 // Settings appropriate ArchSpec ABI Flags
1658 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1659 case llvm::ELF::EF_MIPS_ABI_O32:
1660 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
1661 break;
1662 case EF_MIPS_ABI_O64:
1663 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
1664 break;
1665 case EF_MIPS_ABI_EABI32:
1666 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
1667 break;
1668 case EF_MIPS_ABI_EABI64:
1669 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
1670 break;
1671 default:
1672 // ABI Mask doesn't cover N32 and N64 ABI.
1673 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1674 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
1675 else if (header.e_flags && llvm::ELF::EF_MIPS_ABI2)
1676 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
1677 break;
1678 }
1679 arch_spec.SetFlags(arch_flags);
1680 }
1681
1682 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1683 arch_spec.GetMachine() == llvm::Triple::thumb) {
1684 DataExtractor data;
1685
1686 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
1687 set_data(data, sheader.sh_offset, section_size) == section_size)
1688 ParseARMAttributes(data, section_size, arch_spec);
1689 }
1690
1691 if (name == g_sect_name_gnu_debuglink) {
1692 DataExtractor data;
1693 if (section_size && (set_data(data, sheader.sh_offset,
1694 section_size) == section_size)) {
1695 lldb::offset_t gnu_debuglink_offset = 0;
1696 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1697 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1698 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1699 }
1700 }
1701
1702 // Process ELF note section entries.
1703 bool is_note_header = (sheader.sh_type == SHT_NOTE);
1704
1705 // The section header ".note.android.ident" is stored as a
1706 // PROGBITS type header but it is actually a note header.
1707 static ConstString g_sect_name_android_ident(".note.android.ident");
1708 if (!is_note_header && name == g_sect_name_android_ident)
1709 is_note_header = true;
1710
1711 if (is_note_header) {
1712 // Allow notes to refine module info.
1713 DataExtractor data;
1714 if (section_size && (set_data(data, sheader.sh_offset,
1715 section_size) == section_size)) {
1716 Error error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
1717 if (error.Fail()) {
1718 if (log)
1719 log->Printf("ObjectFileELF::%s ELF note processing failed: %s",
1720 __FUNCTION__, error.AsCString());
1721 }
1722 }
1723 }
1724 }
1725
1726 // Make any unknown triple components to be unspecified unknowns.
1727 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1728 arch_spec.GetTriple().setVendorName(llvm::StringRef());
1729 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1730 arch_spec.GetTriple().setOSName(llvm::StringRef());
1731
1732 return section_headers.size();
1733 }
1734 }
1735
1736 section_headers.clear();
1737 return 0;
Michael Sartaina7499c92013-07-01 19:45:50 +00001738}
1739
Kate Stoneb9c1b512016-09-06 20:57:50 +00001740size_t ObjectFileELF::GetProgramHeaderCount() { return ParseProgramHeaders(); }
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001741
1742const elf::ELFProgramHeader *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001743ObjectFileELF::GetProgramHeaderByIndex(lldb::user_id_t id) {
1744 if (!id || !ParseProgramHeaders())
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001745 return NULL;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001746
1747 if (--id < m_program_headers.size())
1748 return &m_program_headers[id];
1749
1750 return NULL;
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001751}
1752
Kate Stoneb9c1b512016-09-06 20:57:50 +00001753DataExtractor ObjectFileELF::GetSegmentDataByIndex(lldb::user_id_t id) {
1754 const elf::ELFProgramHeader *segment_header = GetProgramHeaderByIndex(id);
1755 if (segment_header == NULL)
1756 return DataExtractor();
1757 return DataExtractor(m_data, segment_header->p_offset,
1758 segment_header->p_filesz);
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001759}
1760
Pavel Labathc6ae7ea2015-03-04 10:25:22 +00001761std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +00001762ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1763 size_t pos = symbol_name.find('@');
1764 return symbol_name.substr(0, pos).str();
Pavel Labathc6ae7ea2015-03-04 10:25:22 +00001765}
1766
Michael Sartaina7499c92013-07-01 19:45:50 +00001767//----------------------------------------------------------------------
1768// ParseSectionHeaders
1769//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001770size_t ObjectFileELF::ParseSectionHeaders() {
1771 using namespace std::placeholders;
Ravitheja Addepally15f89c42016-01-19 12:55:21 +00001772
Kate Stoneb9c1b512016-09-06 20:57:50 +00001773 return GetSectionHeaderInfo(
1774 m_section_headers,
1775 std::bind(&ObjectFileELF::SetDataWithReadMemoryFallback, this, _1, _2,
1776 _3),
1777 m_header, m_uuid, m_gnu_debuglink_file, m_gnu_debuglink_crc, m_arch_spec);
1778}
1779
1780lldb::offset_t ObjectFileELF::SetData(const lldb_private::DataExtractor &src,
1781 lldb_private::DataExtractor &dst,
1782 lldb::offset_t offset,
1783 lldb::offset_t length) {
1784 return dst.SetData(src, offset, length);
Ravitheja Addepally15f89c42016-01-19 12:55:21 +00001785}
1786
1787lldb::offset_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001788ObjectFileELF::SetDataWithReadMemoryFallback(lldb_private::DataExtractor &dst,
1789 lldb::offset_t offset,
1790 lldb::offset_t length) {
1791 if (offset + length <= m_data.GetByteSize())
Ravitheja Addepally15f89c42016-01-19 12:55:21 +00001792 return dst.SetData(m_data, offset, length);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001793
1794 const auto process_sp = m_process_wp.lock();
1795 if (process_sp != nullptr) {
1796 addr_t file_size = offset + length;
1797
1798 DataBufferSP data_sp = ReadMemory(process_sp, m_memory_addr, file_size);
1799 if (!data_sp)
1800 return false;
1801 m_data.SetData(data_sp, 0, file_size);
1802 }
1803
1804 return dst.SetData(m_data, offset, length);
Michael Sartaina7499c92013-07-01 19:45:50 +00001805}
1806
Michael Sartaina7499c92013-07-01 19:45:50 +00001807const ObjectFileELF::ELFSectionHeaderInfo *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001808ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
1809 if (!id || !ParseSectionHeaders())
Michael Sartaina7499c92013-07-01 19:45:50 +00001810 return NULL;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001811
1812 if (--id < m_section_headers.size())
1813 return &m_section_headers[id];
1814
1815 return NULL;
Michael Sartaina7499c92013-07-01 19:45:50 +00001816}
1817
Kate Stoneb9c1b512016-09-06 20:57:50 +00001818lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
1819 if (!name || !name[0] || !ParseSectionHeaders())
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001820 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001821 for (size_t i = 1; i < m_section_headers.size(); ++i)
1822 if (m_section_headers[i].section_name == ConstString(name))
1823 return i;
1824 return 0;
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001825}
1826
Kate Stoneb9c1b512016-09-06 20:57:50 +00001827void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
1828 if (!m_sections_ap.get() && ParseSectionHeaders()) {
1829 m_sections_ap.reset(new SectionList());
Andrew MacPherson17220c12014-03-05 10:12:43 +00001830
1831 for (SectionHeaderCollIter I = m_section_headers.begin();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001832 I != m_section_headers.end(); ++I) {
1833 const ELFSectionHeaderInfo &header = *I;
1834
1835 ConstString &name = I->section_name;
1836 const uint64_t file_size =
1837 header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
1838 const uint64_t vm_size = header.sh_flags & SHF_ALLOC ? header.sh_size : 0;
1839
1840 static ConstString g_sect_name_text(".text");
1841 static ConstString g_sect_name_data(".data");
1842 static ConstString g_sect_name_bss(".bss");
1843 static ConstString g_sect_name_tdata(".tdata");
1844 static ConstString g_sect_name_tbss(".tbss");
1845 static ConstString g_sect_name_dwarf_debug_abbrev(".debug_abbrev");
1846 static ConstString g_sect_name_dwarf_debug_addr(".debug_addr");
1847 static ConstString g_sect_name_dwarf_debug_aranges(".debug_aranges");
1848 static ConstString g_sect_name_dwarf_debug_frame(".debug_frame");
1849 static ConstString g_sect_name_dwarf_debug_info(".debug_info");
1850 static ConstString g_sect_name_dwarf_debug_line(".debug_line");
1851 static ConstString g_sect_name_dwarf_debug_loc(".debug_loc");
1852 static ConstString g_sect_name_dwarf_debug_macinfo(".debug_macinfo");
1853 static ConstString g_sect_name_dwarf_debug_macro(".debug_macro");
1854 static ConstString g_sect_name_dwarf_debug_pubnames(".debug_pubnames");
1855 static ConstString g_sect_name_dwarf_debug_pubtypes(".debug_pubtypes");
1856 static ConstString g_sect_name_dwarf_debug_ranges(".debug_ranges");
1857 static ConstString g_sect_name_dwarf_debug_str(".debug_str");
1858 static ConstString g_sect_name_dwarf_debug_str_offsets(
1859 ".debug_str_offsets");
1860 static ConstString g_sect_name_dwarf_debug_abbrev_dwo(
1861 ".debug_abbrev.dwo");
1862 static ConstString g_sect_name_dwarf_debug_info_dwo(".debug_info.dwo");
1863 static ConstString g_sect_name_dwarf_debug_line_dwo(".debug_line.dwo");
1864 static ConstString g_sect_name_dwarf_debug_macro_dwo(".debug_macro.dwo");
1865 static ConstString g_sect_name_dwarf_debug_loc_dwo(".debug_loc.dwo");
1866 static ConstString g_sect_name_dwarf_debug_str_dwo(".debug_str.dwo");
1867 static ConstString g_sect_name_dwarf_debug_str_offsets_dwo(
1868 ".debug_str_offsets.dwo");
1869 static ConstString g_sect_name_eh_frame(".eh_frame");
1870 static ConstString g_sect_name_arm_exidx(".ARM.exidx");
1871 static ConstString g_sect_name_arm_extab(".ARM.extab");
1872 static ConstString g_sect_name_go_symtab(".gosymtab");
1873
1874 SectionType sect_type = eSectionTypeOther;
1875
1876 bool is_thread_specific = false;
1877
1878 if (name == g_sect_name_text)
1879 sect_type = eSectionTypeCode;
1880 else if (name == g_sect_name_data)
1881 sect_type = eSectionTypeData;
1882 else if (name == g_sect_name_bss)
1883 sect_type = eSectionTypeZeroFill;
1884 else if (name == g_sect_name_tdata) {
1885 sect_type = eSectionTypeData;
1886 is_thread_specific = true;
1887 } else if (name == g_sect_name_tbss) {
1888 sect_type = eSectionTypeZeroFill;
1889 is_thread_specific = true;
1890 }
1891 // .debug_abbrev – Abbreviations used in the .debug_info section
1892 // .debug_aranges – Lookup table for mapping addresses to compilation
1893 // units
1894 // .debug_frame – Call frame information
1895 // .debug_info – The core DWARF information section
1896 // .debug_line – Line number information
1897 // .debug_loc – Location lists used in DW_AT_location attributes
1898 // .debug_macinfo – Macro information
1899 // .debug_pubnames – Lookup table for mapping object and function names to
1900 // compilation units
1901 // .debug_pubtypes – Lookup table for mapping type names to compilation
1902 // units
1903 // .debug_ranges – Address ranges used in DW_AT_ranges attributes
1904 // .debug_str – String table used in .debug_info
1905 // MISSING? .gnu_debugdata - "mini debuginfo / MiniDebugInfo" section,
1906 // http://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
1907 // MISSING? .debug-index -
1908 // http://src.chromium.org/viewvc/chrome/trunk/src/build/gdb-add-index?pathrev=144644
1909 // MISSING? .debug_types - Type descriptions from DWARF 4? See
1910 // http://gcc.gnu.org/wiki/DwarfSeparateTypeInfo
1911 else if (name == g_sect_name_dwarf_debug_abbrev)
1912 sect_type = eSectionTypeDWARFDebugAbbrev;
1913 else if (name == g_sect_name_dwarf_debug_addr)
1914 sect_type = eSectionTypeDWARFDebugAddr;
1915 else if (name == g_sect_name_dwarf_debug_aranges)
1916 sect_type = eSectionTypeDWARFDebugAranges;
1917 else if (name == g_sect_name_dwarf_debug_frame)
1918 sect_type = eSectionTypeDWARFDebugFrame;
1919 else if (name == g_sect_name_dwarf_debug_info)
1920 sect_type = eSectionTypeDWARFDebugInfo;
1921 else if (name == g_sect_name_dwarf_debug_line)
1922 sect_type = eSectionTypeDWARFDebugLine;
1923 else if (name == g_sect_name_dwarf_debug_loc)
1924 sect_type = eSectionTypeDWARFDebugLoc;
1925 else if (name == g_sect_name_dwarf_debug_macinfo)
1926 sect_type = eSectionTypeDWARFDebugMacInfo;
1927 else if (name == g_sect_name_dwarf_debug_macro)
1928 sect_type = eSectionTypeDWARFDebugMacro;
1929 else if (name == g_sect_name_dwarf_debug_pubnames)
1930 sect_type = eSectionTypeDWARFDebugPubNames;
1931 else if (name == g_sect_name_dwarf_debug_pubtypes)
1932 sect_type = eSectionTypeDWARFDebugPubTypes;
1933 else if (name == g_sect_name_dwarf_debug_ranges)
1934 sect_type = eSectionTypeDWARFDebugRanges;
1935 else if (name == g_sect_name_dwarf_debug_str)
1936 sect_type = eSectionTypeDWARFDebugStr;
1937 else if (name == g_sect_name_dwarf_debug_str_offsets)
1938 sect_type = eSectionTypeDWARFDebugStrOffsets;
1939 else if (name == g_sect_name_dwarf_debug_abbrev_dwo)
1940 sect_type = eSectionTypeDWARFDebugAbbrev;
1941 else if (name == g_sect_name_dwarf_debug_info_dwo)
1942 sect_type = eSectionTypeDWARFDebugInfo;
1943 else if (name == g_sect_name_dwarf_debug_line_dwo)
1944 sect_type = eSectionTypeDWARFDebugLine;
1945 else if (name == g_sect_name_dwarf_debug_macro_dwo)
1946 sect_type = eSectionTypeDWARFDebugMacro;
1947 else if (name == g_sect_name_dwarf_debug_loc_dwo)
1948 sect_type = eSectionTypeDWARFDebugLoc;
1949 else if (name == g_sect_name_dwarf_debug_str_dwo)
1950 sect_type = eSectionTypeDWARFDebugStr;
1951 else if (name == g_sect_name_dwarf_debug_str_offsets_dwo)
1952 sect_type = eSectionTypeDWARFDebugStrOffsets;
1953 else if (name == g_sect_name_eh_frame)
1954 sect_type = eSectionTypeEHFrame;
1955 else if (name == g_sect_name_arm_exidx)
1956 sect_type = eSectionTypeARMexidx;
1957 else if (name == g_sect_name_arm_extab)
1958 sect_type = eSectionTypeARMextab;
1959 else if (name == g_sect_name_go_symtab)
1960 sect_type = eSectionTypeGoSymtab;
1961
1962 const uint32_t permissions =
Ilia K4f730dc2016-09-12 05:25:33 +00001963 ((header.sh_flags & SHF_ALLOC) ? ePermissionsReadable : 0u) |
1964 ((header.sh_flags & SHF_WRITE) ? ePermissionsWritable : 0u) |
1965 ((header.sh_flags & SHF_EXECINSTR) ? ePermissionsExecutable : 0u);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001966 switch (header.sh_type) {
1967 case SHT_SYMTAB:
1968 assert(sect_type == eSectionTypeOther);
1969 sect_type = eSectionTypeELFSymbolTable;
1970 break;
1971 case SHT_DYNSYM:
1972 assert(sect_type == eSectionTypeOther);
1973 sect_type = eSectionTypeELFDynamicSymbols;
1974 break;
1975 case SHT_RELA:
1976 case SHT_REL:
1977 assert(sect_type == eSectionTypeOther);
1978 sect_type = eSectionTypeELFRelocationEntries;
1979 break;
1980 case SHT_DYNAMIC:
1981 assert(sect_type == eSectionTypeOther);
1982 sect_type = eSectionTypeELFDynamicLinkInfo;
1983 break;
1984 }
1985
1986 if (eSectionTypeOther == sect_type) {
1987 // the kalimba toolchain assumes that ELF section names are free-form.
1988 // It does
1989 // support linkscripts which (can) give rise to various arbitrarily
1990 // named
1991 // sections being "Code" or "Data".
1992 sect_type = kalimbaSectionType(m_header, header);
1993 }
1994
1995 const uint32_t target_bytes_size =
1996 (eSectionTypeData == sect_type || eSectionTypeZeroFill == sect_type)
1997 ? m_arch_spec.GetDataByteSize()
1998 : eSectionTypeCode == sect_type ? m_arch_spec.GetCodeByteSize()
1999 : 1;
2000
2001 elf::elf_xword log2align =
2002 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
2003 SectionSP section_sp(new Section(
2004 GetModule(), // Module to which this section belongs.
2005 this, // ObjectFile to which this section belongs and should read
2006 // section data from.
2007 SectionIndex(I), // Section ID.
2008 name, // Section name.
2009 sect_type, // Section type.
2010 header.sh_addr, // VM address.
2011 vm_size, // VM size in bytes of this section.
2012 header.sh_offset, // Offset of this section in the file.
2013 file_size, // Size of the section as found in the file.
2014 log2align, // Alignment of the section
2015 header.sh_flags, // Flags for this section.
2016 target_bytes_size)); // Number of host bytes per target byte
2017
2018 section_sp->SetPermissions(permissions);
2019 if (is_thread_specific)
2020 section_sp->SetIsThreadSpecific(is_thread_specific);
2021 m_sections_ap->AddSection(section_sp);
Andrew MacPherson17220c12014-03-05 10:12:43 +00002022 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002023 }
2024
2025 if (m_sections_ap.get()) {
2026 if (GetType() == eTypeDebugInfo) {
2027 static const SectionType g_sections[] = {
2028 eSectionTypeDWARFDebugAbbrev, eSectionTypeDWARFDebugAddr,
2029 eSectionTypeDWARFDebugAranges, eSectionTypeDWARFDebugFrame,
2030 eSectionTypeDWARFDebugInfo, eSectionTypeDWARFDebugLine,
2031 eSectionTypeDWARFDebugLoc, eSectionTypeDWARFDebugMacInfo,
2032 eSectionTypeDWARFDebugPubNames, eSectionTypeDWARFDebugPubTypes,
2033 eSectionTypeDWARFDebugRanges, eSectionTypeDWARFDebugStr,
2034 eSectionTypeDWARFDebugStrOffsets, eSectionTypeELFSymbolTable,
2035 };
2036 SectionList *elf_section_list = m_sections_ap.get();
2037 for (size_t idx = 0; idx < sizeof(g_sections) / sizeof(g_sections[0]);
2038 ++idx) {
2039 SectionType section_type = g_sections[idx];
2040 SectionSP section_sp(
2041 elf_section_list->FindSectionByType(section_type, true));
2042 if (section_sp) {
2043 SectionSP module_section_sp(
2044 unified_section_list.FindSectionByType(section_type, true));
2045 if (module_section_sp)
2046 unified_section_list.ReplaceSection(module_section_sp->GetID(),
2047 section_sp);
2048 else
2049 unified_section_list.AddSection(section_sp);
2050 }
2051 }
2052 } else {
2053 unified_section_list = *m_sections_ap;
2054 }
2055 }
Greg Clayton3046e662013-07-10 01:23:25 +00002056}
2057
Kate Stoneb9c1b512016-09-06 20:57:50 +00002058// Find the arm/aarch64 mapping symbol character in the given symbol name.
2059// Mapping symbols have the
2060// form of "$<char>[.<any>]*". Additionally we recognize cases when the mapping
2061// symbol prefixed by
2062// an arbitrary string because if a symbol prefix added to each symbol in the
2063// object file with
2064// objcopy then the mapping symbols are also prefixed.
2065static char FindArmAarch64MappingSymbol(const char *symbol_name) {
2066 if (!symbol_name)
2067 return '\0';
2068
2069 const char *dollar_pos = ::strchr(symbol_name, '$');
2070 if (!dollar_pos || dollar_pos[1] == '\0')
2071 return '\0';
2072
2073 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
2074 return dollar_pos[1];
2075 return '\0';
2076}
2077
2078#define STO_MIPS_ISA (3 << 6)
2079#define STO_MICROMIPS (2 << 6)
2080#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
2081
2082// private
2083unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
2084 SectionList *section_list,
2085 const size_t num_symbols,
2086 const DataExtractor &symtab_data,
2087 const DataExtractor &strtab_data) {
2088 ELFSymbol symbol;
2089 lldb::offset_t offset = 0;
2090
2091 static ConstString text_section_name(".text");
2092 static ConstString init_section_name(".init");
2093 static ConstString fini_section_name(".fini");
2094 static ConstString ctors_section_name(".ctors");
2095 static ConstString dtors_section_name(".dtors");
2096
2097 static ConstString data_section_name(".data");
2098 static ConstString rodata_section_name(".rodata");
2099 static ConstString rodata1_section_name(".rodata1");
2100 static ConstString data2_section_name(".data1");
2101 static ConstString bss_section_name(".bss");
2102 static ConstString opd_section_name(".opd"); // For ppc64
2103
2104 // On Android the oatdata and the oatexec symbols in the oat and odex files
2105 // covers the full
2106 // .text section what causes issues with displaying unusable symbol name to
2107 // the user and very
2108 // slow unwinding speed because the instruction emulation based unwind plans
2109 // try to emulate all
2110 // instructions in these symbols. Don't add these symbols to the symbol list
2111 // as they have no
2112 // use for the debugger and they are causing a lot of trouble.
2113 // Filtering can't be restricted to Android because this special object file
2114 // don't contain the
2115 // note section specifying the environment to Android but the custom extension
2116 // and file name
2117 // makes it highly unlikely that this will collide with anything else.
2118 ConstString file_extension = m_file.GetFileNameExtension();
2119 bool skip_oatdata_oatexec = file_extension == ConstString("oat") ||
2120 file_extension == ConstString("odex");
2121
2122 ArchSpec arch;
2123 GetArchitecture(arch);
2124 ModuleSP module_sp(GetModule());
2125 SectionList *module_section_list =
2126 module_sp ? module_sp->GetSectionList() : nullptr;
2127
2128 // Local cache to avoid doing a FindSectionByName for each symbol. The "const
2129 // char*" key must
2130 // came from a ConstString object so they can be compared by pointer
2131 std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
2132
2133 unsigned i;
2134 for (i = 0; i < num_symbols; ++i) {
2135 if (symbol.Parse(symtab_data, &offset) == false)
2136 break;
2137
2138 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2139 if (!symbol_name)
2140 symbol_name = "";
2141
2142 // No need to add non-section symbols that have no names
2143 if (symbol.getType() != STT_SECTION &&
2144 (symbol_name == nullptr || symbol_name[0] == '\0'))
2145 continue;
2146
2147 // Skipping oatdata and oatexec sections if it is requested. See details
2148 // above the
2149 // definition of skip_oatdata_oatexec for the reasons.
2150 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
2151 ::strcmp(symbol_name, "oatexec") == 0))
2152 continue;
2153
2154 SectionSP symbol_section_sp;
2155 SymbolType symbol_type = eSymbolTypeInvalid;
2156 Elf64_Half section_idx = symbol.st_shndx;
2157
2158 switch (section_idx) {
2159 case SHN_ABS:
2160 symbol_type = eSymbolTypeAbsolute;
2161 break;
2162 case SHN_UNDEF:
2163 symbol_type = eSymbolTypeUndefined;
2164 break;
2165 default:
2166 symbol_section_sp = section_list->GetSectionAtIndex(section_idx);
2167 break;
2168 }
2169
2170 // If a symbol is undefined do not process it further even if it has a STT
2171 // type
2172 if (symbol_type != eSymbolTypeUndefined) {
2173 switch (symbol.getType()) {
2174 default:
2175 case STT_NOTYPE:
2176 // The symbol's type is not specified.
2177 break;
2178
2179 case STT_OBJECT:
2180 // The symbol is associated with a data object, such as a variable,
2181 // an array, etc.
2182 symbol_type = eSymbolTypeData;
2183 break;
2184
2185 case STT_FUNC:
2186 // The symbol is associated with a function or other executable code.
2187 symbol_type = eSymbolTypeCode;
2188 break;
2189
2190 case STT_SECTION:
2191 // The symbol is associated with a section. Symbol table entries of
2192 // this type exist primarily for relocation and normally have
2193 // STB_LOCAL binding.
2194 break;
2195
2196 case STT_FILE:
2197 // Conventionally, the symbol's name gives the name of the source
2198 // file associated with the object file. A file symbol has STB_LOCAL
2199 // binding, its section index is SHN_ABS, and it precedes the other
2200 // STB_LOCAL symbols for the file, if it is present.
2201 symbol_type = eSymbolTypeSourceFile;
2202 break;
2203
2204 case STT_GNU_IFUNC:
2205 // The symbol is associated with an indirect function. The actual
2206 // function will be resolved if it is referenced.
2207 symbol_type = eSymbolTypeResolver;
2208 break;
2209 }
2210 }
2211
2212 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2213 if (symbol_section_sp) {
2214 const ConstString &sect_name = symbol_section_sp->GetName();
2215 if (sect_name == text_section_name || sect_name == init_section_name ||
2216 sect_name == fini_section_name || sect_name == ctors_section_name ||
2217 sect_name == dtors_section_name) {
2218 symbol_type = eSymbolTypeCode;
2219 } else if (sect_name == data_section_name ||
2220 sect_name == data2_section_name ||
2221 sect_name == rodata_section_name ||
2222 sect_name == rodata1_section_name ||
2223 sect_name == bss_section_name) {
2224 symbol_type = eSymbolTypeData;
2225 }
2226 }
2227 }
2228
2229 int64_t symbol_value_offset = 0;
2230 uint32_t additional_flags = 0;
2231
2232 if (arch.IsValid()) {
2233 if (arch.GetMachine() == llvm::Triple::arm) {
2234 if (symbol.getBinding() == STB_LOCAL) {
2235 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2236 if (symbol_type == eSymbolTypeCode) {
2237 switch (mapping_symbol) {
2238 case 'a':
2239 // $a[.<any>]* - marks an ARM instruction sequence
2240 m_address_class_map[symbol.st_value] = eAddressClassCode;
2241 break;
2242 case 'b':
2243 case 't':
2244 // $b[.<any>]* - marks a THUMB BL instruction sequence
2245 // $t[.<any>]* - marks a THUMB instruction sequence
2246 m_address_class_map[symbol.st_value] =
2247 eAddressClassCodeAlternateISA;
2248 break;
2249 case 'd':
2250 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2251 m_address_class_map[symbol.st_value] = eAddressClassData;
2252 break;
2253 }
2254 }
2255 if (mapping_symbol)
2256 continue;
2257 }
2258 } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2259 if (symbol.getBinding() == STB_LOCAL) {
2260 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2261 if (symbol_type == eSymbolTypeCode) {
2262 switch (mapping_symbol) {
2263 case 'x':
2264 // $x[.<any>]* - marks an A64 instruction sequence
2265 m_address_class_map[symbol.st_value] = eAddressClassCode;
2266 break;
2267 case 'd':
2268 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2269 m_address_class_map[symbol.st_value] = eAddressClassData;
2270 break;
2271 }
2272 }
2273 if (mapping_symbol)
2274 continue;
2275 }
2276 }
2277
2278 if (arch.GetMachine() == llvm::Triple::arm) {
2279 if (symbol_type == eSymbolTypeCode) {
2280 if (symbol.st_value & 1) {
2281 // Subtracting 1 from the address effectively unsets
2282 // the low order bit, which results in the address
2283 // actually pointing to the beginning of the symbol.
2284 // This delta will be used below in conjunction with
2285 // symbol.st_value to produce the final symbol_value
2286 // that we store in the symtab.
2287 symbol_value_offset = -1;
2288 m_address_class_map[symbol.st_value ^ 1] =
2289 eAddressClassCodeAlternateISA;
2290 } else {
2291 // This address is ARM
2292 m_address_class_map[symbol.st_value] = eAddressClassCode;
2293 }
2294 }
2295 }
2296
2297 /*
2298 * MIPS:
2299 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2300 * MIPS).
2301 * This allows processor to switch between microMIPS and MIPS without any
2302 * need
2303 * for special mode-control register. However, apart from .debug_line,
2304 * none of
2305 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2306 * st_other
2307 * flag to check whether the symbol is microMIPS and then set the address
2308 * class
2309 * accordingly.
2310 */
2311 const llvm::Triple::ArchType llvm_arch = arch.GetMachine();
2312 if (llvm_arch == llvm::Triple::mips ||
2313 llvm_arch == llvm::Triple::mipsel ||
2314 llvm_arch == llvm::Triple::mips64 ||
2315 llvm_arch == llvm::Triple::mips64el) {
2316 if (IS_MICROMIPS(symbol.st_other))
2317 m_address_class_map[symbol.st_value] = eAddressClassCodeAlternateISA;
2318 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2319 symbol.st_value = symbol.st_value & (~1ull);
2320 m_address_class_map[symbol.st_value] = eAddressClassCodeAlternateISA;
2321 } else {
2322 if (symbol_type == eSymbolTypeCode)
2323 m_address_class_map[symbol.st_value] = eAddressClassCode;
2324 else if (symbol_type == eSymbolTypeData)
2325 m_address_class_map[symbol.st_value] = eAddressClassData;
2326 else
2327 m_address_class_map[symbol.st_value] = eAddressClassUnknown;
2328 }
2329 }
2330 }
2331
2332 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
2333 // symbols. See above for
2334 // more details.
2335 uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2336
2337 if (symbol_section_sp == nullptr && section_idx == SHN_ABS &&
2338 symbol.st_size != 0) {
2339 // We don't have a section for a symbol with non-zero size. Create a new
2340 // section for it
2341 // so the address range covered by the symbol is also covered by the
2342 // module (represented
2343 // through the section list). It is needed so module lookup for the
2344 // addresses covered
2345 // by this symbol will be successfull. This case happens for absolute
2346 // symbols.
2347 ConstString fake_section_name(std::string(".absolute.") + symbol_name);
2348 symbol_section_sp =
2349 std::make_shared<Section>(module_sp, this, SHN_ABS, fake_section_name,
2350 eSectionTypeAbsoluteAddress, symbol_value,
2351 symbol.st_size, 0, 0, 0, SHF_ALLOC);
2352
2353 module_section_list->AddSection(symbol_section_sp);
2354 section_list->AddSection(symbol_section_sp);
2355 }
2356
2357 if (symbol_section_sp &&
2358 CalculateType() != ObjectFile::Type::eTypeObjectFile)
2359 symbol_value -= symbol_section_sp->GetFileAddress();
2360
2361 if (symbol_section_sp && module_section_list &&
2362 module_section_list != section_list) {
2363 const ConstString &sect_name = symbol_section_sp->GetName();
2364 auto section_it = section_name_to_section.find(sect_name.GetCString());
2365 if (section_it == section_name_to_section.end())
2366 section_it =
2367 section_name_to_section
2368 .emplace(sect_name.GetCString(),
2369 module_section_list->FindSectionByName(sect_name))
2370 .first;
2371 if (section_it->second && section_it->second->GetFileSize())
2372 symbol_section_sp = section_it->second;
2373 }
2374
2375 bool is_global = symbol.getBinding() == STB_GLOBAL;
2376 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2377 bool is_mangled = (symbol_name[0] == '_' && symbol_name[1] == 'Z');
2378
2379 llvm::StringRef symbol_ref(symbol_name);
2380
2381 // Symbol names may contain @VERSION suffixes. Find those and strip them
2382 // temporarily.
2383 size_t version_pos = symbol_ref.find('@');
2384 bool has_suffix = version_pos != llvm::StringRef::npos;
2385 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2386 Mangled mangled(ConstString(symbol_bare), is_mangled);
2387
2388 // Now append the suffix back to mangled and unmangled names. Only do it if
2389 // the
2390 // demangling was successful (string is not empty).
2391 if (has_suffix) {
2392 llvm::StringRef suffix = symbol_ref.substr(version_pos);
2393
2394 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2395 if (!mangled_name.empty())
2396 mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2397
2398 ConstString demangled =
2399 mangled.GetDemangledName(lldb::eLanguageTypeUnknown);
2400 llvm::StringRef demangled_name = demangled.GetStringRef();
2401 if (!demangled_name.empty())
2402 mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2403 }
2404
2405 // In ELF all symbol should have a valid size but it is not true for some
2406 // function symbols
2407 // coming from hand written assembly. As none of the function symbol should
2408 // have 0 size we
2409 // try to calculate the size for these symbols in the symtab with saying
2410 // that their original
2411 // size is not valid.
2412 bool symbol_size_valid =
2413 symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2414
2415 Symbol dc_symbol(
2416 i + start_id, // ID is the original symbol table index.
2417 mangled,
2418 symbol_type, // Type of this symbol
2419 is_global, // Is this globally visible?
2420 false, // Is this symbol debug info?
2421 false, // Is this symbol a trampoline?
2422 false, // Is this symbol artificial?
2423 AddressRange(symbol_section_sp, // Section in which this symbol is
2424 // defined or null.
2425 symbol_value, // Offset in section or symbol value.
2426 symbol.st_size), // Size in bytes of this symbol.
2427 symbol_size_valid, // Symbol size is valid
2428 has_suffix, // Contains linker annotations?
2429 flags); // Symbol flags.
2430 symtab->AddSymbol(dc_symbol);
2431 }
2432 return i;
2433}
2434
2435unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
2436 user_id_t start_id,
2437 lldb_private::Section *symtab) {
2438 if (symtab->GetObjectFile() != this) {
2439 // If the symbol table section is owned by a different object file, have it
2440 // do the
2441 // parsing.
2442 ObjectFileELF *obj_file_elf =
2443 static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2444 return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2445 }
2446
2447 // Get section list for this object file.
2448 SectionList *section_list = m_sections_ap.get();
2449 if (!section_list)
2450 return 0;
2451
2452 user_id_t symtab_id = symtab->GetID();
2453 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2454 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2455 symtab_hdr->sh_type == SHT_DYNSYM);
2456
2457 // sh_link: section header index of associated string table.
2458 // Section ID's are ones based.
2459 user_id_t strtab_id = symtab_hdr->sh_link + 1;
2460 Section *strtab = section_list->FindSectionByID(strtab_id).get();
2461
2462 if (symtab && strtab) {
2463 assert(symtab->GetObjectFile() == this);
2464 assert(strtab->GetObjectFile() == this);
2465
2466 DataExtractor symtab_data;
2467 DataExtractor strtab_data;
2468 if (ReadSectionData(symtab, symtab_data) &&
2469 ReadSectionData(strtab, strtab_data)) {
2470 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2471
2472 return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2473 symtab_data, strtab_data);
2474 }
2475 }
2476
2477 return 0;
2478}
2479
2480size_t ObjectFileELF::ParseDynamicSymbols() {
2481 if (m_dynamic_symbols.size())
2482 return m_dynamic_symbols.size();
2483
2484 SectionList *section_list = GetSectionList();
2485 if (!section_list)
2486 return 0;
2487
2488 // Find the SHT_DYNAMIC section.
2489 Section *dynsym =
2490 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
2491 .get();
2492 if (!dynsym)
2493 return 0;
2494 assert(dynsym->GetObjectFile() == this);
2495
2496 ELFDynamic symbol;
2497 DataExtractor dynsym_data;
2498 if (ReadSectionData(dynsym, dynsym_data)) {
2499 const lldb::offset_t section_size = dynsym_data.GetByteSize();
2500 lldb::offset_t cursor = 0;
2501
2502 while (cursor < section_size) {
2503 if (!symbol.Parse(dynsym_data, &cursor))
2504 break;
2505
2506 m_dynamic_symbols.push_back(symbol);
2507 }
2508 }
2509
2510 return m_dynamic_symbols.size();
2511}
2512
2513const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
2514 if (!ParseDynamicSymbols())
2515 return NULL;
2516
2517 DynamicSymbolCollIter I = m_dynamic_symbols.begin();
2518 DynamicSymbolCollIter E = m_dynamic_symbols.end();
2519 for (; I != E; ++I) {
2520 ELFDynamic *symbol = &*I;
2521
2522 if (symbol->d_tag == tag)
2523 return symbol;
2524 }
2525
2526 return NULL;
2527}
2528
2529unsigned ObjectFileELF::PLTRelocationType() {
2530 // DT_PLTREL
2531 // This member specifies the type of relocation entry to which the
2532 // procedure linkage table refers. The d_val member holds DT_REL or
2533 // DT_RELA, as appropriate. All relocations in a procedure linkage table
2534 // must use the same relocation.
2535 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2536
2537 if (symbol)
2538 return symbol->d_val;
2539
2540 return 0;
2541}
2542
2543// Returns the size of the normal plt entries and the offset of the first normal
2544// plt entry. The
2545// 0th entry in the plt table is usually a resolution entry which have different
2546// size in some
2547// architectures then the rest of the plt entries.
2548static std::pair<uint64_t, uint64_t>
2549GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
2550 const ELFSectionHeader *plt_hdr) {
2551 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2552
2553 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 16
2554 // bytes.
2555 // So round the entsize up by the alignment if addralign is set.
2556 elf_xword plt_entsize =
2557 plt_hdr->sh_addralign
2558 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2559 : plt_hdr->sh_entsize;
2560
2561 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2562 // PLT entries relocation code in general requires multiple instruction and
2563 // should be greater than 4 bytes in most cases. Try to guess correct size
2564 // just in case.
2565 if (plt_entsize <= 4) {
2566 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
2567 // size of the plt
2568 // entries based on the number of entries and the size of the plt section
2569 // with the
2570 // assumption that the size of the 0th entry is at least as big as the size
2571 // of the normal
2572 // entries and it isn't much bigger then that.
2573 if (plt_hdr->sh_addralign)
2574 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2575 (num_relocations + 1) * plt_hdr->sh_addralign;
2576 else
2577 plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2578 }
2579
2580 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2581
2582 return std::make_pair(plt_entsize, plt_offset);
2583}
2584
2585static unsigned ParsePLTRelocations(
2586 Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2587 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2588 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2589 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2590 DataExtractor &symtab_data, DataExtractor &strtab_data) {
2591 ELFRelocation rel(rel_type);
2592 ELFSymbol symbol;
2593 lldb::offset_t offset = 0;
2594
2595 uint64_t plt_offset, plt_entsize;
2596 std::tie(plt_entsize, plt_offset) =
2597 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2598 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2599
2600 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2601 reloc_info_fn reloc_type;
2602 reloc_info_fn reloc_symbol;
2603
2604 if (hdr->Is32Bit()) {
2605 reloc_type = ELFRelocation::RelocType32;
2606 reloc_symbol = ELFRelocation::RelocSymbol32;
2607 } else {
2608 reloc_type = ELFRelocation::RelocType64;
2609 reloc_symbol = ELFRelocation::RelocSymbol64;
2610 }
2611
2612 unsigned slot_type = hdr->GetRelocationJumpSlotType();
2613 unsigned i;
2614 for (i = 0; i < num_relocations; ++i) {
2615 if (rel.Parse(rel_data, &offset) == false)
2616 break;
2617
2618 if (reloc_type(rel) != slot_type)
2619 continue;
2620
2621 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2622 if (!symbol.Parse(symtab_data, &symbol_offset))
2623 break;
2624
2625 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2626 bool is_mangled =
2627 symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
2628 uint64_t plt_index = plt_offset + i * plt_entsize;
2629
2630 Symbol jump_symbol(
2631 i + start_id, // Symbol table index
2632 symbol_name, // symbol name.
2633 is_mangled, // is the symbol name mangled?
2634 eSymbolTypeTrampoline, // Type of this symbol
2635 false, // Is this globally visible?
2636 false, // Is this symbol debug info?
2637 true, // Is this symbol a trampoline?
2638 true, // Is this symbol artificial?
2639 plt_section_sp, // Section in which this symbol is defined or null.
2640 plt_index, // Offset in section or symbol value.
2641 plt_entsize, // Size in bytes of this symbol.
2642 true, // Size is valid
2643 false, // Contains linker annotations?
2644 0); // Symbol flags.
2645
2646 symbol_table->AddSymbol(jump_symbol);
2647 }
2648
2649 return i;
2650}
2651
2652unsigned
2653ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
2654 const ELFSectionHeaderInfo *rel_hdr,
2655 user_id_t rel_id) {
2656 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2657
2658 // The link field points to the associated symbol table.
2659 user_id_t symtab_id = rel_hdr->sh_link;
2660
2661 // If the link field doesn't point to the appropriate symbol name table then
2662 // try to find it by name as some compiler don't fill in the link fields.
2663 if (!symtab_id)
2664 symtab_id = GetSectionIndexByName(".dynsym");
2665
2666 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers
2667 // point that to the .got.plt or .got section instead of .plt.
2668 user_id_t plt_id = GetSectionIndexByName(".plt");
2669
2670 if (!symtab_id || !plt_id)
2671 return 0;
2672
2673 // Section ID's are ones based;
2674 symtab_id++;
2675 plt_id++;
2676
2677 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2678 if (!plt_hdr)
2679 return 0;
2680
2681 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2682 if (!sym_hdr)
2683 return 0;
2684
2685 SectionList *section_list = m_sections_ap.get();
2686 if (!section_list)
2687 return 0;
2688
2689 Section *rel_section = section_list->FindSectionByID(rel_id).get();
2690 if (!rel_section)
2691 return 0;
2692
2693 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2694 if (!plt_section_sp)
2695 return 0;
2696
2697 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2698 if (!symtab)
2699 return 0;
2700
2701 // sh_link points to associated string table.
2702 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link + 1).get();
2703 if (!strtab)
2704 return 0;
2705
2706 DataExtractor rel_data;
2707 if (!ReadSectionData(rel_section, rel_data))
2708 return 0;
2709
2710 DataExtractor symtab_data;
2711 if (!ReadSectionData(symtab, symtab_data))
2712 return 0;
2713
2714 DataExtractor strtab_data;
2715 if (!ReadSectionData(strtab, strtab_data))
2716 return 0;
2717
2718 unsigned rel_type = PLTRelocationType();
2719 if (!rel_type)
2720 return 0;
2721
2722 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2723 rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2724 rel_data, symtab_data, strtab_data);
2725}
2726
2727unsigned ObjectFileELF::RelocateSection(
2728 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2729 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
2730 DataExtractor &rel_data, DataExtractor &symtab_data,
2731 DataExtractor &debug_data, Section *rel_section) {
2732 ELFRelocation rel(rel_hdr->sh_type);
2733 lldb::addr_t offset = 0;
2734 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2735 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2736 reloc_info_fn reloc_type;
2737 reloc_info_fn reloc_symbol;
2738
2739 if (hdr->Is32Bit()) {
2740 reloc_type = ELFRelocation::RelocType32;
2741 reloc_symbol = ELFRelocation::RelocSymbol32;
2742 } else {
2743 reloc_type = ELFRelocation::RelocType64;
2744 reloc_symbol = ELFRelocation::RelocSymbol64;
2745 }
2746
2747 for (unsigned i = 0; i < num_relocations; ++i) {
2748 if (rel.Parse(rel_data, &offset) == false)
2749 break;
2750
2751 Symbol *symbol = NULL;
2752
2753 if (hdr->Is32Bit()) {
2754 switch (reloc_type(rel)) {
2755 case R_386_32:
2756 case R_386_PC32:
2757 default:
2758 assert(false && "unexpected relocation type");
2759 }
2760 } else {
2761 switch (reloc_type(rel)) {
2762 case R_X86_64_64: {
2763 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2764 if (symbol) {
2765 addr_t value = symbol->GetAddressRef().GetFileAddress();
2766 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2767 uint64_t *dst = reinterpret_cast<uint64_t *>(
2768 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2769 ELFRelocation::RelocOffset64(rel));
2770 *dst = value + ELFRelocation::RelocAddend64(rel);
2771 }
2772 break;
2773 }
2774 case R_X86_64_32:
2775 case R_X86_64_32S: {
2776 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2777 if (symbol) {
2778 addr_t value = symbol->GetAddressRef().GetFileAddress();
2779 value += ELFRelocation::RelocAddend32(rel);
2780 assert(
2781 (reloc_type(rel) == R_X86_64_32 && (value <= UINT32_MAX)) ||
2782 (reloc_type(rel) == R_X86_64_32S &&
2783 ((int64_t)value <= INT32_MAX && (int64_t)value >= INT32_MIN)));
2784 uint32_t truncated_addr = (value & 0xFFFFFFFF);
2785 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2786 uint32_t *dst = reinterpret_cast<uint32_t *>(
2787 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2788 ELFRelocation::RelocOffset32(rel));
2789 *dst = truncated_addr;
2790 }
2791 break;
2792 }
2793 case R_X86_64_PC32:
2794 default:
2795 assert(false && "unexpected relocation type");
2796 }
2797 }
2798 }
2799
2800 return 0;
2801}
2802
2803unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
2804 user_id_t rel_id) {
2805 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2806
2807 // Parse in the section list if needed.
2808 SectionList *section_list = GetSectionList();
2809 if (!section_list)
2810 return 0;
2811
2812 // Section ID's are ones based.
2813 user_id_t symtab_id = rel_hdr->sh_link + 1;
2814 user_id_t debug_id = rel_hdr->sh_info + 1;
2815
2816 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2817 if (!symtab_hdr)
2818 return 0;
2819
2820 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
2821 if (!debug_hdr)
2822 return 0;
2823
2824 Section *rel = section_list->FindSectionByID(rel_id).get();
2825 if (!rel)
2826 return 0;
2827
2828 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2829 if (!symtab)
2830 return 0;
2831
2832 Section *debug = section_list->FindSectionByID(debug_id).get();
2833 if (!debug)
2834 return 0;
2835
2836 DataExtractor rel_data;
2837 DataExtractor symtab_data;
2838 DataExtractor debug_data;
2839
2840 if (ReadSectionData(rel, rel_data) && ReadSectionData(symtab, symtab_data) &&
2841 ReadSectionData(debug, debug_data)) {
2842 RelocateSection(m_symtab_ap.get(), &m_header, rel_hdr, symtab_hdr,
2843 debug_hdr, rel_data, symtab_data, debug_data, debug);
2844 }
2845
2846 return 0;
2847}
2848
2849Symtab *ObjectFileELF::GetSymtab() {
2850 ModuleSP module_sp(GetModule());
2851 if (!module_sp)
2852 return NULL;
2853
2854 // We always want to use the main object file so we (hopefully) only have one
2855 // cached copy
2856 // of our symtab, dynamic sections, etc.
2857 ObjectFile *module_obj_file = module_sp->GetObjectFile();
2858 if (module_obj_file && module_obj_file != this)
2859 return module_obj_file->GetSymtab();
2860
2861 if (m_symtab_ap.get() == NULL) {
2862 SectionList *section_list = module_sp->GetSectionList();
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002863 if (!section_list)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002864 return NULL;
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002865
Kate Stoneb9c1b512016-09-06 20:57:50 +00002866 uint64_t symbol_id = 0;
2867 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002868
Kate Stoneb9c1b512016-09-06 20:57:50 +00002869 // Sharable objects and dynamic executables usually have 2 distinct symbol
2870 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
2871 // smaller
2872 // version of the symtab that only contains global symbols. The information
2873 // found
2874 // in the dynsym is therefore also found in the symtab, while the reverse is
2875 // not
2876 // necessarily true.
2877 Section *symtab =
2878 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
2879 if (!symtab) {
2880 // The symtab section is non-allocable and can be stripped, so if it
2881 // doesn't exist
2882 // then use the dynsym section which should always be there.
2883 symtab =
2884 section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
2885 .get();
2886 }
2887 if (symtab) {
2888 m_symtab_ap.reset(new Symtab(symtab->GetObjectFile()));
2889 symbol_id += ParseSymbolTable(m_symtab_ap.get(), symbol_id, symtab);
2890 }
2891
2892 // DT_JMPREL
2893 // If present, this entry's d_ptr member holds the address of
2894 // relocation
2895 // entries associated solely with the procedure linkage table.
2896 // Separating
2897 // these relocation entries lets the dynamic linker ignore them during
2898 // process initialization, if lazy binding is enabled. If this entry is
2899 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
2900 // also be present.
2901 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
2902 if (symbol) {
2903 // Synthesize trampoline symbols to help navigate the PLT.
2904 addr_t addr = symbol->d_ptr;
2905 Section *reloc_section =
2906 section_list->FindSectionContainingFileAddress(addr).get();
2907 if (reloc_section) {
2908 user_id_t reloc_id = reloc_section->GetID();
2909 const ELFSectionHeaderInfo *reloc_header =
2910 GetSectionHeaderByIndex(reloc_id);
2911 assert(reloc_header);
2912
2913 if (m_symtab_ap == nullptr)
2914 m_symtab_ap.reset(new Symtab(reloc_section->GetObjectFile()));
2915
2916 ParseTrampolineSymbols(m_symtab_ap.get(), symbol_id, reloc_header,
2917 reloc_id);
2918 }
2919 }
2920
2921 DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo();
2922 if (eh_frame) {
2923 if (m_symtab_ap == nullptr)
2924 m_symtab_ap.reset(new Symtab(this));
2925 ParseUnwindSymbols(m_symtab_ap.get(), eh_frame);
2926 }
2927
2928 // If we still don't have any symtab then create an empty instance to avoid
2929 // do the section
2930 // lookup next time.
2931 if (m_symtab_ap == nullptr)
2932 m_symtab_ap.reset(new Symtab(this));
2933
2934 m_symtab_ap->CalculateSymbolSizes();
2935 }
2936
2937 for (SectionHeaderCollIter I = m_section_headers.begin();
2938 I != m_section_headers.end(); ++I) {
2939 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
2940 if (CalculateType() == eTypeObjectFile) {
2941 const char *section_name = I->section_name.AsCString("");
2942 if (strstr(section_name, ".rela.debug") ||
2943 strstr(section_name, ".rel.debug")) {
2944 const ELFSectionHeader &reloc_header = *I;
2945 user_id_t reloc_id = SectionIndex(I);
2946 RelocateDebugSections(&reloc_header, reloc_id);
Tamas Berghammered844cb2016-02-10 10:43:34 +00002947 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002948 }
2949 }
2950 }
2951 return m_symtab_ap.get();
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002952}
Tamas Berghammer5bfd4d02016-02-10 12:10:58 +00002953
Kate Stoneb9c1b512016-09-06 20:57:50 +00002954void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
2955 DWARFCallFrameInfo *eh_frame) {
2956 SectionList *section_list = GetSectionList();
2957 if (!section_list)
2958 return;
2959
2960 // First we save the new symbols into a separate list and add them to the
2961 // symbol table after
2962 // we colleced all symbols we want to add. This is neccessary because adding a
2963 // new symbol
2964 // invalidates the internal index of the symtab what causing the next lookup
2965 // to be slow because
2966 // it have to recalculate the index first.
2967 std::vector<Symbol> new_symbols;
2968
2969 eh_frame->ForEachFDEEntries([this, symbol_table, section_list, &new_symbols](
2970 lldb::addr_t file_addr, uint32_t size, dw_offset_t) {
2971 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
2972 if (symbol) {
2973 if (!symbol->GetByteSizeIsValid()) {
2974 symbol->SetByteSize(size);
2975 symbol->SetSizeIsSynthesized(true);
2976 }
2977 } else {
2978 SectionSP section_sp =
2979 section_list->FindSectionContainingFileAddress(file_addr);
2980 if (section_sp) {
2981 addr_t offset = file_addr - section_sp->GetFileAddress();
2982 const char *symbol_name = GetNextSyntheticSymbolName().GetCString();
2983 uint64_t symbol_id = symbol_table->GetNumSymbols();
2984 Symbol eh_symbol(
2985 symbol_id, // Symbol table index.
2986 symbol_name, // Symbol name.
2987 false, // Is the symbol name mangled?
2988 eSymbolTypeCode, // Type of this symbol.
2989 true, // Is this globally visible?
2990 false, // Is this symbol debug info?
2991 false, // Is this symbol a trampoline?
2992 true, // Is this symbol artificial?
2993 section_sp, // Section in which this symbol is defined or null.
2994 offset, // Offset in section or symbol value.
2995 0, // Size: Don't specify the size as an FDE can
2996 false, // Size is valid: cover multiple symbols.
2997 false, // Contains linker annotations?
2998 0); // Symbol flags.
2999 new_symbols.push_back(eh_symbol);
3000 }
3001 }
3002 return true;
3003 });
3004
3005 for (const Symbol &s : new_symbols)
3006 symbol_table->AddSymbol(s);
3007}
3008
3009bool ObjectFileELF::IsStripped() {
3010 // TODO: determine this for ELF
3011 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003012}
3013
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003014//===----------------------------------------------------------------------===//
3015// Dump
3016//
3017// Dump the specifics of the runtime file container (such as any headers
3018// segments, sections, etc).
3019//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003020void ObjectFileELF::Dump(Stream *s) {
3021 ModuleSP module_sp(GetModule());
3022 if (!module_sp) {
3023 return;
3024 }
Adrian McCarthy543725c2016-04-04 21:21:49 +00003025
Kate Stoneb9c1b512016-09-06 20:57:50 +00003026 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3027 s->Printf("%p: ", static_cast<void *>(this));
3028 s->Indent();
3029 s->PutCString("ObjectFileELF");
Adrian McCarthy543725c2016-04-04 21:21:49 +00003030
Kate Stoneb9c1b512016-09-06 20:57:50 +00003031 ArchSpec header_arch;
3032 GetArchitecture(header_arch);
Adrian McCarthy543725c2016-04-04 21:21:49 +00003033
Kate Stoneb9c1b512016-09-06 20:57:50 +00003034 *s << ", file = '" << m_file
3035 << "', arch = " << header_arch.GetArchitectureName() << "\n";
Adrian McCarthy543725c2016-04-04 21:21:49 +00003036
Kate Stoneb9c1b512016-09-06 20:57:50 +00003037 DumpELFHeader(s, m_header);
3038 s->EOL();
3039 DumpELFProgramHeaders(s);
3040 s->EOL();
3041 DumpELFSectionHeaders(s);
3042 s->EOL();
3043 SectionList *section_list = GetSectionList();
3044 if (section_list)
3045 section_list->Dump(s, NULL, true, UINT32_MAX);
3046 Symtab *symtab = GetSymtab();
3047 if (symtab)
3048 symtab->Dump(s, NULL, eSortOrderNone);
3049 s->EOL();
3050 DumpDependentModules(s);
3051 s->EOL();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052}
3053
3054//----------------------------------------------------------------------
3055// DumpELFHeader
3056//
3057// Dump the ELF header to the specified output stream
3058//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003059void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
3060 s->PutCString("ELF Header\n");
3061 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
3062 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
3063 header.e_ident[EI_MAG1]);
3064 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
3065 header.e_ident[EI_MAG2]);
3066 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
3067 header.e_ident[EI_MAG3]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003068
Kate Stoneb9c1b512016-09-06 20:57:50 +00003069 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
3070 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
3071 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
3072 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
3073 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003074
Kate Stoneb9c1b512016-09-06 20:57:50 +00003075 s->Printf("e_type = 0x%4.4x ", header.e_type);
3076 DumpELFHeader_e_type(s, header.e_type);
3077 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
3078 s->Printf("e_version = 0x%8.8x\n", header.e_version);
3079 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
3080 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
3081 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
3082 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
3083 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
3084 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
Pavel Labath23ccc292017-01-31 23:09:46 +00003085 s->Printf("e_phnum = 0x%8.8x\n", header.e_phnum);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003086 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
Pavel Labath23ccc292017-01-31 23:09:46 +00003087 s->Printf("e_shnum = 0x%8.8x\n", header.e_shnum);
3088 s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003089}
3090
3091//----------------------------------------------------------------------
3092// DumpELFHeader_e_type
3093//
3094// Dump an token value for the ELF header member e_type
3095//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003096void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
3097 switch (e_type) {
3098 case ET_NONE:
3099 *s << "ET_NONE";
3100 break;
3101 case ET_REL:
3102 *s << "ET_REL";
3103 break;
3104 case ET_EXEC:
3105 *s << "ET_EXEC";
3106 break;
3107 case ET_DYN:
3108 *s << "ET_DYN";
3109 break;
3110 case ET_CORE:
3111 *s << "ET_CORE";
3112 break;
3113 default:
3114 break;
3115 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003116}
3117
3118//----------------------------------------------------------------------
3119// DumpELFHeader_e_ident_EI_DATA
3120//
3121// Dump an token value for the ELF header member e_ident[EI_DATA]
3122//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003123void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
3124 unsigned char ei_data) {
3125 switch (ei_data) {
3126 case ELFDATANONE:
3127 *s << "ELFDATANONE";
3128 break;
3129 case ELFDATA2LSB:
3130 *s << "ELFDATA2LSB - Little Endian";
3131 break;
3132 case ELFDATA2MSB:
3133 *s << "ELFDATA2MSB - Big Endian";
3134 break;
3135 default:
3136 break;
3137 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003138}
3139
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003140//----------------------------------------------------------------------
3141// DumpELFProgramHeader
3142//
3143// Dump a single ELF program header to the specified output stream
3144//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003145void ObjectFileELF::DumpELFProgramHeader(Stream *s,
3146 const ELFProgramHeader &ph) {
3147 DumpELFProgramHeader_p_type(s, ph.p_type);
3148 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3149 ph.p_vaddr, ph.p_paddr);
3150 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3151 ph.p_flags);
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003152
Kate Stoneb9c1b512016-09-06 20:57:50 +00003153 DumpELFProgramHeader_p_flags(s, ph.p_flags);
3154 s->Printf(") %8.8" PRIx64, ph.p_align);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003155}
3156
3157//----------------------------------------------------------------------
3158// DumpELFProgramHeader_p_type
3159//
3160// Dump an token value for the ELF program header member p_type which
3161// describes the type of the program header
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003162// ----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
3164 const int kStrWidth = 15;
3165 switch (p_type) {
3166 CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3167 CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3168 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3169 CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3170 CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3171 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3172 CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3173 CASE_AND_STREAM(s, PT_TLS, kStrWidth);
Filipe Cabecinhas477d86d2013-05-23 23:01:14 +00003174 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003175 default:
3176 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3177 break;
3178 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179}
3180
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003181//----------------------------------------------------------------------
3182// DumpELFProgramHeader_p_flags
3183//
3184// Dump an token value for the ELF program header member p_flags
3185//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
3187 *s << ((p_flags & PF_X) ? "PF_X" : " ")
3188 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3189 << ((p_flags & PF_W) ? "PF_W" : " ")
3190 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3191 << ((p_flags & PF_R) ? "PF_R" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192}
3193
3194//----------------------------------------------------------------------
3195// DumpELFProgramHeaders
3196//
3197// Dump all of the ELF program header to the specified output stream
3198//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003199void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
3200 if (!ParseProgramHeaders())
3201 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003202
Kate Stoneb9c1b512016-09-06 20:57:50 +00003203 s->PutCString("Program Headers\n");
3204 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
3205 "p_filesz p_memsz p_flags p_align\n");
3206 s->PutCString("==== --------------- -------- -------- -------- "
3207 "-------- -------- ------------------------- --------\n");
Ed Maste3a8ab6e2015-02-23 15:33:11 +00003208
Kate Stoneb9c1b512016-09-06 20:57:50 +00003209 uint32_t idx = 0;
3210 for (ProgramHeaderCollConstIter I = m_program_headers.begin();
3211 I != m_program_headers.end(); ++I, ++idx) {
3212 s->Printf("[%2u] ", idx);
3213 ObjectFileELF::DumpELFProgramHeader(s, *I);
3214 s->EOL();
3215 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003216}
3217
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003218//----------------------------------------------------------------------
3219// DumpELFSectionHeader
3220//
3221// Dump a single ELF section header to the specified output stream
3222//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003223void ObjectFileELF::DumpELFSectionHeader(Stream *s,
3224 const ELFSectionHeaderInfo &sh) {
3225 s->Printf("%8.8x ", sh.sh_name);
3226 DumpELFSectionHeader_sh_type(s, sh.sh_type);
3227 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3228 DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
3229 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3230 sh.sh_offset, sh.sh_size);
3231 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3232 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003233}
3234
3235//----------------------------------------------------------------------
3236// DumpELFSectionHeader_sh_type
3237//
3238// Dump an token value for the ELF section header member sh_type which
3239// describes the type of the section
3240//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003241void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
3242 const int kStrWidth = 12;
3243 switch (sh_type) {
3244 CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3245 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3246 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3247 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3248 CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3249 CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3250 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3251 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3252 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3253 CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3254 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3255 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3256 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3257 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3258 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3259 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3260 default:
3261 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3262 break;
3263 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003264}
3265
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003266//----------------------------------------------------------------------
3267// DumpELFSectionHeader_sh_flags
3268//
3269// Dump an token value for the ELF section header member sh_flags
3270//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003271void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
3272 elf_xword sh_flags) {
3273 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
3274 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3275 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
3276 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3277 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003278}
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003279
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003280//----------------------------------------------------------------------
3281// DumpELFSectionHeaders
3282//
3283// Dump all of the ELF section header to the specified output stream
3284//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003285void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
3286 if (!ParseSectionHeaders())
3287 return;
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003288
Kate Stoneb9c1b512016-09-06 20:57:50 +00003289 s->PutCString("Section Headers\n");
3290 s->PutCString("IDX name type flags "
3291 "addr offset size link info addralgn "
3292 "entsize Name\n");
3293 s->PutCString("==== -------- ------------ -------------------------------- "
3294 "-------- -------- -------- -------- -------- -------- "
3295 "-------- ====================\n");
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003296
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297 uint32_t idx = 0;
3298 for (SectionHeaderCollConstIter I = m_section_headers.begin();
3299 I != m_section_headers.end(); ++I, ++idx) {
3300 s->Printf("[%2u] ", idx);
3301 ObjectFileELF::DumpELFSectionHeader(s, *I);
3302 const char *section_name = I->section_name.AsCString("");
3303 if (section_name)
3304 *s << ' ' << section_name << "\n";
3305 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003306}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003307
Kate Stoneb9c1b512016-09-06 20:57:50 +00003308void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
3309 size_t num_modules = ParseDependentModules();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003310
Kate Stoneb9c1b512016-09-06 20:57:50 +00003311 if (num_modules > 0) {
3312 s->PutCString("Dependent Modules:\n");
3313 for (unsigned i = 0; i < num_modules; ++i) {
3314 const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
3315 s->Printf(" %s\n", spec.GetFilename().GetCString());
3316 }
3317 }
3318}
3319
3320bool ObjectFileELF::GetArchitecture(ArchSpec &arch) {
3321 if (!ParseHeader())
3322 return false;
3323
3324 if (m_section_headers.empty()) {
3325 // Allow elf notes to be parsed which may affect the detected architecture.
3326 ParseSectionHeaders();
3327 }
3328
3329 if (CalculateType() == eTypeCoreFile &&
3330 m_arch_spec.TripleOSIsUnspecifiedUnknown()) {
3331 // Core files don't have section headers yet they have PT_NOTE program
3332 // headers
3333 // that might shed more light on the architecture
3334 if (ParseProgramHeaders()) {
3335 for (size_t i = 0, count = GetProgramHeaderCount(); i < count; ++i) {
3336 const elf::ELFProgramHeader *header = GetProgramHeaderByIndex(i);
3337 if (header && header->p_type == PT_NOTE && header->p_offset != 0 &&
3338 header->p_filesz > 0) {
3339 DataExtractor data;
3340 if (data.SetData(m_data, header->p_offset, header->p_filesz) ==
3341 header->p_filesz) {
3342 lldb_private::UUID uuid;
3343 RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
3344 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003345 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003346 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003347 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003348 }
3349 arch = m_arch_spec;
3350 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003351}
3352
Kate Stoneb9c1b512016-09-06 20:57:50 +00003353ObjectFile::Type ObjectFileELF::CalculateType() {
3354 switch (m_header.e_type) {
3355 case llvm::ELF::ET_NONE:
3356 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003357 return eTypeUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003358
3359 case llvm::ELF::ET_REL:
3360 // 1 - Relocatable file
3361 return eTypeObjectFile;
3362
3363 case llvm::ELF::ET_EXEC:
3364 // 2 - Executable file
3365 return eTypeExecutable;
3366
3367 case llvm::ELF::ET_DYN:
3368 // 3 - Shared object file
3369 return eTypeSharedLibrary;
3370
3371 case ET_CORE:
3372 // 4 - Core file
3373 return eTypeCoreFile;
3374
3375 default:
3376 break;
3377 }
3378 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003379}
3380
Kate Stoneb9c1b512016-09-06 20:57:50 +00003381ObjectFile::Strata ObjectFileELF::CalculateStrata() {
3382 switch (m_header.e_type) {
3383 case llvm::ELF::ET_NONE:
3384 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003385 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003386
Kate Stoneb9c1b512016-09-06 20:57:50 +00003387 case llvm::ELF::ET_REL:
3388 // 1 - Relocatable file
3389 return eStrataUnknown;
3390
3391 case llvm::ELF::ET_EXEC:
3392 // 2 - Executable file
3393 // TODO: is there any way to detect that an executable is a kernel
3394 // related executable by inspecting the program headers, section
3395 // headers, symbols, or any other flag bits???
3396 return eStrataUser;
3397
3398 case llvm::ELF::ET_DYN:
3399 // 3 - Shared object file
3400 // TODO: is there any way to detect that an shared library is a kernel
3401 // related executable by inspecting the program headers, section
3402 // headers, symbols, or any other flag bits???
3403 return eStrataUnknown;
3404
3405 case ET_CORE:
3406 // 4 - Core file
3407 // TODO: is there any way to detect that an core file is a kernel
3408 // related executable by inspecting the program headers, section
3409 // headers, symbols, or any other flag bits???
3410 return eStrataUnknown;
3411
3412 default:
3413 break;
3414 }
3415 return eStrataUnknown;
3416}