blob: 406fa501735385d6e333429603fcd67e77dcfa7c [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"
18#include "lldb/Core/Error.h"
Stephen Wilsonf325ba92010-07-13 23:07:23 +000019#include "lldb/Core/FileSpecList.h"
Ed Mastec113ff82013-12-02 17:49:13 +000020#include "lldb/Core/Log.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000021#include "lldb/Core/Module.h"
Greg Claytonf4d6de62013-04-24 22:29:28 +000022#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000023#include "lldb/Core/PluginManager.h"
24#include "lldb/Core/Section.h"
25#include "lldb/Core/Stream.h"
Todd Fiala4339f3a2014-03-25 19:29:09 +000026#include "lldb/Core/Timer.h"
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +000027#include "lldb/Symbol/DWARFCallFrameInfo.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000028#include "lldb/Symbol/SymbolContext.h"
Steve Pucci9e02dac2014-02-06 19:02:19 +000029#include "lldb/Target/SectionLoadList.h"
Ed Maste54803652013-10-11 17:39:07 +000030#include "lldb/Target/Target.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;
613 if (header.Parse(data, &data_offset)) {
614 if (data_sp) {
615 ModuleSpec spec(file);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000616
Kate Stoneb9c1b512016-09-06 20:57:50 +0000617 const uint32_t sub_type = subTypeFromElfHeader(header);
618 spec.GetArchitecture().SetArchitecture(
619 eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000620
Kate Stoneb9c1b512016-09-06 20:57:50 +0000621 if (spec.GetArchitecture().IsValid()) {
622 llvm::Triple::OSType ostype;
623 llvm::Triple::VendorType vendor;
624 llvm::Triple::OSType spec_ostype =
625 spec.GetArchitecture().GetTriple().getOS();
Todd Fialab91de782014-06-27 16:52:49 +0000626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627 if (log)
628 log->Printf("ObjectFileELF::%s file '%s' module OSABI: %s",
629 __FUNCTION__, file.GetPath().c_str(),
630 OSABIAsCString(header.e_ident[EI_OSABI]));
Ed Mastef6a13122015-06-05 13:03:08 +0000631
Kate Stoneb9c1b512016-09-06 20:57:50 +0000632 // SetArchitecture should have set the vendor to unknown
633 vendor = spec.GetArchitecture().GetTriple().getVendor();
634 assert(vendor == llvm::Triple::UnknownVendor);
Ed Mastef6a13122015-06-05 13:03:08 +0000635
Kate Stoneb9c1b512016-09-06 20:57:50 +0000636 //
637 // Validate it is ok to remove GetOsFromOSABI
638 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
639 assert(spec_ostype == ostype);
640 if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
641 if (log)
642 log->Printf("ObjectFileELF::%s file '%s' set ELF module OS type "
643 "from ELF header OSABI.",
644 __FUNCTION__, file.GetPath().c_str());
645 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000646
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 // Try to get the UUID from the section list. Usually that's at the
648 // end, so
649 // map the file in if we don't have it already.
650 size_t section_header_end =
651 header.e_shoff + header.e_shnum * header.e_shentsize;
652 if (section_header_end > data_sp->GetByteSize()) {
653 data_sp = file.MemoryMapFileContentsIfLocal(file_offset,
654 section_header_end);
655 data.SetData(data_sp);
656 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000657
Kate Stoneb9c1b512016-09-06 20:57:50 +0000658 uint32_t gnu_debuglink_crc = 0;
659 std::string gnu_debuglink_file;
660 SectionHeaderColl section_headers;
661 lldb_private::UUID &uuid = spec.GetUUID();
Michael Sartain9f4517a2013-07-03 01:52:14 +0000662
Kate Stoneb9c1b512016-09-06 20:57:50 +0000663 using namespace std::placeholders;
664 const SetDataFunction set_data =
665 std::bind(&ObjectFileELF::SetData, std::cref(data), _1, _2, _3);
666 GetSectionHeaderInfo(section_headers, set_data, header, uuid,
667 gnu_debuglink_file, gnu_debuglink_crc,
668 spec.GetArchitecture());
Ravitheja Addepally15f89c42016-01-19 12:55:21 +0000669
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
Todd Fialab91de782014-06-27 16:52:49 +0000671
Kate Stoneb9c1b512016-09-06 20:57:50 +0000672 if (log)
673 log->Printf("ObjectFileELF::%s file '%s' module set to triple: %s "
674 "(architecture %s)",
675 __FUNCTION__, file.GetPath().c_str(),
676 spec_triple.getTriple().c_str(),
677 spec.GetArchitecture().GetArchitectureName());
Todd Fialab91de782014-06-27 16:52:49 +0000678
Kate Stoneb9c1b512016-09-06 20:57:50 +0000679 if (!uuid.IsValid()) {
680 uint32_t core_notes_crc = 0;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000681
Kate Stoneb9c1b512016-09-06 20:57:50 +0000682 if (!gnu_debuglink_crc) {
683 lldb_private::Timer scoped_timer(
684 LLVM_PRETTY_FUNCTION,
685 "Calculating module crc32 %s with size %" PRIu64 " KiB",
686 file.GetLastPathComponent().AsCString(),
687 (file.GetByteSize() - file_offset) / 1024);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000688
Kate Stoneb9c1b512016-09-06 20:57:50 +0000689 // For core files - which usually don't happen to have a
690 // gnu_debuglink,
691 // and are pretty bulky - calculating whole contents crc32 would
692 // be too much of luxury.
693 // Thus we will need to fallback to something simpler.
694 if (header.e_type == llvm::ELF::ET_CORE) {
695 size_t program_headers_end =
696 header.e_phoff + header.e_phnum * header.e_phentsize;
697 if (program_headers_end > data_sp->GetByteSize()) {
698 data_sp = file.MemoryMapFileContentsIfLocal(
699 file_offset, program_headers_end);
700 data.SetData(data_sp);
Michael Sartain9f0013d2013-05-17 00:20:21 +0000701 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 ProgramHeaderColl program_headers;
703 GetProgramHeaderInfo(program_headers, set_data, header);
Michael Sartainc836ae72013-05-23 20:57:03 +0000704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 size_t segment_data_end = 0;
706 for (ProgramHeaderCollConstIter I = program_headers.begin();
707 I != program_headers.end(); ++I) {
708 segment_data_end = std::max<unsigned long long>(
709 I->p_offset + I->p_filesz, segment_data_end);
710 }
711
712 if (segment_data_end > data_sp->GetByteSize()) {
713 data_sp = file.MemoryMapFileContentsIfLocal(file_offset,
714 segment_data_end);
715 data.SetData(data_sp);
716 }
717
718 core_notes_crc =
719 CalculateELFNotesSegmentsCRC32(program_headers, data);
720 } else {
721 // Need to map entire file into memory to calculate the crc.
722 data_sp =
723 file.MemoryMapFileContentsIfLocal(file_offset, SIZE_MAX);
724 data.SetData(data_sp);
725 gnu_debuglink_crc = calc_gnu_debuglink_crc32(
726 data.GetDataStart(), data.GetByteSize());
727 }
728 }
729 if (gnu_debuglink_crc) {
730 // Use 4 bytes of crc from the .gnu_debuglink section.
731 uint32_t uuidt[4] = {gnu_debuglink_crc, 0, 0, 0};
732 uuid.SetBytes(uuidt, sizeof(uuidt));
733 } else if (core_notes_crc) {
734 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
735 // it look different form
736 // .gnu_debuglink crc followed by 4 bytes of note segments crc.
737 uint32_t uuidt[4] = {g_core_uuid_magic, core_notes_crc, 0, 0};
738 uuid.SetBytes(uuidt, sizeof(uuidt));
739 }
740 }
741
742 specs.Append(spec);
743 }
744 }
745 }
746 }
747
748 return specs.GetSize() - initial_count;
Greg Claytonf4d6de62013-04-24 22:29:28 +0000749}
750
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000751//------------------------------------------------------------------
752// PluginInterface protocol
753//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000754lldb_private::ConstString ObjectFileELF::GetPluginName() {
755 return GetPluginNameStatic();
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000756}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000757
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758uint32_t ObjectFileELF::GetPluginVersion() { return m_plugin_version; }
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000759//------------------------------------------------------------------
760// ObjectFile protocol
761//------------------------------------------------------------------
762
Kate Stoneb9c1b512016-09-06 20:57:50 +0000763ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
764 DataBufferSP &data_sp, lldb::offset_t data_offset,
765 const FileSpec *file, lldb::offset_t file_offset,
766 lldb::offset_t length)
767 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
768 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
769 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
770 m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
771 if (file)
772 m_file = *file;
773 ::memset(&m_header, 0, sizeof(m_header));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000774}
775
Kate Stoneb9c1b512016-09-06 20:57:50 +0000776ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
777 DataBufferSP &header_data_sp,
778 const lldb::ProcessSP &process_sp,
779 addr_t header_addr)
780 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
781 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
782 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
783 m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
784 ::memset(&m_header, 0, sizeof(m_header));
Andrew MacPherson17220c12014-03-05 10:12:43 +0000785}
786
Kate Stoneb9c1b512016-09-06 20:57:50 +0000787ObjectFileELF::~ObjectFileELF() {}
788
789bool ObjectFileELF::IsExecutable() const {
790 return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000791}
792
Kate Stoneb9c1b512016-09-06 20:57:50 +0000793bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
794 bool value_is_offset) {
795 ModuleSP module_sp = GetModule();
796 if (module_sp) {
797 size_t num_loaded_sections = 0;
798 SectionList *section_list = GetSectionList();
799 if (section_list) {
800 if (!value_is_offset) {
801 bool found_offset = false;
802 for (size_t i = 0, count = GetProgramHeaderCount(); i < count; ++i) {
803 const elf::ELFProgramHeader *header = GetProgramHeaderByIndex(i);
804 if (header == nullptr)
805 continue;
Jim Ingham5aee1622010-08-09 23:31:02 +0000806
Kate Stoneb9c1b512016-09-06 20:57:50 +0000807 if (header->p_type != PT_LOAD || header->p_offset != 0)
808 continue;
Tamas Berghammerf2561842015-06-30 10:41:23 +0000809
Kate Stoneb9c1b512016-09-06 20:57:50 +0000810 value = value - header->p_vaddr;
811 found_offset = true;
812 break;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000813 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 if (!found_offset)
815 return false;
816 }
817
818 const size_t num_sections = section_list->GetSize();
819 size_t sect_idx = 0;
820
821 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
822 // Iterate through the object file sections to find all
823 // of the sections that have SHF_ALLOC in their flag bits.
824 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
825 if (section_sp && section_sp->Test(SHF_ALLOC)) {
826 lldb::addr_t load_addr = section_sp->GetFileAddress();
827 // We don't want to update the load address of a section with type
828 // eSectionTypeAbsoluteAddress as they already have the absolute load
829 // address
830 // already specified
831 if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
832 load_addr += value;
833
834 // On 32-bit systems the load address have to fit into 4 bytes. The
835 // rest of
836 // the bytes are the overflow from the addition.
837 if (GetAddressByteSize() == 4)
838 load_addr &= 0xFFFFFFFF;
839
840 if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
841 load_addr))
842 ++num_loaded_sections;
843 }
844 }
845 return num_loaded_sections > 0;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000846 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000847 }
848 return false;
849}
850
851ByteOrder ObjectFileELF::GetByteOrder() const {
852 if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
853 return eByteOrderBig;
854 if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
855 return eByteOrderLittle;
856 return eByteOrderInvalid;
857}
858
859uint32_t ObjectFileELF::GetAddressByteSize() const {
860 return m_data.GetAddressByteSize();
861}
862
863AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
864 Symtab *symtab = GetSymtab();
865 if (!symtab)
866 return eAddressClassUnknown;
867
868 // The address class is determined based on the symtab. Ask it from the object
869 // file what
870 // contains the symtab information.
871 ObjectFile *symtab_objfile = symtab->GetObjectFile();
872 if (symtab_objfile != nullptr && symtab_objfile != this)
873 return symtab_objfile->GetAddressClass(file_addr);
874
875 auto res = ObjectFile::GetAddressClass(file_addr);
876 if (res != eAddressClassCode)
877 return res;
878
879 auto ub = m_address_class_map.upper_bound(file_addr);
880 if (ub == m_address_class_map.begin()) {
881 // No entry in the address class map before the address. Return
882 // default address class for an address in a code section.
883 return eAddressClassCode;
884 }
885
886 // Move iterator to the address class entry preceding address
887 --ub;
888
889 return ub->second;
890}
891
892size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
893 return std::distance(m_section_headers.begin(), I) + 1u;
894}
895
896size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
897 return std::distance(m_section_headers.begin(), I) + 1u;
898}
899
900bool ObjectFileELF::ParseHeader() {
901 lldb::offset_t offset = 0;
902 if (!m_header.Parse(m_data, &offset))
Tamas Berghammer42ecef32015-08-24 10:21:55 +0000903 return false;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000904
Kate Stoneb9c1b512016-09-06 20:57:50 +0000905 if (!IsInMemory())
Tamas Berghammerf2561842015-06-30 10:41:23 +0000906 return true;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907
908 // For in memory object files m_data might not contain the full object file.
909 // Try to load it
910 // until the end of the "Section header table" what is at the end of the ELF
911 // file.
912 addr_t file_size = m_header.e_shoff + m_header.e_shnum * m_header.e_shentsize;
913 if (m_data.GetByteSize() < file_size) {
914 ProcessSP process_sp(m_process_wp.lock());
915 if (!process_sp)
916 return false;
917
918 DataBufferSP data_sp = ReadMemory(process_sp, m_memory_addr, file_size);
919 if (!data_sp)
920 return false;
921 m_data.SetData(data_sp, 0, file_size);
922 }
923
924 return true;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000925}
926
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927bool ObjectFileELF::GetUUID(lldb_private::UUID *uuid) {
928 // Need to parse the section list to get the UUIDs, so make sure that's been
929 // done.
930 if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000931 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000932
933 if (m_uuid.IsValid()) {
934 // We have the full build id uuid.
935 *uuid = m_uuid;
936 return true;
937 } else if (GetType() == ObjectFile::eTypeCoreFile) {
938 uint32_t core_notes_crc = 0;
939
940 if (!ParseProgramHeaders())
941 return false;
942
943 core_notes_crc = CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
944
945 if (core_notes_crc) {
946 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
947 // look different form .gnu_debuglink crc - followed by 4 bytes of note
948 // segments crc.
949 uint32_t uuidt[4] = {g_core_uuid_magic, core_notes_crc, 0, 0};
950 m_uuid.SetBytes(uuidt, sizeof(uuidt));
951 }
952 } else {
953 if (!m_gnu_debuglink_crc)
954 m_gnu_debuglink_crc =
955 calc_gnu_debuglink_crc32(m_data.GetDataStart(), m_data.GetByteSize());
956 if (m_gnu_debuglink_crc) {
957 // Use 4 bytes of crc from the .gnu_debuglink section.
958 uint32_t uuidt[4] = {m_gnu_debuglink_crc, 0, 0, 0};
959 m_uuid.SetBytes(uuidt, sizeof(uuidt));
960 }
961 }
962
963 if (m_uuid.IsValid()) {
964 *uuid = m_uuid;
965 return true;
966 }
967
968 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000969}
970
Kate Stoneb9c1b512016-09-06 20:57:50 +0000971lldb_private::FileSpecList ObjectFileELF::GetDebugSymbolFilePaths() {
972 FileSpecList file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000973
Kate Stoneb9c1b512016-09-06 20:57:50 +0000974 if (!m_gnu_debuglink_file.empty()) {
Malcolm Parsons771ef6d2016-11-02 20:34:10 +0000975 FileSpec file_spec(m_gnu_debuglink_file, false);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000976 file_spec_list.Append(file_spec);
977 }
978 return file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000979}
980
Kate Stoneb9c1b512016-09-06 20:57:50 +0000981uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
982 size_t num_modules = ParseDependentModules();
983 uint32_t num_specs = 0;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000984
Kate Stoneb9c1b512016-09-06 20:57:50 +0000985 for (unsigned i = 0; i < num_modules; ++i) {
986 if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
987 num_specs++;
988 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000989
Kate Stoneb9c1b512016-09-06 20:57:50 +0000990 return num_specs;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000991}
992
Kate Stoneb9c1b512016-09-06 20:57:50 +0000993Address ObjectFileELF::GetImageInfoAddress(Target *target) {
994 if (!ParseDynamicSymbols())
Stephen Wilson2ab0a582011-01-15 00:08:44 +0000995 return Address();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000996
997 SectionList *section_list = GetSectionList();
998 if (!section_list)
999 return Address();
1000
1001 // Find the SHT_DYNAMIC (.dynamic) section.
1002 SectionSP dynsym_section_sp(
1003 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
1004 if (!dynsym_section_sp)
1005 return Address();
1006 assert(dynsym_section_sp->GetObjectFile() == this);
1007
1008 user_id_t dynsym_id = dynsym_section_sp->GetID();
1009 const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
1010 if (!dynsym_hdr)
1011 return Address();
1012
1013 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
1014 ELFDynamic &symbol = m_dynamic_symbols[i];
1015
1016 if (symbol.d_tag == DT_DEBUG) {
1017 // Compute the offset as the number of previous entries plus the
1018 // size of d_tag.
1019 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
1020 return Address(dynsym_section_sp, offset);
1021 }
1022 // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
1023 // exists in non-PIE.
1024 else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
1025 symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
1026 target) {
1027 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
1028 addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
1029 if (dyn_base == LLDB_INVALID_ADDRESS)
1030 return Address();
1031
1032 Error error;
1033 if (symbol.d_tag == DT_MIPS_RLD_MAP) {
1034 // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
1035 Address addr;
1036 if (target->ReadPointerFromMemory(dyn_base + offset, false, error,
1037 addr))
1038 return addr;
1039 }
1040 if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
1041 // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
1042 // relative to the address of the tag.
1043 uint64_t rel_offset;
1044 rel_offset = target->ReadUnsignedIntegerFromMemory(
1045 dyn_base + offset, false, GetAddressByteSize(), UINT64_MAX, error);
1046 if (error.Success() && rel_offset != UINT64_MAX) {
1047 Address addr;
1048 addr_t debug_ptr_address =
1049 dyn_base + (offset - GetAddressByteSize()) + rel_offset;
1050 addr.SetOffset(debug_ptr_address);
1051 return addr;
1052 }
1053 }
1054 }
1055 }
1056
1057 return Address();
Stephen Wilson2ab0a582011-01-15 00:08:44 +00001058}
1059
Kate Stoneb9c1b512016-09-06 20:57:50 +00001060lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
1061 if (m_entry_point_address.IsValid())
Stephen Wilsond126c8c2011-03-08 04:12:15 +00001062 return m_entry_point_address;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001063
1064 if (!ParseHeader() || !IsExecutable())
1065 return m_entry_point_address;
1066
1067 SectionList *section_list = GetSectionList();
1068 addr_t offset = m_header.e_entry;
1069
1070 if (!section_list)
1071 m_entry_point_address.SetOffset(offset);
1072 else
1073 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
1074 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00001075}
1076
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001077//----------------------------------------------------------------------
1078// ParseDependentModules
1079//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001080size_t ObjectFileELF::ParseDependentModules() {
1081 if (m_filespec_ap.get())
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001082 return m_filespec_ap->GetSize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083
1084 m_filespec_ap.reset(new FileSpecList());
1085
1086 if (!ParseSectionHeaders())
1087 return 0;
1088
1089 SectionList *section_list = GetSectionList();
1090 if (!section_list)
1091 return 0;
1092
1093 // Find the SHT_DYNAMIC section.
1094 Section *dynsym =
1095 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
1096 .get();
1097 if (!dynsym)
1098 return 0;
1099 assert(dynsym->GetObjectFile() == this);
1100
1101 const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
1102 if (!header)
1103 return 0;
1104 // sh_link: section header index of string table used by entries in the
1105 // section.
1106 Section *dynstr = section_list->FindSectionByID(header->sh_link + 1).get();
1107 if (!dynstr)
1108 return 0;
1109
1110 DataExtractor dynsym_data;
1111 DataExtractor dynstr_data;
1112 if (ReadSectionData(dynsym, dynsym_data) &&
1113 ReadSectionData(dynstr, dynstr_data)) {
1114 ELFDynamic symbol;
1115 const lldb::offset_t section_size = dynsym_data.GetByteSize();
1116 lldb::offset_t offset = 0;
1117
1118 // The only type of entries we are concerned with are tagged DT_NEEDED,
1119 // yielding the name of a required library.
1120 while (offset < section_size) {
1121 if (!symbol.Parse(dynsym_data, &offset))
1122 break;
1123
1124 if (symbol.d_tag != DT_NEEDED)
1125 continue;
1126
1127 uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
1128 const char *lib_name = dynstr_data.PeekCStr(str_index);
1129 m_filespec_ap->Append(FileSpec(lib_name, true));
1130 }
1131 }
1132
1133 return m_filespec_ap->GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001134}
1135
1136//----------------------------------------------------------------------
Todd Fiala4339f3a2014-03-25 19:29:09 +00001137// GetProgramHeaderInfo
1138//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001139size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
1140 const SetDataFunction &set_data,
1141 const ELFHeader &header) {
1142 // We have already parsed the program headers
1143 if (!program_headers.empty())
Todd Fiala4339f3a2014-03-25 19:29:09 +00001144 return program_headers.size();
1145
Kate Stoneb9c1b512016-09-06 20:57:50 +00001146 // If there are no program headers to read we are done.
1147 if (header.e_phnum == 0)
1148 return 0;
1149
1150 program_headers.resize(header.e_phnum);
1151 if (program_headers.size() != header.e_phnum)
1152 return 0;
1153
1154 const size_t ph_size = header.e_phnum * header.e_phentsize;
1155 const elf_off ph_offset = header.e_phoff;
1156 DataExtractor data;
1157 if (set_data(data, ph_offset, ph_size) != ph_size)
1158 return 0;
1159
1160 uint32_t idx;
1161 lldb::offset_t offset;
1162 for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
1163 if (program_headers[idx].Parse(data, &offset) == false)
1164 break;
1165 }
1166
1167 if (idx < program_headers.size())
1168 program_headers.resize(idx);
1169
1170 return program_headers.size();
Todd Fiala4339f3a2014-03-25 19:29:09 +00001171}
1172
1173//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001174// ParseProgramHeaders
1175//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176size_t ObjectFileELF::ParseProgramHeaders() {
1177 using namespace std::placeholders;
1178 return GetProgramHeaderInfo(
1179 m_program_headers,
1180 std::bind(&ObjectFileELF::SetDataWithReadMemoryFallback, this, _1, _2,
1181 _3),
1182 m_header);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001183}
1184
Todd Fialab91de782014-06-27 16:52:49 +00001185lldb_private::Error
Kate Stoneb9c1b512016-09-06 20:57:50 +00001186ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
1187 lldb_private::ArchSpec &arch_spec,
1188 lldb_private::UUID &uuid) {
1189 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1190 Error error;
Todd Fialab91de782014-06-27 16:52:49 +00001191
Kate Stoneb9c1b512016-09-06 20:57:50 +00001192 lldb::offset_t offset = 0;
Michael Sartainc836ae72013-05-23 20:57:03 +00001193
Kate Stoneb9c1b512016-09-06 20:57:50 +00001194 while (true) {
1195 // Parse the note header. If this fails, bail out.
1196 const lldb::offset_t note_offset = offset;
1197 ELFNote note = ELFNote();
1198 if (!note.Parse(data, &offset)) {
1199 // We're done.
1200 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001201 }
Todd Fialab91de782014-06-27 16:52:49 +00001202
Kate Stoneb9c1b512016-09-06 20:57:50 +00001203 if (log)
1204 log->Printf("ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1205 __FUNCTION__, note.n_name.c_str(), note.n_type);
1206
1207 // Process FreeBSD ELF notes.
1208 if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1209 (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
1210 (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
1211 // Pull out the min version info.
1212 uint32_t version_info;
1213 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1214 error.SetErrorString("failed to read FreeBSD ABI note payload");
1215 return error;
1216 }
1217
1218 // Convert the version info into a major/minor number.
1219 const uint32_t version_major = version_info / 100000;
1220 const uint32_t version_minor = (version_info / 1000) % 100;
1221
1222 char os_name[32];
1223 snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1224 version_major, version_minor);
1225
1226 // Set the elf OS version to FreeBSD. Also clear the vendor.
1227 arch_spec.GetTriple().setOSName(os_name);
1228 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1229
1230 if (log)
1231 log->Printf("ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1232 ".%" PRIu32,
1233 __FUNCTION__, version_major, version_minor,
1234 static_cast<uint32_t>(version_info % 1000));
1235 }
1236 // Process GNU ELF notes.
1237 else if (note.n_name == LLDB_NT_OWNER_GNU) {
1238 switch (note.n_type) {
1239 case LLDB_NT_GNU_ABI_TAG:
1240 if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1241 // Pull out the min OS version supporting the ABI.
1242 uint32_t version_info[4];
1243 if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1244 nullptr) {
1245 error.SetErrorString("failed to read GNU ABI note payload");
1246 return error;
1247 }
1248
1249 // Set the OS per the OS field.
1250 switch (version_info[0]) {
1251 case LLDB_NT_GNU_ABI_OS_LINUX:
1252 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1253 arch_spec.GetTriple().setVendor(
1254 llvm::Triple::VendorType::UnknownVendor);
1255 if (log)
1256 log->Printf(
1257 "ObjectFileELF::%s detected Linux, min version %" PRIu32
1258 ".%" PRIu32 ".%" PRIu32,
1259 __FUNCTION__, version_info[1], version_info[2],
1260 version_info[3]);
1261 // FIXME we have the minimal version number, we could be propagating
1262 // that. version_info[1] = OS Major, version_info[2] = OS Minor,
1263 // version_info[3] = Revision.
1264 break;
1265 case LLDB_NT_GNU_ABI_OS_HURD:
1266 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1267 arch_spec.GetTriple().setVendor(
1268 llvm::Triple::VendorType::UnknownVendor);
1269 if (log)
1270 log->Printf("ObjectFileELF::%s detected Hurd (unsupported), min "
1271 "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1272 __FUNCTION__, version_info[1], version_info[2],
1273 version_info[3]);
1274 break;
1275 case LLDB_NT_GNU_ABI_OS_SOLARIS:
1276 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1277 arch_spec.GetTriple().setVendor(
1278 llvm::Triple::VendorType::UnknownVendor);
1279 if (log)
1280 log->Printf(
1281 "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1282 ".%" PRIu32 ".%" PRIu32,
1283 __FUNCTION__, version_info[1], version_info[2],
1284 version_info[3]);
1285 break;
1286 default:
1287 if (log)
1288 log->Printf(
1289 "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1290 ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1291 __FUNCTION__, version_info[0], version_info[1],
1292 version_info[2], version_info[3]);
1293 break;
1294 }
1295 }
1296 break;
1297
1298 case LLDB_NT_GNU_BUILD_ID_TAG:
1299 // Only bother processing this if we don't already have the uuid set.
1300 if (!uuid.IsValid()) {
1301 // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
1302 // build-id of a different
1303 // length. Accept it as long as it's at least 4 bytes as it will be
1304 // better than our own crc32.
1305 if (note.n_descsz >= 4 && note.n_descsz <= 20) {
1306 uint8_t uuidbuf[20];
1307 if (data.GetU8(&offset, &uuidbuf, note.n_descsz) == nullptr) {
1308 error.SetErrorString("failed to read GNU_BUILD_ID note payload");
1309 return error;
1310 }
1311
1312 // Save the build id as the UUID for the module.
1313 uuid.SetBytes(uuidbuf, note.n_descsz);
1314 }
1315 }
1316 break;
1317 }
1318 }
1319 // Process NetBSD ELF notes.
1320 else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
1321 (note.n_type == LLDB_NT_NETBSD_ABI_TAG) &&
1322 (note.n_descsz == LLDB_NT_NETBSD_ABI_SIZE)) {
1323 // Pull out the min version info.
1324 uint32_t version_info;
1325 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1326 error.SetErrorString("failed to read NetBSD ABI note payload");
1327 return error;
1328 }
1329
1330 // Set the elf OS version to NetBSD. Also clear the vendor.
1331 arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
1332 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1333
1334 if (log)
1335 log->Printf(
1336 "ObjectFileELF::%s detected NetBSD, min version constant %" PRIu32,
1337 __FUNCTION__, version_info);
1338 }
1339 // Process CSR kalimba notes
1340 else if ((note.n_type == LLDB_NT_GNU_ABI_TAG) &&
1341 (note.n_name == LLDB_NT_OWNER_CSR)) {
1342 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1343 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::CSR);
1344
1345 // TODO At some point the description string could be processed.
1346 // It could provide a steer towards the kalimba variant which
1347 // this ELF targets.
1348 if (note.n_descsz) {
1349 const char *cstr =
1350 data.GetCStr(&offset, llvm::alignTo(note.n_descsz, 4));
1351 (void)cstr;
1352 }
1353 } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1354 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1355 arch_spec.GetTriple().setEnvironment(
1356 llvm::Triple::EnvironmentType::Android);
1357 } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1358 // This is sometimes found in core files and usually contains extended
1359 // register info
1360 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1361 } else if (note.n_name == LLDB_NT_OWNER_CORE) {
1362 // Parse the NT_FILE to look for stuff in paths to shared libraries
1363 // As the contents look like this in a 64 bit ELF core file:
1364 // count = 0x000000000000000a (10)
1365 // page_size = 0x0000000000001000 (4096)
1366 // Index start end file_ofs path
1367 // ===== ------------------ ------------------ ------------------
1368 // -------------------------------------
1369 // [ 0] 0x0000000000400000 0x0000000000401000 0x0000000000000000
1370 // /tmp/a.out
1371 // [ 1] 0x0000000000600000 0x0000000000601000 0x0000000000000000
1372 // /tmp/a.out
1373 // [ 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001
1374 // /tmp/a.out
1375 // [ 3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000
1376 // /lib/x86_64-linux-gnu/libc-2.19.so
1377 // [ 4] 0x00007fa79cba8000 0x00007fa79cda7000 0x00000000000001bb
1378 // /lib/x86_64-linux-gnu/libc-2.19.so
1379 // [ 5] 0x00007fa79cda7000 0x00007fa79cdab000 0x00000000000001ba
1380 // /lib/x86_64-linux-gnu/libc-2.19.so
1381 // [ 6] 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be
1382 // /lib/x86_64-linux-gnu/libc-2.19.so
1383 // [ 7] 0x00007fa79cdb2000 0x00007fa79cdd5000 0x0000000000000000
1384 // /lib/x86_64-linux-gnu/ld-2.19.so
1385 // [ 8] 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022
1386 // /lib/x86_64-linux-gnu/ld-2.19.so
1387 // [ 9] 0x00007fa79cfd5000 0x00007fa79cfd6000 0x0000000000000023
1388 // /lib/x86_64-linux-gnu/ld-2.19.so
1389 // In the 32 bit ELFs the count, page_size, start, end, file_ofs are
1390 // uint32_t
1391 // For reference: see readelf source code (in binutils).
1392 if (note.n_type == NT_FILE) {
1393 uint64_t count = data.GetAddress(&offset);
1394 const char *cstr;
1395 data.GetAddress(&offset); // Skip page size
1396 offset += count * 3 *
1397 data.GetAddressByteSize(); // Skip all start/end/file_ofs
1398 for (size_t i = 0; i < count; ++i) {
1399 cstr = data.GetCStr(&offset);
1400 if (cstr == nullptr) {
1401 error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
1402 "at an offset after the end "
1403 "(GetCStr returned nullptr)",
1404 __FUNCTION__);
1405 return error;
1406 }
1407 llvm::StringRef path(cstr);
Richard Chamberlaina0c82e12016-10-13 12:11:00 +00001408 if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001409 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1410 break;
1411 }
1412 }
1413 }
1414 }
1415
1416 // Calculate the offset of the next note just in case "offset" has been used
1417 // to poke at the contents of the note data
1418 offset = note_offset + note.GetByteSize();
1419 }
1420
1421 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001422}
Michael Sartaina7499c92013-07-01 19:45:50 +00001423
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
1425 ArchSpec &arch_spec) {
1426 lldb::offset_t Offset = 0;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001427
Kate Stoneb9c1b512016-09-06 20:57:50 +00001428 uint8_t FormatVersion = data.GetU8(&Offset);
1429 if (FormatVersion != llvm::ARMBuildAttrs::Format_Version)
1430 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001431
Kate Stoneb9c1b512016-09-06 20:57:50 +00001432 Offset = Offset + sizeof(uint32_t); // Section Length
1433 llvm::StringRef VendorName = data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001434
Kate Stoneb9c1b512016-09-06 20:57:50 +00001435 if (VendorName != "aeabi")
1436 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001437
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 if (arch_spec.GetTriple().getEnvironment() ==
1439 llvm::Triple::UnknownEnvironment)
1440 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001441
Kate Stoneb9c1b512016-09-06 20:57:50 +00001442 while (Offset < length) {
1443 uint8_t Tag = data.GetU8(&Offset);
1444 uint32_t Size = data.GetU32(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001445
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1447 continue;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001448
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 while (Offset < length) {
1450 uint64_t Tag = data.GetULEB128(&Offset);
1451 switch (Tag) {
1452 default:
1453 if (Tag < 32)
1454 data.GetULEB128(&Offset);
1455 else if (Tag % 2 == 0)
1456 data.GetULEB128(&Offset);
1457 else
1458 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001459
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001461
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462 case llvm::ARMBuildAttrs::CPU_raw_name:
1463 case llvm::ARMBuildAttrs::CPU_name:
1464 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001465
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001467
Kate Stoneb9c1b512016-09-06 20:57:50 +00001468 case llvm::ARMBuildAttrs::ABI_VFP_args: {
1469 uint64_t VFPArgs = data.GetULEB128(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001470
Kate Stoneb9c1b512016-09-06 20:57:50 +00001471 if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1472 if (arch_spec.GetTriple().getEnvironment() ==
1473 llvm::Triple::UnknownEnvironment ||
1474 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1475 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001476
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1478 } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1479 if (arch_spec.GetTriple().getEnvironment() ==
1480 llvm::Triple::UnknownEnvironment ||
1481 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1482 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001483
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001485 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486
1487 break;
1488 }
1489 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001490 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001491 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001492}
Todd Fialab91de782014-06-27 16:52:49 +00001493
Michael Sartaina7499c92013-07-01 19:45:50 +00001494//----------------------------------------------------------------------
1495// GetSectionHeaderInfo
1496//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
1498 const SetDataFunction &set_data,
1499 const elf::ELFHeader &header,
1500 lldb_private::UUID &uuid,
1501 std::string &gnu_debuglink_file,
1502 uint32_t &gnu_debuglink_crc,
1503 ArchSpec &arch_spec) {
1504 // Don't reparse the section headers if we already did that.
1505 if (!section_headers.empty())
1506 return section_headers.size();
Todd Fiala6477ea82014-07-11 15:13:33 +00001507
Kate Stoneb9c1b512016-09-06 20:57:50 +00001508 // Only initialize the arch_spec to okay defaults if they're not already set.
1509 // We'll refine this with note data as we parse the notes.
1510 if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1511 llvm::Triple::OSType ostype;
1512 llvm::Triple::OSType spec_ostype;
1513 const uint32_t sub_type = subTypeFromElfHeader(header);
1514 arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1515 header.e_ident[EI_OSABI]);
1516 //
1517 // Validate if it is ok to remove GetOsFromOSABI
1518 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1519 spec_ostype = arch_spec.GetTriple().getOS();
1520 assert(spec_ostype == ostype);
1521 }
1522
1523 if (arch_spec.GetMachine() == llvm::Triple::mips ||
1524 arch_spec.GetMachine() == llvm::Triple::mipsel ||
1525 arch_spec.GetMachine() == llvm::Triple::mips64 ||
1526 arch_spec.GetMachine() == llvm::Triple::mips64el) {
1527 switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1528 case llvm::ELF::EF_MIPS_MICROMIPS:
1529 arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
1530 break;
1531 case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1532 arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
1533 break;
1534 case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1535 arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
1536 break;
1537 default:
1538 break;
Todd Fialab91de782014-06-27 16:52:49 +00001539 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001540 }
Todd Fialab91de782014-06-27 16:52:49 +00001541
Kate Stoneb9c1b512016-09-06 20:57:50 +00001542 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1543 arch_spec.GetMachine() == llvm::Triple::thumb) {
1544 if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1545 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1546 else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1547 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1548 }
Jaydeep Patil501a7812015-07-16 03:51:55 +00001549
Kate Stoneb9c1b512016-09-06 20:57:50 +00001550 // If there are no section headers we are done.
1551 if (header.e_shnum == 0)
Michael Sartaina7499c92013-07-01 19:45:50 +00001552 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001553
1554 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1555
1556 section_headers.resize(header.e_shnum);
1557 if (section_headers.size() != header.e_shnum)
1558 return 0;
1559
1560 const size_t sh_size = header.e_shnum * header.e_shentsize;
1561 const elf_off sh_offset = header.e_shoff;
1562 DataExtractor sh_data;
1563 if (set_data(sh_data, sh_offset, sh_size) != sh_size)
1564 return 0;
1565
1566 uint32_t idx;
1567 lldb::offset_t offset;
1568 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
1569 if (section_headers[idx].Parse(sh_data, &offset) == false)
1570 break;
1571 }
1572 if (idx < section_headers.size())
1573 section_headers.resize(idx);
1574
1575 const unsigned strtab_idx = header.e_shstrndx;
1576 if (strtab_idx && strtab_idx < section_headers.size()) {
1577 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1578 const size_t byte_size = sheader.sh_size;
1579 const Elf64_Off offset = sheader.sh_offset;
1580 lldb_private::DataExtractor shstr_data;
1581
1582 if (set_data(shstr_data, offset, byte_size) == byte_size) {
1583 for (SectionHeaderCollIter I = section_headers.begin();
1584 I != section_headers.end(); ++I) {
1585 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1586 const ELFSectionHeaderInfo &sheader = *I;
1587 const uint64_t section_size =
1588 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1589 ConstString name(shstr_data.PeekCStr(I->sh_name));
1590
1591 I->section_name = name;
1592
1593 if (arch_spec.IsMIPS()) {
1594 uint32_t arch_flags = arch_spec.GetFlags();
1595 DataExtractor data;
1596 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1597
1598 if (section_size && (set_data(data, sheader.sh_offset,
1599 section_size) == section_size)) {
1600 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1601 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1602 arch_flags |= data.GetU32(&offset);
1603
1604 // The floating point ABI is at offset 7
1605 offset = 7;
1606 switch (data.GetU8(&offset)) {
1607 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1608 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
1609 break;
1610 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1611 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
1612 break;
1613 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1614 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
1615 break;
1616 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1617 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
1618 break;
1619 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1620 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
1621 break;
1622 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1623 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
1624 break;
1625 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1626 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
1627 break;
1628 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1629 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
1630 break;
1631 }
1632 }
1633 }
1634 // Settings appropriate ArchSpec ABI Flags
1635 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1636 case llvm::ELF::EF_MIPS_ABI_O32:
1637 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
1638 break;
1639 case EF_MIPS_ABI_O64:
1640 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
1641 break;
1642 case EF_MIPS_ABI_EABI32:
1643 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
1644 break;
1645 case EF_MIPS_ABI_EABI64:
1646 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
1647 break;
1648 default:
1649 // ABI Mask doesn't cover N32 and N64 ABI.
1650 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1651 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
1652 else if (header.e_flags && llvm::ELF::EF_MIPS_ABI2)
1653 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
1654 break;
1655 }
1656 arch_spec.SetFlags(arch_flags);
1657 }
1658
1659 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1660 arch_spec.GetMachine() == llvm::Triple::thumb) {
1661 DataExtractor data;
1662
1663 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
1664 set_data(data, sheader.sh_offset, section_size) == section_size)
1665 ParseARMAttributes(data, section_size, arch_spec);
1666 }
1667
1668 if (name == g_sect_name_gnu_debuglink) {
1669 DataExtractor data;
1670 if (section_size && (set_data(data, sheader.sh_offset,
1671 section_size) == section_size)) {
1672 lldb::offset_t gnu_debuglink_offset = 0;
1673 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1674 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1675 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1676 }
1677 }
1678
1679 // Process ELF note section entries.
1680 bool is_note_header = (sheader.sh_type == SHT_NOTE);
1681
1682 // The section header ".note.android.ident" is stored as a
1683 // PROGBITS type header but it is actually a note header.
1684 static ConstString g_sect_name_android_ident(".note.android.ident");
1685 if (!is_note_header && name == g_sect_name_android_ident)
1686 is_note_header = true;
1687
1688 if (is_note_header) {
1689 // Allow notes to refine module info.
1690 DataExtractor data;
1691 if (section_size && (set_data(data, sheader.sh_offset,
1692 section_size) == section_size)) {
1693 Error error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
1694 if (error.Fail()) {
1695 if (log)
1696 log->Printf("ObjectFileELF::%s ELF note processing failed: %s",
1697 __FUNCTION__, error.AsCString());
1698 }
1699 }
1700 }
1701 }
1702
1703 // Make any unknown triple components to be unspecified unknowns.
1704 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1705 arch_spec.GetTriple().setVendorName(llvm::StringRef());
1706 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1707 arch_spec.GetTriple().setOSName(llvm::StringRef());
1708
1709 return section_headers.size();
1710 }
1711 }
1712
1713 section_headers.clear();
1714 return 0;
Michael Sartaina7499c92013-07-01 19:45:50 +00001715}
1716
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717size_t ObjectFileELF::GetProgramHeaderCount() { return ParseProgramHeaders(); }
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001718
1719const elf::ELFProgramHeader *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720ObjectFileELF::GetProgramHeaderByIndex(lldb::user_id_t id) {
1721 if (!id || !ParseProgramHeaders())
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001722 return NULL;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001723
1724 if (--id < m_program_headers.size())
1725 return &m_program_headers[id];
1726
1727 return NULL;
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001728}
1729
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730DataExtractor ObjectFileELF::GetSegmentDataByIndex(lldb::user_id_t id) {
1731 const elf::ELFProgramHeader *segment_header = GetProgramHeaderByIndex(id);
1732 if (segment_header == NULL)
1733 return DataExtractor();
1734 return DataExtractor(m_data, segment_header->p_offset,
1735 segment_header->p_filesz);
Ashok Thirumurthi4822d922013-07-11 20:39:00 +00001736}
1737
Pavel Labathc6ae7ea2015-03-04 10:25:22 +00001738std::string
Kate Stoneb9c1b512016-09-06 20:57:50 +00001739ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1740 size_t pos = symbol_name.find('@');
1741 return symbol_name.substr(0, pos).str();
Pavel Labathc6ae7ea2015-03-04 10:25:22 +00001742}
1743
Michael Sartaina7499c92013-07-01 19:45:50 +00001744//----------------------------------------------------------------------
1745// ParseSectionHeaders
1746//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747size_t ObjectFileELF::ParseSectionHeaders() {
1748 using namespace std::placeholders;
Ravitheja Addepally15f89c42016-01-19 12:55:21 +00001749
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 return GetSectionHeaderInfo(
1751 m_section_headers,
1752 std::bind(&ObjectFileELF::SetDataWithReadMemoryFallback, this, _1, _2,
1753 _3),
1754 m_header, m_uuid, m_gnu_debuglink_file, m_gnu_debuglink_crc, m_arch_spec);
1755}
1756
1757lldb::offset_t ObjectFileELF::SetData(const lldb_private::DataExtractor &src,
1758 lldb_private::DataExtractor &dst,
1759 lldb::offset_t offset,
1760 lldb::offset_t length) {
1761 return dst.SetData(src, offset, length);
Ravitheja Addepally15f89c42016-01-19 12:55:21 +00001762}
1763
1764lldb::offset_t
Kate Stoneb9c1b512016-09-06 20:57:50 +00001765ObjectFileELF::SetDataWithReadMemoryFallback(lldb_private::DataExtractor &dst,
1766 lldb::offset_t offset,
1767 lldb::offset_t length) {
1768 if (offset + length <= m_data.GetByteSize())
Ravitheja Addepally15f89c42016-01-19 12:55:21 +00001769 return dst.SetData(m_data, offset, length);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001770
1771 const auto process_sp = m_process_wp.lock();
1772 if (process_sp != nullptr) {
1773 addr_t file_size = offset + length;
1774
1775 DataBufferSP data_sp = ReadMemory(process_sp, m_memory_addr, file_size);
1776 if (!data_sp)
1777 return false;
1778 m_data.SetData(data_sp, 0, file_size);
1779 }
1780
1781 return dst.SetData(m_data, offset, length);
Michael Sartaina7499c92013-07-01 19:45:50 +00001782}
1783
Michael Sartaina7499c92013-07-01 19:45:50 +00001784const ObjectFileELF::ELFSectionHeaderInfo *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001785ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
1786 if (!id || !ParseSectionHeaders())
Michael Sartaina7499c92013-07-01 19:45:50 +00001787 return NULL;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001788
1789 if (--id < m_section_headers.size())
1790 return &m_section_headers[id];
1791
1792 return NULL;
Michael Sartaina7499c92013-07-01 19:45:50 +00001793}
1794
Kate Stoneb9c1b512016-09-06 20:57:50 +00001795lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
1796 if (!name || !name[0] || !ParseSectionHeaders())
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001797 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001798 for (size_t i = 1; i < m_section_headers.size(); ++i)
1799 if (m_section_headers[i].section_name == ConstString(name))
1800 return i;
1801 return 0;
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001802}
1803
Kate Stoneb9c1b512016-09-06 20:57:50 +00001804void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
1805 if (!m_sections_ap.get() && ParseSectionHeaders()) {
1806 m_sections_ap.reset(new SectionList());
Andrew MacPherson17220c12014-03-05 10:12:43 +00001807
1808 for (SectionHeaderCollIter I = m_section_headers.begin();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001809 I != m_section_headers.end(); ++I) {
1810 const ELFSectionHeaderInfo &header = *I;
1811
1812 ConstString &name = I->section_name;
1813 const uint64_t file_size =
1814 header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
1815 const uint64_t vm_size = header.sh_flags & SHF_ALLOC ? header.sh_size : 0;
1816
1817 static ConstString g_sect_name_text(".text");
1818 static ConstString g_sect_name_data(".data");
1819 static ConstString g_sect_name_bss(".bss");
1820 static ConstString g_sect_name_tdata(".tdata");
1821 static ConstString g_sect_name_tbss(".tbss");
1822 static ConstString g_sect_name_dwarf_debug_abbrev(".debug_abbrev");
1823 static ConstString g_sect_name_dwarf_debug_addr(".debug_addr");
1824 static ConstString g_sect_name_dwarf_debug_aranges(".debug_aranges");
1825 static ConstString g_sect_name_dwarf_debug_frame(".debug_frame");
1826 static ConstString g_sect_name_dwarf_debug_info(".debug_info");
1827 static ConstString g_sect_name_dwarf_debug_line(".debug_line");
1828 static ConstString g_sect_name_dwarf_debug_loc(".debug_loc");
1829 static ConstString g_sect_name_dwarf_debug_macinfo(".debug_macinfo");
1830 static ConstString g_sect_name_dwarf_debug_macro(".debug_macro");
1831 static ConstString g_sect_name_dwarf_debug_pubnames(".debug_pubnames");
1832 static ConstString g_sect_name_dwarf_debug_pubtypes(".debug_pubtypes");
1833 static ConstString g_sect_name_dwarf_debug_ranges(".debug_ranges");
1834 static ConstString g_sect_name_dwarf_debug_str(".debug_str");
1835 static ConstString g_sect_name_dwarf_debug_str_offsets(
1836 ".debug_str_offsets");
1837 static ConstString g_sect_name_dwarf_debug_abbrev_dwo(
1838 ".debug_abbrev.dwo");
1839 static ConstString g_sect_name_dwarf_debug_info_dwo(".debug_info.dwo");
1840 static ConstString g_sect_name_dwarf_debug_line_dwo(".debug_line.dwo");
1841 static ConstString g_sect_name_dwarf_debug_macro_dwo(".debug_macro.dwo");
1842 static ConstString g_sect_name_dwarf_debug_loc_dwo(".debug_loc.dwo");
1843 static ConstString g_sect_name_dwarf_debug_str_dwo(".debug_str.dwo");
1844 static ConstString g_sect_name_dwarf_debug_str_offsets_dwo(
1845 ".debug_str_offsets.dwo");
1846 static ConstString g_sect_name_eh_frame(".eh_frame");
1847 static ConstString g_sect_name_arm_exidx(".ARM.exidx");
1848 static ConstString g_sect_name_arm_extab(".ARM.extab");
1849 static ConstString g_sect_name_go_symtab(".gosymtab");
1850
1851 SectionType sect_type = eSectionTypeOther;
1852
1853 bool is_thread_specific = false;
1854
1855 if (name == g_sect_name_text)
1856 sect_type = eSectionTypeCode;
1857 else if (name == g_sect_name_data)
1858 sect_type = eSectionTypeData;
1859 else if (name == g_sect_name_bss)
1860 sect_type = eSectionTypeZeroFill;
1861 else if (name == g_sect_name_tdata) {
1862 sect_type = eSectionTypeData;
1863 is_thread_specific = true;
1864 } else if (name == g_sect_name_tbss) {
1865 sect_type = eSectionTypeZeroFill;
1866 is_thread_specific = true;
1867 }
1868 // .debug_abbrev – Abbreviations used in the .debug_info section
1869 // .debug_aranges – Lookup table for mapping addresses to compilation
1870 // units
1871 // .debug_frame – Call frame information
1872 // .debug_info – The core DWARF information section
1873 // .debug_line – Line number information
1874 // .debug_loc – Location lists used in DW_AT_location attributes
1875 // .debug_macinfo – Macro information
1876 // .debug_pubnames – Lookup table for mapping object and function names to
1877 // compilation units
1878 // .debug_pubtypes – Lookup table for mapping type names to compilation
1879 // units
1880 // .debug_ranges – Address ranges used in DW_AT_ranges attributes
1881 // .debug_str – String table used in .debug_info
1882 // MISSING? .gnu_debugdata - "mini debuginfo / MiniDebugInfo" section,
1883 // http://sourceware.org/gdb/onlinedocs/gdb/MiniDebugInfo.html
1884 // MISSING? .debug-index -
1885 // http://src.chromium.org/viewvc/chrome/trunk/src/build/gdb-add-index?pathrev=144644
1886 // MISSING? .debug_types - Type descriptions from DWARF 4? See
1887 // http://gcc.gnu.org/wiki/DwarfSeparateTypeInfo
1888 else if (name == g_sect_name_dwarf_debug_abbrev)
1889 sect_type = eSectionTypeDWARFDebugAbbrev;
1890 else if (name == g_sect_name_dwarf_debug_addr)
1891 sect_type = eSectionTypeDWARFDebugAddr;
1892 else if (name == g_sect_name_dwarf_debug_aranges)
1893 sect_type = eSectionTypeDWARFDebugAranges;
1894 else if (name == g_sect_name_dwarf_debug_frame)
1895 sect_type = eSectionTypeDWARFDebugFrame;
1896 else if (name == g_sect_name_dwarf_debug_info)
1897 sect_type = eSectionTypeDWARFDebugInfo;
1898 else if (name == g_sect_name_dwarf_debug_line)
1899 sect_type = eSectionTypeDWARFDebugLine;
1900 else if (name == g_sect_name_dwarf_debug_loc)
1901 sect_type = eSectionTypeDWARFDebugLoc;
1902 else if (name == g_sect_name_dwarf_debug_macinfo)
1903 sect_type = eSectionTypeDWARFDebugMacInfo;
1904 else if (name == g_sect_name_dwarf_debug_macro)
1905 sect_type = eSectionTypeDWARFDebugMacro;
1906 else if (name == g_sect_name_dwarf_debug_pubnames)
1907 sect_type = eSectionTypeDWARFDebugPubNames;
1908 else if (name == g_sect_name_dwarf_debug_pubtypes)
1909 sect_type = eSectionTypeDWARFDebugPubTypes;
1910 else if (name == g_sect_name_dwarf_debug_ranges)
1911 sect_type = eSectionTypeDWARFDebugRanges;
1912 else if (name == g_sect_name_dwarf_debug_str)
1913 sect_type = eSectionTypeDWARFDebugStr;
1914 else if (name == g_sect_name_dwarf_debug_str_offsets)
1915 sect_type = eSectionTypeDWARFDebugStrOffsets;
1916 else if (name == g_sect_name_dwarf_debug_abbrev_dwo)
1917 sect_type = eSectionTypeDWARFDebugAbbrev;
1918 else if (name == g_sect_name_dwarf_debug_info_dwo)
1919 sect_type = eSectionTypeDWARFDebugInfo;
1920 else if (name == g_sect_name_dwarf_debug_line_dwo)
1921 sect_type = eSectionTypeDWARFDebugLine;
1922 else if (name == g_sect_name_dwarf_debug_macro_dwo)
1923 sect_type = eSectionTypeDWARFDebugMacro;
1924 else if (name == g_sect_name_dwarf_debug_loc_dwo)
1925 sect_type = eSectionTypeDWARFDebugLoc;
1926 else if (name == g_sect_name_dwarf_debug_str_dwo)
1927 sect_type = eSectionTypeDWARFDebugStr;
1928 else if (name == g_sect_name_dwarf_debug_str_offsets_dwo)
1929 sect_type = eSectionTypeDWARFDebugStrOffsets;
1930 else if (name == g_sect_name_eh_frame)
1931 sect_type = eSectionTypeEHFrame;
1932 else if (name == g_sect_name_arm_exidx)
1933 sect_type = eSectionTypeARMexidx;
1934 else if (name == g_sect_name_arm_extab)
1935 sect_type = eSectionTypeARMextab;
1936 else if (name == g_sect_name_go_symtab)
1937 sect_type = eSectionTypeGoSymtab;
1938
1939 const uint32_t permissions =
Ilia K4f730dc2016-09-12 05:25:33 +00001940 ((header.sh_flags & SHF_ALLOC) ? ePermissionsReadable : 0u) |
1941 ((header.sh_flags & SHF_WRITE) ? ePermissionsWritable : 0u) |
1942 ((header.sh_flags & SHF_EXECINSTR) ? ePermissionsExecutable : 0u);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001943 switch (header.sh_type) {
1944 case SHT_SYMTAB:
1945 assert(sect_type == eSectionTypeOther);
1946 sect_type = eSectionTypeELFSymbolTable;
1947 break;
1948 case SHT_DYNSYM:
1949 assert(sect_type == eSectionTypeOther);
1950 sect_type = eSectionTypeELFDynamicSymbols;
1951 break;
1952 case SHT_RELA:
1953 case SHT_REL:
1954 assert(sect_type == eSectionTypeOther);
1955 sect_type = eSectionTypeELFRelocationEntries;
1956 break;
1957 case SHT_DYNAMIC:
1958 assert(sect_type == eSectionTypeOther);
1959 sect_type = eSectionTypeELFDynamicLinkInfo;
1960 break;
1961 }
1962
1963 if (eSectionTypeOther == sect_type) {
1964 // the kalimba toolchain assumes that ELF section names are free-form.
1965 // It does
1966 // support linkscripts which (can) give rise to various arbitrarily
1967 // named
1968 // sections being "Code" or "Data".
1969 sect_type = kalimbaSectionType(m_header, header);
1970 }
1971
1972 const uint32_t target_bytes_size =
1973 (eSectionTypeData == sect_type || eSectionTypeZeroFill == sect_type)
1974 ? m_arch_spec.GetDataByteSize()
1975 : eSectionTypeCode == sect_type ? m_arch_spec.GetCodeByteSize()
1976 : 1;
1977
1978 elf::elf_xword log2align =
1979 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
1980 SectionSP section_sp(new Section(
1981 GetModule(), // Module to which this section belongs.
1982 this, // ObjectFile to which this section belongs and should read
1983 // section data from.
1984 SectionIndex(I), // Section ID.
1985 name, // Section name.
1986 sect_type, // Section type.
1987 header.sh_addr, // VM address.
1988 vm_size, // VM size in bytes of this section.
1989 header.sh_offset, // Offset of this section in the file.
1990 file_size, // Size of the section as found in the file.
1991 log2align, // Alignment of the section
1992 header.sh_flags, // Flags for this section.
1993 target_bytes_size)); // Number of host bytes per target byte
1994
1995 section_sp->SetPermissions(permissions);
1996 if (is_thread_specific)
1997 section_sp->SetIsThreadSpecific(is_thread_specific);
1998 m_sections_ap->AddSection(section_sp);
Andrew MacPherson17220c12014-03-05 10:12:43 +00001999 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002000 }
2001
2002 if (m_sections_ap.get()) {
2003 if (GetType() == eTypeDebugInfo) {
2004 static const SectionType g_sections[] = {
2005 eSectionTypeDWARFDebugAbbrev, eSectionTypeDWARFDebugAddr,
2006 eSectionTypeDWARFDebugAranges, eSectionTypeDWARFDebugFrame,
2007 eSectionTypeDWARFDebugInfo, eSectionTypeDWARFDebugLine,
2008 eSectionTypeDWARFDebugLoc, eSectionTypeDWARFDebugMacInfo,
2009 eSectionTypeDWARFDebugPubNames, eSectionTypeDWARFDebugPubTypes,
2010 eSectionTypeDWARFDebugRanges, eSectionTypeDWARFDebugStr,
2011 eSectionTypeDWARFDebugStrOffsets, eSectionTypeELFSymbolTable,
2012 };
2013 SectionList *elf_section_list = m_sections_ap.get();
2014 for (size_t idx = 0; idx < sizeof(g_sections) / sizeof(g_sections[0]);
2015 ++idx) {
2016 SectionType section_type = g_sections[idx];
2017 SectionSP section_sp(
2018 elf_section_list->FindSectionByType(section_type, true));
2019 if (section_sp) {
2020 SectionSP module_section_sp(
2021 unified_section_list.FindSectionByType(section_type, true));
2022 if (module_section_sp)
2023 unified_section_list.ReplaceSection(module_section_sp->GetID(),
2024 section_sp);
2025 else
2026 unified_section_list.AddSection(section_sp);
2027 }
2028 }
2029 } else {
2030 unified_section_list = *m_sections_ap;
2031 }
2032 }
Greg Clayton3046e662013-07-10 01:23:25 +00002033}
2034
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035// Find the arm/aarch64 mapping symbol character in the given symbol name.
2036// Mapping symbols have the
2037// form of "$<char>[.<any>]*". Additionally we recognize cases when the mapping
2038// symbol prefixed by
2039// an arbitrary string because if a symbol prefix added to each symbol in the
2040// object file with
2041// objcopy then the mapping symbols are also prefixed.
2042static char FindArmAarch64MappingSymbol(const char *symbol_name) {
2043 if (!symbol_name)
2044 return '\0';
2045
2046 const char *dollar_pos = ::strchr(symbol_name, '$');
2047 if (!dollar_pos || dollar_pos[1] == '\0')
2048 return '\0';
2049
2050 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
2051 return dollar_pos[1];
2052 return '\0';
2053}
2054
2055#define STO_MIPS_ISA (3 << 6)
2056#define STO_MICROMIPS (2 << 6)
2057#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
2058
2059// private
2060unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
2061 SectionList *section_list,
2062 const size_t num_symbols,
2063 const DataExtractor &symtab_data,
2064 const DataExtractor &strtab_data) {
2065 ELFSymbol symbol;
2066 lldb::offset_t offset = 0;
2067
2068 static ConstString text_section_name(".text");
2069 static ConstString init_section_name(".init");
2070 static ConstString fini_section_name(".fini");
2071 static ConstString ctors_section_name(".ctors");
2072 static ConstString dtors_section_name(".dtors");
2073
2074 static ConstString data_section_name(".data");
2075 static ConstString rodata_section_name(".rodata");
2076 static ConstString rodata1_section_name(".rodata1");
2077 static ConstString data2_section_name(".data1");
2078 static ConstString bss_section_name(".bss");
2079 static ConstString opd_section_name(".opd"); // For ppc64
2080
2081 // On Android the oatdata and the oatexec symbols in the oat and odex files
2082 // covers the full
2083 // .text section what causes issues with displaying unusable symbol name to
2084 // the user and very
2085 // slow unwinding speed because the instruction emulation based unwind plans
2086 // try to emulate all
2087 // instructions in these symbols. Don't add these symbols to the symbol list
2088 // as they have no
2089 // use for the debugger and they are causing a lot of trouble.
2090 // Filtering can't be restricted to Android because this special object file
2091 // don't contain the
2092 // note section specifying the environment to Android but the custom extension
2093 // and file name
2094 // makes it highly unlikely that this will collide with anything else.
2095 ConstString file_extension = m_file.GetFileNameExtension();
2096 bool skip_oatdata_oatexec = file_extension == ConstString("oat") ||
2097 file_extension == ConstString("odex");
2098
2099 ArchSpec arch;
2100 GetArchitecture(arch);
2101 ModuleSP module_sp(GetModule());
2102 SectionList *module_section_list =
2103 module_sp ? module_sp->GetSectionList() : nullptr;
2104
2105 // Local cache to avoid doing a FindSectionByName for each symbol. The "const
2106 // char*" key must
2107 // came from a ConstString object so they can be compared by pointer
2108 std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
2109
2110 unsigned i;
2111 for (i = 0; i < num_symbols; ++i) {
2112 if (symbol.Parse(symtab_data, &offset) == false)
2113 break;
2114
2115 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2116 if (!symbol_name)
2117 symbol_name = "";
2118
2119 // No need to add non-section symbols that have no names
2120 if (symbol.getType() != STT_SECTION &&
2121 (symbol_name == nullptr || symbol_name[0] == '\0'))
2122 continue;
2123
2124 // Skipping oatdata and oatexec sections if it is requested. See details
2125 // above the
2126 // definition of skip_oatdata_oatexec for the reasons.
2127 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
2128 ::strcmp(symbol_name, "oatexec") == 0))
2129 continue;
2130
2131 SectionSP symbol_section_sp;
2132 SymbolType symbol_type = eSymbolTypeInvalid;
2133 Elf64_Half section_idx = symbol.st_shndx;
2134
2135 switch (section_idx) {
2136 case SHN_ABS:
2137 symbol_type = eSymbolTypeAbsolute;
2138 break;
2139 case SHN_UNDEF:
2140 symbol_type = eSymbolTypeUndefined;
2141 break;
2142 default:
2143 symbol_section_sp = section_list->GetSectionAtIndex(section_idx);
2144 break;
2145 }
2146
2147 // If a symbol is undefined do not process it further even if it has a STT
2148 // type
2149 if (symbol_type != eSymbolTypeUndefined) {
2150 switch (symbol.getType()) {
2151 default:
2152 case STT_NOTYPE:
2153 // The symbol's type is not specified.
2154 break;
2155
2156 case STT_OBJECT:
2157 // The symbol is associated with a data object, such as a variable,
2158 // an array, etc.
2159 symbol_type = eSymbolTypeData;
2160 break;
2161
2162 case STT_FUNC:
2163 // The symbol is associated with a function or other executable code.
2164 symbol_type = eSymbolTypeCode;
2165 break;
2166
2167 case STT_SECTION:
2168 // The symbol is associated with a section. Symbol table entries of
2169 // this type exist primarily for relocation and normally have
2170 // STB_LOCAL binding.
2171 break;
2172
2173 case STT_FILE:
2174 // Conventionally, the symbol's name gives the name of the source
2175 // file associated with the object file. A file symbol has STB_LOCAL
2176 // binding, its section index is SHN_ABS, and it precedes the other
2177 // STB_LOCAL symbols for the file, if it is present.
2178 symbol_type = eSymbolTypeSourceFile;
2179 break;
2180
2181 case STT_GNU_IFUNC:
2182 // The symbol is associated with an indirect function. The actual
2183 // function will be resolved if it is referenced.
2184 symbol_type = eSymbolTypeResolver;
2185 break;
2186 }
2187 }
2188
2189 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2190 if (symbol_section_sp) {
2191 const ConstString &sect_name = symbol_section_sp->GetName();
2192 if (sect_name == text_section_name || sect_name == init_section_name ||
2193 sect_name == fini_section_name || sect_name == ctors_section_name ||
2194 sect_name == dtors_section_name) {
2195 symbol_type = eSymbolTypeCode;
2196 } else if (sect_name == data_section_name ||
2197 sect_name == data2_section_name ||
2198 sect_name == rodata_section_name ||
2199 sect_name == rodata1_section_name ||
2200 sect_name == bss_section_name) {
2201 symbol_type = eSymbolTypeData;
2202 }
2203 }
2204 }
2205
2206 int64_t symbol_value_offset = 0;
2207 uint32_t additional_flags = 0;
2208
2209 if (arch.IsValid()) {
2210 if (arch.GetMachine() == llvm::Triple::arm) {
2211 if (symbol.getBinding() == STB_LOCAL) {
2212 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2213 if (symbol_type == eSymbolTypeCode) {
2214 switch (mapping_symbol) {
2215 case 'a':
2216 // $a[.<any>]* - marks an ARM instruction sequence
2217 m_address_class_map[symbol.st_value] = eAddressClassCode;
2218 break;
2219 case 'b':
2220 case 't':
2221 // $b[.<any>]* - marks a THUMB BL instruction sequence
2222 // $t[.<any>]* - marks a THUMB instruction sequence
2223 m_address_class_map[symbol.st_value] =
2224 eAddressClassCodeAlternateISA;
2225 break;
2226 case 'd':
2227 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2228 m_address_class_map[symbol.st_value] = eAddressClassData;
2229 break;
2230 }
2231 }
2232 if (mapping_symbol)
2233 continue;
2234 }
2235 } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2236 if (symbol.getBinding() == STB_LOCAL) {
2237 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2238 if (symbol_type == eSymbolTypeCode) {
2239 switch (mapping_symbol) {
2240 case 'x':
2241 // $x[.<any>]* - marks an A64 instruction sequence
2242 m_address_class_map[symbol.st_value] = eAddressClassCode;
2243 break;
2244 case 'd':
2245 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2246 m_address_class_map[symbol.st_value] = eAddressClassData;
2247 break;
2248 }
2249 }
2250 if (mapping_symbol)
2251 continue;
2252 }
2253 }
2254
2255 if (arch.GetMachine() == llvm::Triple::arm) {
2256 if (symbol_type == eSymbolTypeCode) {
2257 if (symbol.st_value & 1) {
2258 // Subtracting 1 from the address effectively unsets
2259 // the low order bit, which results in the address
2260 // actually pointing to the beginning of the symbol.
2261 // This delta will be used below in conjunction with
2262 // symbol.st_value to produce the final symbol_value
2263 // that we store in the symtab.
2264 symbol_value_offset = -1;
2265 m_address_class_map[symbol.st_value ^ 1] =
2266 eAddressClassCodeAlternateISA;
2267 } else {
2268 // This address is ARM
2269 m_address_class_map[symbol.st_value] = eAddressClassCode;
2270 }
2271 }
2272 }
2273
2274 /*
2275 * MIPS:
2276 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2277 * MIPS).
2278 * This allows processor to switch between microMIPS and MIPS without any
2279 * need
2280 * for special mode-control register. However, apart from .debug_line,
2281 * none of
2282 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2283 * st_other
2284 * flag to check whether the symbol is microMIPS and then set the address
2285 * class
2286 * accordingly.
2287 */
2288 const llvm::Triple::ArchType llvm_arch = arch.GetMachine();
2289 if (llvm_arch == llvm::Triple::mips ||
2290 llvm_arch == llvm::Triple::mipsel ||
2291 llvm_arch == llvm::Triple::mips64 ||
2292 llvm_arch == llvm::Triple::mips64el) {
2293 if (IS_MICROMIPS(symbol.st_other))
2294 m_address_class_map[symbol.st_value] = eAddressClassCodeAlternateISA;
2295 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2296 symbol.st_value = symbol.st_value & (~1ull);
2297 m_address_class_map[symbol.st_value] = eAddressClassCodeAlternateISA;
2298 } else {
2299 if (symbol_type == eSymbolTypeCode)
2300 m_address_class_map[symbol.st_value] = eAddressClassCode;
2301 else if (symbol_type == eSymbolTypeData)
2302 m_address_class_map[symbol.st_value] = eAddressClassData;
2303 else
2304 m_address_class_map[symbol.st_value] = eAddressClassUnknown;
2305 }
2306 }
2307 }
2308
2309 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
2310 // symbols. See above for
2311 // more details.
2312 uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2313
2314 if (symbol_section_sp == nullptr && section_idx == SHN_ABS &&
2315 symbol.st_size != 0) {
2316 // We don't have a section for a symbol with non-zero size. Create a new
2317 // section for it
2318 // so the address range covered by the symbol is also covered by the
2319 // module (represented
2320 // through the section list). It is needed so module lookup for the
2321 // addresses covered
2322 // by this symbol will be successfull. This case happens for absolute
2323 // symbols.
2324 ConstString fake_section_name(std::string(".absolute.") + symbol_name);
2325 symbol_section_sp =
2326 std::make_shared<Section>(module_sp, this, SHN_ABS, fake_section_name,
2327 eSectionTypeAbsoluteAddress, symbol_value,
2328 symbol.st_size, 0, 0, 0, SHF_ALLOC);
2329
2330 module_section_list->AddSection(symbol_section_sp);
2331 section_list->AddSection(symbol_section_sp);
2332 }
2333
2334 if (symbol_section_sp &&
2335 CalculateType() != ObjectFile::Type::eTypeObjectFile)
2336 symbol_value -= symbol_section_sp->GetFileAddress();
2337
2338 if (symbol_section_sp && module_section_list &&
2339 module_section_list != section_list) {
2340 const ConstString &sect_name = symbol_section_sp->GetName();
2341 auto section_it = section_name_to_section.find(sect_name.GetCString());
2342 if (section_it == section_name_to_section.end())
2343 section_it =
2344 section_name_to_section
2345 .emplace(sect_name.GetCString(),
2346 module_section_list->FindSectionByName(sect_name))
2347 .first;
2348 if (section_it->second && section_it->second->GetFileSize())
2349 symbol_section_sp = section_it->second;
2350 }
2351
2352 bool is_global = symbol.getBinding() == STB_GLOBAL;
2353 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2354 bool is_mangled = (symbol_name[0] == '_' && symbol_name[1] == 'Z');
2355
2356 llvm::StringRef symbol_ref(symbol_name);
2357
2358 // Symbol names may contain @VERSION suffixes. Find those and strip them
2359 // temporarily.
2360 size_t version_pos = symbol_ref.find('@');
2361 bool has_suffix = version_pos != llvm::StringRef::npos;
2362 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2363 Mangled mangled(ConstString(symbol_bare), is_mangled);
2364
2365 // Now append the suffix back to mangled and unmangled names. Only do it if
2366 // the
2367 // demangling was successful (string is not empty).
2368 if (has_suffix) {
2369 llvm::StringRef suffix = symbol_ref.substr(version_pos);
2370
2371 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2372 if (!mangled_name.empty())
2373 mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2374
2375 ConstString demangled =
2376 mangled.GetDemangledName(lldb::eLanguageTypeUnknown);
2377 llvm::StringRef demangled_name = demangled.GetStringRef();
2378 if (!demangled_name.empty())
2379 mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2380 }
2381
2382 // In ELF all symbol should have a valid size but it is not true for some
2383 // function symbols
2384 // coming from hand written assembly. As none of the function symbol should
2385 // have 0 size we
2386 // try to calculate the size for these symbols in the symtab with saying
2387 // that their original
2388 // size is not valid.
2389 bool symbol_size_valid =
2390 symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2391
2392 Symbol dc_symbol(
2393 i + start_id, // ID is the original symbol table index.
2394 mangled,
2395 symbol_type, // Type of this symbol
2396 is_global, // Is this globally visible?
2397 false, // Is this symbol debug info?
2398 false, // Is this symbol a trampoline?
2399 false, // Is this symbol artificial?
2400 AddressRange(symbol_section_sp, // Section in which this symbol is
2401 // defined or null.
2402 symbol_value, // Offset in section or symbol value.
2403 symbol.st_size), // Size in bytes of this symbol.
2404 symbol_size_valid, // Symbol size is valid
2405 has_suffix, // Contains linker annotations?
2406 flags); // Symbol flags.
2407 symtab->AddSymbol(dc_symbol);
2408 }
2409 return i;
2410}
2411
2412unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
2413 user_id_t start_id,
2414 lldb_private::Section *symtab) {
2415 if (symtab->GetObjectFile() != this) {
2416 // If the symbol table section is owned by a different object file, have it
2417 // do the
2418 // parsing.
2419 ObjectFileELF *obj_file_elf =
2420 static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2421 return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2422 }
2423
2424 // Get section list for this object file.
2425 SectionList *section_list = m_sections_ap.get();
2426 if (!section_list)
2427 return 0;
2428
2429 user_id_t symtab_id = symtab->GetID();
2430 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2431 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2432 symtab_hdr->sh_type == SHT_DYNSYM);
2433
2434 // sh_link: section header index of associated string table.
2435 // Section ID's are ones based.
2436 user_id_t strtab_id = symtab_hdr->sh_link + 1;
2437 Section *strtab = section_list->FindSectionByID(strtab_id).get();
2438
2439 if (symtab && strtab) {
2440 assert(symtab->GetObjectFile() == this);
2441 assert(strtab->GetObjectFile() == this);
2442
2443 DataExtractor symtab_data;
2444 DataExtractor strtab_data;
2445 if (ReadSectionData(symtab, symtab_data) &&
2446 ReadSectionData(strtab, strtab_data)) {
2447 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2448
2449 return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2450 symtab_data, strtab_data);
2451 }
2452 }
2453
2454 return 0;
2455}
2456
2457size_t ObjectFileELF::ParseDynamicSymbols() {
2458 if (m_dynamic_symbols.size())
2459 return m_dynamic_symbols.size();
2460
2461 SectionList *section_list = GetSectionList();
2462 if (!section_list)
2463 return 0;
2464
2465 // Find the SHT_DYNAMIC section.
2466 Section *dynsym =
2467 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
2468 .get();
2469 if (!dynsym)
2470 return 0;
2471 assert(dynsym->GetObjectFile() == this);
2472
2473 ELFDynamic symbol;
2474 DataExtractor dynsym_data;
2475 if (ReadSectionData(dynsym, dynsym_data)) {
2476 const lldb::offset_t section_size = dynsym_data.GetByteSize();
2477 lldb::offset_t cursor = 0;
2478
2479 while (cursor < section_size) {
2480 if (!symbol.Parse(dynsym_data, &cursor))
2481 break;
2482
2483 m_dynamic_symbols.push_back(symbol);
2484 }
2485 }
2486
2487 return m_dynamic_symbols.size();
2488}
2489
2490const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
2491 if (!ParseDynamicSymbols())
2492 return NULL;
2493
2494 DynamicSymbolCollIter I = m_dynamic_symbols.begin();
2495 DynamicSymbolCollIter E = m_dynamic_symbols.end();
2496 for (; I != E; ++I) {
2497 ELFDynamic *symbol = &*I;
2498
2499 if (symbol->d_tag == tag)
2500 return symbol;
2501 }
2502
2503 return NULL;
2504}
2505
2506unsigned ObjectFileELF::PLTRelocationType() {
2507 // DT_PLTREL
2508 // This member specifies the type of relocation entry to which the
2509 // procedure linkage table refers. The d_val member holds DT_REL or
2510 // DT_RELA, as appropriate. All relocations in a procedure linkage table
2511 // must use the same relocation.
2512 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2513
2514 if (symbol)
2515 return symbol->d_val;
2516
2517 return 0;
2518}
2519
2520// Returns the size of the normal plt entries and the offset of the first normal
2521// plt entry. The
2522// 0th entry in the plt table is usually a resolution entry which have different
2523// size in some
2524// architectures then the rest of the plt entries.
2525static std::pair<uint64_t, uint64_t>
2526GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
2527 const ELFSectionHeader *plt_hdr) {
2528 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2529
2530 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are 16
2531 // bytes.
2532 // So round the entsize up by the alignment if addralign is set.
2533 elf_xword plt_entsize =
2534 plt_hdr->sh_addralign
2535 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2536 : plt_hdr->sh_entsize;
2537
2538 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2539 // PLT entries relocation code in general requires multiple instruction and
2540 // should be greater than 4 bytes in most cases. Try to guess correct size
2541 // just in case.
2542 if (plt_entsize <= 4) {
2543 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
2544 // size of the plt
2545 // entries based on the number of entries and the size of the plt section
2546 // with the
2547 // assumption that the size of the 0th entry is at least as big as the size
2548 // of the normal
2549 // entries and it isn't much bigger then that.
2550 if (plt_hdr->sh_addralign)
2551 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2552 (num_relocations + 1) * plt_hdr->sh_addralign;
2553 else
2554 plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2555 }
2556
2557 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2558
2559 return std::make_pair(plt_entsize, plt_offset);
2560}
2561
2562static unsigned ParsePLTRelocations(
2563 Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2564 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2565 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2566 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2567 DataExtractor &symtab_data, DataExtractor &strtab_data) {
2568 ELFRelocation rel(rel_type);
2569 ELFSymbol symbol;
2570 lldb::offset_t offset = 0;
2571
2572 uint64_t plt_offset, plt_entsize;
2573 std::tie(plt_entsize, plt_offset) =
2574 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2575 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2576
2577 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2578 reloc_info_fn reloc_type;
2579 reloc_info_fn reloc_symbol;
2580
2581 if (hdr->Is32Bit()) {
2582 reloc_type = ELFRelocation::RelocType32;
2583 reloc_symbol = ELFRelocation::RelocSymbol32;
2584 } else {
2585 reloc_type = ELFRelocation::RelocType64;
2586 reloc_symbol = ELFRelocation::RelocSymbol64;
2587 }
2588
2589 unsigned slot_type = hdr->GetRelocationJumpSlotType();
2590 unsigned i;
2591 for (i = 0; i < num_relocations; ++i) {
2592 if (rel.Parse(rel_data, &offset) == false)
2593 break;
2594
2595 if (reloc_type(rel) != slot_type)
2596 continue;
2597
2598 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2599 if (!symbol.Parse(symtab_data, &symbol_offset))
2600 break;
2601
2602 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2603 bool is_mangled =
2604 symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
2605 uint64_t plt_index = plt_offset + i * plt_entsize;
2606
2607 Symbol jump_symbol(
2608 i + start_id, // Symbol table index
2609 symbol_name, // symbol name.
2610 is_mangled, // is the symbol name mangled?
2611 eSymbolTypeTrampoline, // Type of this symbol
2612 false, // Is this globally visible?
2613 false, // Is this symbol debug info?
2614 true, // Is this symbol a trampoline?
2615 true, // Is this symbol artificial?
2616 plt_section_sp, // Section in which this symbol is defined or null.
2617 plt_index, // Offset in section or symbol value.
2618 plt_entsize, // Size in bytes of this symbol.
2619 true, // Size is valid
2620 false, // Contains linker annotations?
2621 0); // Symbol flags.
2622
2623 symbol_table->AddSymbol(jump_symbol);
2624 }
2625
2626 return i;
2627}
2628
2629unsigned
2630ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
2631 const ELFSectionHeaderInfo *rel_hdr,
2632 user_id_t rel_id) {
2633 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2634
2635 // The link field points to the associated symbol table.
2636 user_id_t symtab_id = rel_hdr->sh_link;
2637
2638 // If the link field doesn't point to the appropriate symbol name table then
2639 // try to find it by name as some compiler don't fill in the link fields.
2640 if (!symtab_id)
2641 symtab_id = GetSectionIndexByName(".dynsym");
2642
2643 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers
2644 // point that to the .got.plt or .got section instead of .plt.
2645 user_id_t plt_id = GetSectionIndexByName(".plt");
2646
2647 if (!symtab_id || !plt_id)
2648 return 0;
2649
2650 // Section ID's are ones based;
2651 symtab_id++;
2652 plt_id++;
2653
2654 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2655 if (!plt_hdr)
2656 return 0;
2657
2658 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2659 if (!sym_hdr)
2660 return 0;
2661
2662 SectionList *section_list = m_sections_ap.get();
2663 if (!section_list)
2664 return 0;
2665
2666 Section *rel_section = section_list->FindSectionByID(rel_id).get();
2667 if (!rel_section)
2668 return 0;
2669
2670 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2671 if (!plt_section_sp)
2672 return 0;
2673
2674 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2675 if (!symtab)
2676 return 0;
2677
2678 // sh_link points to associated string table.
2679 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link + 1).get();
2680 if (!strtab)
2681 return 0;
2682
2683 DataExtractor rel_data;
2684 if (!ReadSectionData(rel_section, rel_data))
2685 return 0;
2686
2687 DataExtractor symtab_data;
2688 if (!ReadSectionData(symtab, symtab_data))
2689 return 0;
2690
2691 DataExtractor strtab_data;
2692 if (!ReadSectionData(strtab, strtab_data))
2693 return 0;
2694
2695 unsigned rel_type = PLTRelocationType();
2696 if (!rel_type)
2697 return 0;
2698
2699 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2700 rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2701 rel_data, symtab_data, strtab_data);
2702}
2703
2704unsigned ObjectFileELF::RelocateSection(
2705 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2706 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
2707 DataExtractor &rel_data, DataExtractor &symtab_data,
2708 DataExtractor &debug_data, Section *rel_section) {
2709 ELFRelocation rel(rel_hdr->sh_type);
2710 lldb::addr_t offset = 0;
2711 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2712 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2713 reloc_info_fn reloc_type;
2714 reloc_info_fn reloc_symbol;
2715
2716 if (hdr->Is32Bit()) {
2717 reloc_type = ELFRelocation::RelocType32;
2718 reloc_symbol = ELFRelocation::RelocSymbol32;
2719 } else {
2720 reloc_type = ELFRelocation::RelocType64;
2721 reloc_symbol = ELFRelocation::RelocSymbol64;
2722 }
2723
2724 for (unsigned i = 0; i < num_relocations; ++i) {
2725 if (rel.Parse(rel_data, &offset) == false)
2726 break;
2727
2728 Symbol *symbol = NULL;
2729
2730 if (hdr->Is32Bit()) {
2731 switch (reloc_type(rel)) {
2732 case R_386_32:
2733 case R_386_PC32:
2734 default:
2735 assert(false && "unexpected relocation type");
2736 }
2737 } else {
2738 switch (reloc_type(rel)) {
2739 case R_X86_64_64: {
2740 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2741 if (symbol) {
2742 addr_t value = symbol->GetAddressRef().GetFileAddress();
2743 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2744 uint64_t *dst = reinterpret_cast<uint64_t *>(
2745 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2746 ELFRelocation::RelocOffset64(rel));
2747 *dst = value + ELFRelocation::RelocAddend64(rel);
2748 }
2749 break;
2750 }
2751 case R_X86_64_32:
2752 case R_X86_64_32S: {
2753 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2754 if (symbol) {
2755 addr_t value = symbol->GetAddressRef().GetFileAddress();
2756 value += ELFRelocation::RelocAddend32(rel);
2757 assert(
2758 (reloc_type(rel) == R_X86_64_32 && (value <= UINT32_MAX)) ||
2759 (reloc_type(rel) == R_X86_64_32S &&
2760 ((int64_t)value <= INT32_MAX && (int64_t)value >= INT32_MIN)));
2761 uint32_t truncated_addr = (value & 0xFFFFFFFF);
2762 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2763 uint32_t *dst = reinterpret_cast<uint32_t *>(
2764 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2765 ELFRelocation::RelocOffset32(rel));
2766 *dst = truncated_addr;
2767 }
2768 break;
2769 }
2770 case R_X86_64_PC32:
2771 default:
2772 assert(false && "unexpected relocation type");
2773 }
2774 }
2775 }
2776
2777 return 0;
2778}
2779
2780unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
2781 user_id_t rel_id) {
2782 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2783
2784 // Parse in the section list if needed.
2785 SectionList *section_list = GetSectionList();
2786 if (!section_list)
2787 return 0;
2788
2789 // Section ID's are ones based.
2790 user_id_t symtab_id = rel_hdr->sh_link + 1;
2791 user_id_t debug_id = rel_hdr->sh_info + 1;
2792
2793 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2794 if (!symtab_hdr)
2795 return 0;
2796
2797 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
2798 if (!debug_hdr)
2799 return 0;
2800
2801 Section *rel = section_list->FindSectionByID(rel_id).get();
2802 if (!rel)
2803 return 0;
2804
2805 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2806 if (!symtab)
2807 return 0;
2808
2809 Section *debug = section_list->FindSectionByID(debug_id).get();
2810 if (!debug)
2811 return 0;
2812
2813 DataExtractor rel_data;
2814 DataExtractor symtab_data;
2815 DataExtractor debug_data;
2816
2817 if (ReadSectionData(rel, rel_data) && ReadSectionData(symtab, symtab_data) &&
2818 ReadSectionData(debug, debug_data)) {
2819 RelocateSection(m_symtab_ap.get(), &m_header, rel_hdr, symtab_hdr,
2820 debug_hdr, rel_data, symtab_data, debug_data, debug);
2821 }
2822
2823 return 0;
2824}
2825
2826Symtab *ObjectFileELF::GetSymtab() {
2827 ModuleSP module_sp(GetModule());
2828 if (!module_sp)
2829 return NULL;
2830
2831 // We always want to use the main object file so we (hopefully) only have one
2832 // cached copy
2833 // of our symtab, dynamic sections, etc.
2834 ObjectFile *module_obj_file = module_sp->GetObjectFile();
2835 if (module_obj_file && module_obj_file != this)
2836 return module_obj_file->GetSymtab();
2837
2838 if (m_symtab_ap.get() == NULL) {
2839 SectionList *section_list = module_sp->GetSectionList();
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002840 if (!section_list)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002841 return NULL;
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002842
Kate Stoneb9c1b512016-09-06 20:57:50 +00002843 uint64_t symbol_id = 0;
2844 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002845
Kate Stoneb9c1b512016-09-06 20:57:50 +00002846 // Sharable objects and dynamic executables usually have 2 distinct symbol
2847 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
2848 // smaller
2849 // version of the symtab that only contains global symbols. The information
2850 // found
2851 // in the dynsym is therefore also found in the symtab, while the reverse is
2852 // not
2853 // necessarily true.
2854 Section *symtab =
2855 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
2856 if (!symtab) {
2857 // The symtab section is non-allocable and can be stripped, so if it
2858 // doesn't exist
2859 // then use the dynsym section which should always be there.
2860 symtab =
2861 section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
2862 .get();
2863 }
2864 if (symtab) {
2865 m_symtab_ap.reset(new Symtab(symtab->GetObjectFile()));
2866 symbol_id += ParseSymbolTable(m_symtab_ap.get(), symbol_id, symtab);
2867 }
2868
2869 // DT_JMPREL
2870 // If present, this entry's d_ptr member holds the address of
2871 // relocation
2872 // entries associated solely with the procedure linkage table.
2873 // Separating
2874 // these relocation entries lets the dynamic linker ignore them during
2875 // process initialization, if lazy binding is enabled. If this entry is
2876 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
2877 // also be present.
2878 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
2879 if (symbol) {
2880 // Synthesize trampoline symbols to help navigate the PLT.
2881 addr_t addr = symbol->d_ptr;
2882 Section *reloc_section =
2883 section_list->FindSectionContainingFileAddress(addr).get();
2884 if (reloc_section) {
2885 user_id_t reloc_id = reloc_section->GetID();
2886 const ELFSectionHeaderInfo *reloc_header =
2887 GetSectionHeaderByIndex(reloc_id);
2888 assert(reloc_header);
2889
2890 if (m_symtab_ap == nullptr)
2891 m_symtab_ap.reset(new Symtab(reloc_section->GetObjectFile()));
2892
2893 ParseTrampolineSymbols(m_symtab_ap.get(), symbol_id, reloc_header,
2894 reloc_id);
2895 }
2896 }
2897
2898 DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo();
2899 if (eh_frame) {
2900 if (m_symtab_ap == nullptr)
2901 m_symtab_ap.reset(new Symtab(this));
2902 ParseUnwindSymbols(m_symtab_ap.get(), eh_frame);
2903 }
2904
2905 // If we still don't have any symtab then create an empty instance to avoid
2906 // do the section
2907 // lookup next time.
2908 if (m_symtab_ap == nullptr)
2909 m_symtab_ap.reset(new Symtab(this));
2910
2911 m_symtab_ap->CalculateSymbolSizes();
2912 }
2913
2914 for (SectionHeaderCollIter I = m_section_headers.begin();
2915 I != m_section_headers.end(); ++I) {
2916 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
2917 if (CalculateType() == eTypeObjectFile) {
2918 const char *section_name = I->section_name.AsCString("");
2919 if (strstr(section_name, ".rela.debug") ||
2920 strstr(section_name, ".rel.debug")) {
2921 const ELFSectionHeader &reloc_header = *I;
2922 user_id_t reloc_id = SectionIndex(I);
2923 RelocateDebugSections(&reloc_header, reloc_id);
Tamas Berghammered844cb2016-02-10 10:43:34 +00002924 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 }
2926 }
2927 }
2928 return m_symtab_ap.get();
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002929}
Tamas Berghammer5bfd4d02016-02-10 12:10:58 +00002930
Kate Stoneb9c1b512016-09-06 20:57:50 +00002931void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
2932 DWARFCallFrameInfo *eh_frame) {
2933 SectionList *section_list = GetSectionList();
2934 if (!section_list)
2935 return;
2936
2937 // First we save the new symbols into a separate list and add them to the
2938 // symbol table after
2939 // we colleced all symbols we want to add. This is neccessary because adding a
2940 // new symbol
2941 // invalidates the internal index of the symtab what causing the next lookup
2942 // to be slow because
2943 // it have to recalculate the index first.
2944 std::vector<Symbol> new_symbols;
2945
2946 eh_frame->ForEachFDEEntries([this, symbol_table, section_list, &new_symbols](
2947 lldb::addr_t file_addr, uint32_t size, dw_offset_t) {
2948 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
2949 if (symbol) {
2950 if (!symbol->GetByteSizeIsValid()) {
2951 symbol->SetByteSize(size);
2952 symbol->SetSizeIsSynthesized(true);
2953 }
2954 } else {
2955 SectionSP section_sp =
2956 section_list->FindSectionContainingFileAddress(file_addr);
2957 if (section_sp) {
2958 addr_t offset = file_addr - section_sp->GetFileAddress();
2959 const char *symbol_name = GetNextSyntheticSymbolName().GetCString();
2960 uint64_t symbol_id = symbol_table->GetNumSymbols();
2961 Symbol eh_symbol(
2962 symbol_id, // Symbol table index.
2963 symbol_name, // Symbol name.
2964 false, // Is the symbol name mangled?
2965 eSymbolTypeCode, // Type of this symbol.
2966 true, // Is this globally visible?
2967 false, // Is this symbol debug info?
2968 false, // Is this symbol a trampoline?
2969 true, // Is this symbol artificial?
2970 section_sp, // Section in which this symbol is defined or null.
2971 offset, // Offset in section or symbol value.
2972 0, // Size: Don't specify the size as an FDE can
2973 false, // Size is valid: cover multiple symbols.
2974 false, // Contains linker annotations?
2975 0); // Symbol flags.
2976 new_symbols.push_back(eh_symbol);
2977 }
2978 }
2979 return true;
2980 });
2981
2982 for (const Symbol &s : new_symbols)
2983 symbol_table->AddSymbol(s);
2984}
2985
2986bool ObjectFileELF::IsStripped() {
2987 // TODO: determine this for ELF
2988 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002989}
2990
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991//===----------------------------------------------------------------------===//
2992// Dump
2993//
2994// Dump the specifics of the runtime file container (such as any headers
2995// segments, sections, etc).
2996//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002997void ObjectFileELF::Dump(Stream *s) {
2998 ModuleSP module_sp(GetModule());
2999 if (!module_sp) {
3000 return;
3001 }
Adrian McCarthy543725c2016-04-04 21:21:49 +00003002
Kate Stoneb9c1b512016-09-06 20:57:50 +00003003 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3004 s->Printf("%p: ", static_cast<void *>(this));
3005 s->Indent();
3006 s->PutCString("ObjectFileELF");
Adrian McCarthy543725c2016-04-04 21:21:49 +00003007
Kate Stoneb9c1b512016-09-06 20:57:50 +00003008 ArchSpec header_arch;
3009 GetArchitecture(header_arch);
Adrian McCarthy543725c2016-04-04 21:21:49 +00003010
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 *s << ", file = '" << m_file
3012 << "', arch = " << header_arch.GetArchitectureName() << "\n";
Adrian McCarthy543725c2016-04-04 21:21:49 +00003013
Kate Stoneb9c1b512016-09-06 20:57:50 +00003014 DumpELFHeader(s, m_header);
3015 s->EOL();
3016 DumpELFProgramHeaders(s);
3017 s->EOL();
3018 DumpELFSectionHeaders(s);
3019 s->EOL();
3020 SectionList *section_list = GetSectionList();
3021 if (section_list)
3022 section_list->Dump(s, NULL, true, UINT32_MAX);
3023 Symtab *symtab = GetSymtab();
3024 if (symtab)
3025 symtab->Dump(s, NULL, eSortOrderNone);
3026 s->EOL();
3027 DumpDependentModules(s);
3028 s->EOL();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003029}
3030
3031//----------------------------------------------------------------------
3032// DumpELFHeader
3033//
3034// Dump the ELF header to the specified output stream
3035//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003036void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
3037 s->PutCString("ELF Header\n");
3038 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
3039 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
3040 header.e_ident[EI_MAG1]);
3041 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
3042 header.e_ident[EI_MAG2]);
3043 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
3044 header.e_ident[EI_MAG3]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045
Kate Stoneb9c1b512016-09-06 20:57:50 +00003046 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
3047 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
3048 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
3049 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
3050 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003051
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052 s->Printf("e_type = 0x%4.4x ", header.e_type);
3053 DumpELFHeader_e_type(s, header.e_type);
3054 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
3055 s->Printf("e_version = 0x%8.8x\n", header.e_version);
3056 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
3057 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
3058 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
3059 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
3060 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
3061 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
3062 s->Printf("e_phnum = 0x%4.4x\n", header.e_phnum);
3063 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
3064 s->Printf("e_shnum = 0x%4.4x\n", header.e_shnum);
3065 s->Printf("e_shstrndx = 0x%4.4x\n", header.e_shstrndx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003066}
3067
3068//----------------------------------------------------------------------
3069// DumpELFHeader_e_type
3070//
3071// Dump an token value for the ELF header member e_type
3072//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003073void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
3074 switch (e_type) {
3075 case ET_NONE:
3076 *s << "ET_NONE";
3077 break;
3078 case ET_REL:
3079 *s << "ET_REL";
3080 break;
3081 case ET_EXEC:
3082 *s << "ET_EXEC";
3083 break;
3084 case ET_DYN:
3085 *s << "ET_DYN";
3086 break;
3087 case ET_CORE:
3088 *s << "ET_CORE";
3089 break;
3090 default:
3091 break;
3092 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003093}
3094
3095//----------------------------------------------------------------------
3096// DumpELFHeader_e_ident_EI_DATA
3097//
3098// Dump an token value for the ELF header member e_ident[EI_DATA]
3099//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003100void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
3101 unsigned char ei_data) {
3102 switch (ei_data) {
3103 case ELFDATANONE:
3104 *s << "ELFDATANONE";
3105 break;
3106 case ELFDATA2LSB:
3107 *s << "ELFDATA2LSB - Little Endian";
3108 break;
3109 case ELFDATA2MSB:
3110 *s << "ELFDATA2MSB - Big Endian";
3111 break;
3112 default:
3113 break;
3114 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115}
3116
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117//----------------------------------------------------------------------
3118// DumpELFProgramHeader
3119//
3120// Dump a single ELF program header to the specified output stream
3121//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003122void ObjectFileELF::DumpELFProgramHeader(Stream *s,
3123 const ELFProgramHeader &ph) {
3124 DumpELFProgramHeader_p_type(s, ph.p_type);
3125 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3126 ph.p_vaddr, ph.p_paddr);
3127 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3128 ph.p_flags);
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003129
Kate Stoneb9c1b512016-09-06 20:57:50 +00003130 DumpELFProgramHeader_p_flags(s, ph.p_flags);
3131 s->Printf(") %8.8" PRIx64, ph.p_align);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003132}
3133
3134//----------------------------------------------------------------------
3135// DumpELFProgramHeader_p_type
3136//
3137// Dump an token value for the ELF program header member p_type which
3138// describes the type of the program header
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003139// ----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
3141 const int kStrWidth = 15;
3142 switch (p_type) {
3143 CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3144 CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3145 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3146 CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3147 CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3148 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3149 CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3150 CASE_AND_STREAM(s, PT_TLS, kStrWidth);
Filipe Cabecinhas477d86d2013-05-23 23:01:14 +00003151 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003152 default:
3153 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3154 break;
3155 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003156}
3157
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158//----------------------------------------------------------------------
3159// DumpELFProgramHeader_p_flags
3160//
3161// Dump an token value for the ELF program header member p_flags
3162//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003163void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
3164 *s << ((p_flags & PF_X) ? "PF_X" : " ")
3165 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3166 << ((p_flags & PF_W) ? "PF_W" : " ")
3167 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3168 << ((p_flags & PF_R) ? "PF_R" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003169}
3170
3171//----------------------------------------------------------------------
3172// DumpELFProgramHeaders
3173//
3174// Dump all of the ELF program header to the specified output stream
3175//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003176void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
3177 if (!ParseProgramHeaders())
3178 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003179
Kate Stoneb9c1b512016-09-06 20:57:50 +00003180 s->PutCString("Program Headers\n");
3181 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
3182 "p_filesz p_memsz p_flags p_align\n");
3183 s->PutCString("==== --------------- -------- -------- -------- "
3184 "-------- -------- ------------------------- --------\n");
Ed Maste3a8ab6e2015-02-23 15:33:11 +00003185
Kate Stoneb9c1b512016-09-06 20:57:50 +00003186 uint32_t idx = 0;
3187 for (ProgramHeaderCollConstIter I = m_program_headers.begin();
3188 I != m_program_headers.end(); ++I, ++idx) {
3189 s->Printf("[%2u] ", idx);
3190 ObjectFileELF::DumpELFProgramHeader(s, *I);
3191 s->EOL();
3192 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003193}
3194
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195//----------------------------------------------------------------------
3196// DumpELFSectionHeader
3197//
3198// Dump a single ELF section header to the specified output stream
3199//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003200void ObjectFileELF::DumpELFSectionHeader(Stream *s,
3201 const ELFSectionHeaderInfo &sh) {
3202 s->Printf("%8.8x ", sh.sh_name);
3203 DumpELFSectionHeader_sh_type(s, sh.sh_type);
3204 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3205 DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
3206 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3207 sh.sh_offset, sh.sh_size);
3208 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3209 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003210}
3211
3212//----------------------------------------------------------------------
3213// DumpELFSectionHeader_sh_type
3214//
3215// Dump an token value for the ELF section header member sh_type which
3216// describes the type of the section
3217//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003218void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
3219 const int kStrWidth = 12;
3220 switch (sh_type) {
3221 CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3222 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3223 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3224 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3225 CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3226 CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3227 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3228 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3229 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3230 CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3231 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3232 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3233 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3234 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3235 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3236 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3237 default:
3238 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3239 break;
3240 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003241}
3242
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003243//----------------------------------------------------------------------
3244// DumpELFSectionHeader_sh_flags
3245//
3246// Dump an token value for the ELF section header member sh_flags
3247//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003248void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
3249 elf_xword sh_flags) {
3250 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
3251 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3252 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
3253 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3254 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003255}
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003256
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003257//----------------------------------------------------------------------
3258// DumpELFSectionHeaders
3259//
3260// Dump all of the ELF section header to the specified output stream
3261//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003262void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
3263 if (!ParseSectionHeaders())
3264 return;
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003265
Kate Stoneb9c1b512016-09-06 20:57:50 +00003266 s->PutCString("Section Headers\n");
3267 s->PutCString("IDX name type flags "
3268 "addr offset size link info addralgn "
3269 "entsize Name\n");
3270 s->PutCString("==== -------- ------------ -------------------------------- "
3271 "-------- -------- -------- -------- -------- -------- "
3272 "-------- ====================\n");
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003273
Kate Stoneb9c1b512016-09-06 20:57:50 +00003274 uint32_t idx = 0;
3275 for (SectionHeaderCollConstIter I = m_section_headers.begin();
3276 I != m_section_headers.end(); ++I, ++idx) {
3277 s->Printf("[%2u] ", idx);
3278 ObjectFileELF::DumpELFSectionHeader(s, *I);
3279 const char *section_name = I->section_name.AsCString("");
3280 if (section_name)
3281 *s << ' ' << section_name << "\n";
3282 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003283}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003284
Kate Stoneb9c1b512016-09-06 20:57:50 +00003285void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
3286 size_t num_modules = ParseDependentModules();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003287
Kate Stoneb9c1b512016-09-06 20:57:50 +00003288 if (num_modules > 0) {
3289 s->PutCString("Dependent Modules:\n");
3290 for (unsigned i = 0; i < num_modules; ++i) {
3291 const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
3292 s->Printf(" %s\n", spec.GetFilename().GetCString());
3293 }
3294 }
3295}
3296
3297bool ObjectFileELF::GetArchitecture(ArchSpec &arch) {
3298 if (!ParseHeader())
3299 return false;
3300
3301 if (m_section_headers.empty()) {
3302 // Allow elf notes to be parsed which may affect the detected architecture.
3303 ParseSectionHeaders();
3304 }
3305
3306 if (CalculateType() == eTypeCoreFile &&
3307 m_arch_spec.TripleOSIsUnspecifiedUnknown()) {
3308 // Core files don't have section headers yet they have PT_NOTE program
3309 // headers
3310 // that might shed more light on the architecture
3311 if (ParseProgramHeaders()) {
3312 for (size_t i = 0, count = GetProgramHeaderCount(); i < count; ++i) {
3313 const elf::ELFProgramHeader *header = GetProgramHeaderByIndex(i);
3314 if (header && header->p_type == PT_NOTE && header->p_offset != 0 &&
3315 header->p_filesz > 0) {
3316 DataExtractor data;
3317 if (data.SetData(m_data, header->p_offset, header->p_filesz) ==
3318 header->p_filesz) {
3319 lldb_private::UUID uuid;
3320 RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
3321 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003322 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003323 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003324 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003325 }
3326 arch = m_arch_spec;
3327 return true;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003328}
3329
Kate Stoneb9c1b512016-09-06 20:57:50 +00003330ObjectFile::Type ObjectFileELF::CalculateType() {
3331 switch (m_header.e_type) {
3332 case llvm::ELF::ET_NONE:
3333 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003334 return eTypeUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003335
3336 case llvm::ELF::ET_REL:
3337 // 1 - Relocatable file
3338 return eTypeObjectFile;
3339
3340 case llvm::ELF::ET_EXEC:
3341 // 2 - Executable file
3342 return eTypeExecutable;
3343
3344 case llvm::ELF::ET_DYN:
3345 // 3 - Shared object file
3346 return eTypeSharedLibrary;
3347
3348 case ET_CORE:
3349 // 4 - Core file
3350 return eTypeCoreFile;
3351
3352 default:
3353 break;
3354 }
3355 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003356}
3357
Kate Stoneb9c1b512016-09-06 20:57:50 +00003358ObjectFile::Strata ObjectFileELF::CalculateStrata() {
3359 switch (m_header.e_type) {
3360 case llvm::ELF::ET_NONE:
3361 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003362 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003363
Kate Stoneb9c1b512016-09-06 20:57:50 +00003364 case llvm::ELF::ET_REL:
3365 // 1 - Relocatable file
3366 return eStrataUnknown;
3367
3368 case llvm::ELF::ET_EXEC:
3369 // 2 - Executable file
3370 // TODO: is there any way to detect that an executable is a kernel
3371 // related executable by inspecting the program headers, section
3372 // headers, symbols, or any other flag bits???
3373 return eStrataUser;
3374
3375 case llvm::ELF::ET_DYN:
3376 // 3 - Shared object file
3377 // TODO: is there any way to detect that an shared library is a kernel
3378 // related executable by inspecting the program headers, section
3379 // headers, symbols, or any other flag bits???
3380 return eStrataUnknown;
3381
3382 case ET_CORE:
3383 // 4 - Core file
3384 // TODO: is there any way to detect that an core file is a kernel
3385 // related executable by inspecting the program headers, section
3386 // headers, symbols, or any other flag bits???
3387 return eStrataUnknown;
3388
3389 default:
3390 break;
3391 }
3392 return eStrataUnknown;
3393}