blob: ca2da5a72a5ecaddb3ec26252074637d5ee00b9c [file] [log] [blame]
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001//===-- ObjectFileELF.cpp ------------------------------------- -*- C++ -*-===//
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Chris Lattner30fdc8d2010-06-08 16:52:24 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "ObjectFileELF.h"
10
Chris Lattner30fdc8d2010-06-08 16:52:24 +000011#include <algorithm>
Kate Stoneb9c1b512016-09-06 20:57:50 +000012#include <cassert>
Tamas Berghammer9fa11472015-10-27 10:43:27 +000013#include <unordered_map>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000014
Stephen Wilsonf325ba92010-07-13 23:07:23 +000015#include "lldb/Core/FileSpecList.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000016#include "lldb/Core/Module.h"
Greg Claytonf4d6de62013-04-24 22:29:28 +000017#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000018#include "lldb/Core/PluginManager.h"
19#include "lldb/Core/Section.h"
Jonas Devlieghere59b78bc2018-11-01 04:45:28 +000020#include "lldb/Host/FileSystem.h"
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +000021#include "lldb/Symbol/DWARFCallFrameInfo.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000022#include "lldb/Symbol/SymbolContext.h"
Steve Pucci9e02dac2014-02-06 19:02:19 +000023#include "lldb/Target/SectionLoadList.h"
Ed Maste54803652013-10-11 17:39:07 +000024#include "lldb/Target/Target.h"
Pavel Labath5f19b902017-11-13 16:16:33 +000025#include "lldb/Utility/ArchSpec.h"
Pavel Labathe2867bc2017-12-15 14:23:58 +000026#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000027#include "lldb/Utility/Log.h"
Pavel Labathb8093312019-03-06 14:41:43 +000028#include "lldb/Utility/RangeMap.h"
Zachary Turner97206d52017-05-12 04:51:55 +000029#include "lldb/Utility/Status.h"
Zachary Turnerbf9a7732017-02-02 21:39:50 +000030#include "lldb/Utility/Stream.h"
Pavel Labath38d06322017-06-29 14:32:17 +000031#include "lldb/Utility/Timer.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000032
Pavel Labathf55aea72019-01-09 16:50:45 +000033#include "llvm/ADT/IntervalMap.h"
Stephen Wilson499b40e2011-03-30 16:07:05 +000034#include "llvm/ADT/PointerUnion.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000035#include "llvm/ADT/StringRef.h"
Pavel Labathe2867bc2017-12-15 14:23:58 +000036#include "llvm/Object/Decompressor.h"
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +000037#include "llvm/Support/ARMBuildAttributes.h"
Zachary Turner736d4d82014-06-25 05:42:32 +000038#include "llvm/Support/MathExtras.h"
Zachary Turner3f4a4b32017-02-24 18:56:49 +000039#include "llvm/Support/MemoryBuffer.h"
Sagar Thakurad5b55a2016-05-24 14:52:50 +000040#include "llvm/Support/MipsABIFlags.h"
Stephen Wilson499b40e2011-03-30 16:07:05 +000041
Kate Stoneb9c1b512016-09-06 20:57:50 +000042#define CASE_AND_STREAM(s, def, width) \
43 case def: \
44 s->Printf("%-*s", width, #def); \
45 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046
Chris Lattner30fdc8d2010-06-08 16:52:24 +000047using namespace lldb;
48using namespace lldb_private;
Stephen Wilsonf325ba92010-07-13 23:07:23 +000049using namespace elf;
50using namespace llvm::ELF;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000051
Stephen Wilson499b40e2011-03-30 16:07:05 +000052namespace {
Todd Fialab91de782014-06-27 16:52:49 +000053
54// ELF note owner definitions
55const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";
Kate Stoneb9c1b512016-09-06 20:57:50 +000056const char *const LLDB_NT_OWNER_GNU = "GNU";
57const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";
Michal Gorny4f134fb2019-02-20 14:31:06 +000058const char *const LLDB_NT_OWNER_NETBSDCORE = "NetBSD-CORE";
Kamil Rytarowski12801f12017-03-26 15:34:57 +000059const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD";
Kate Stoneb9c1b512016-09-06 20:57:50 +000060const char *const LLDB_NT_OWNER_CSR = "csr";
Tamas Berghammerdb037d92015-03-18 10:36:27 +000061const char *const LLDB_NT_OWNER_ANDROID = "Android";
Kate Stoneb9c1b512016-09-06 20:57:50 +000062const char *const LLDB_NT_OWNER_CORE = "CORE";
63const char *const LLDB_NT_OWNER_LINUX = "LINUX";
Todd Fialab91de782014-06-27 16:52:49 +000064
65// ELF note type definitions
Kate Stoneb9c1b512016-09-06 20:57:50 +000066const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01;
Todd Fialab91de782014-06-27 16:52:49 +000067const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4;
68
Kate Stoneb9c1b512016-09-06 20:57:50 +000069const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;
70const elf_word LLDB_NT_GNU_ABI_SIZE = 16;
Todd Fialab91de782014-06-27 16:52:49 +000071
72const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03;
73
Michal Gorny4f134fb2019-02-20 14:31:06 +000074const elf_word LLDB_NT_NETBSD_IDENT_TAG = 1;
75const elf_word LLDB_NT_NETBSD_IDENT_DESCSZ = 4;
76const elf_word LLDB_NT_NETBSD_IDENT_NAMESZ = 7;
77const elf_word LLDB_NT_NETBSD_PROCINFO = 1;
Todd Fialab91de782014-06-27 16:52:49 +000078
79// GNU ABI note OS constants
Kate Stoneb9c1b512016-09-06 20:57:50 +000080const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00;
81const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01;
Todd Fialab91de782014-06-27 16:52:49 +000082const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02;
83
Greg Claytonb704b692015-10-28 18:04:38 +000084// LLDB_NT_OWNER_CORE and LLDB_NT_OWNER_LINUX note contants
Kate Stoneb9c1b512016-09-06 20:57:50 +000085#define NT_PRSTATUS 1
86#define NT_PRFPREG 2
87#define NT_PRPSINFO 3
88#define NT_TASKSTRUCT 4
89#define NT_AUXV 6
90#define NT_SIGINFO 0x53494749
91#define NT_FILE 0x46494c45
92#define NT_PRXFPREG 0x46e62b7f
93#define NT_PPC_VMX 0x100
94#define NT_PPC_SPE 0x101
95#define NT_PPC_VSX 0x102
96#define NT_386_TLS 0x200
97#define NT_386_IOPERM 0x201
98#define NT_X86_XSTATE 0x202
99#define NT_S390_HIGH_GPRS 0x300
100#define NT_S390_TIMER 0x301
101#define NT_S390_TODCMP 0x302
102#define NT_S390_TODPREG 0x303
103#define NT_S390_CTRS 0x304
104#define NT_S390_PREFIX 0x305
105#define NT_S390_LAST_BREAK 0x306
106#define NT_S390_SYSTEM_CALL 0x307
107#define NT_S390_TDB 0x308
108#define NT_S390_VXRS_LOW 0x309
109#define NT_S390_VXRS_HIGH 0x30a
110#define NT_ARM_VFP 0x400
111#define NT_ARM_TLS 0x401
112#define NT_ARM_HW_BREAK 0x402
113#define NT_ARM_HW_WATCH 0x403
114#define NT_ARM_SYSTEM_CALL 0x404
115#define NT_METAG_CBUF 0x500
116#define NT_METAG_RPIPE 0x501
117#define NT_METAG_TLS 0x502
Greg Claytonb704b692015-10-28 18:04:38 +0000118
Stephen Wilson499b40e2011-03-30 16:07:05 +0000119//===----------------------------------------------------------------------===//
120/// @class ELFRelocation
Adrian Prantld8f460e2018-05-02 16:55:16 +0000121/// Generic wrapper for ELFRel and ELFRela.
Stephen Wilson499b40e2011-03-30 16:07:05 +0000122///
123/// This helper class allows us to parse both ELFRel and ELFRela relocation
124/// entries in a generic manner.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000125class ELFRelocation {
Stephen Wilson499b40e2011-03-30 16:07:05 +0000126public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000127 /// Constructs an ELFRelocation entry with a personality as given by @p
128 /// type.
129 ///
130 /// @param type Either DT_REL or DT_RELA. Any other value is invalid.
131 ELFRelocation(unsigned type);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 ~ELFRelocation();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 static unsigned RelocType32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 static unsigned RelocType64(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 static unsigned RelocSymbol32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 static unsigned RelocSymbol64(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 static unsigned RelocOffset32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 static unsigned RelocOffset64(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000148
Kate Stoneb9c1b512016-09-06 20:57:50 +0000149 static unsigned RelocAddend32(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000150
Kate Stoneb9c1b512016-09-06 20:57:50 +0000151 static unsigned RelocAddend64(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000152
Stephen Wilson499b40e2011-03-30 16:07:05 +0000153private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000154 typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;
Stephen Wilson499b40e2011-03-30 16:07:05 +0000155
Kate Stoneb9c1b512016-09-06 20:57:50 +0000156 RelocUnion reloc;
Stephen Wilson499b40e2011-03-30 16:07:05 +0000157};
158
Kate Stoneb9c1b512016-09-06 20:57:50 +0000159ELFRelocation::ELFRelocation(unsigned type) {
160 if (type == DT_REL || type == SHT_REL)
161 reloc = new ELFRel();
162 else if (type == DT_RELA || type == SHT_RELA)
163 reloc = new ELFRela();
164 else {
165 assert(false && "unexpected relocation type");
166 reloc = static_cast<ELFRel *>(NULL);
167 }
Stephen Wilson499b40e2011-03-30 16:07:05 +0000168}
169
Kate Stoneb9c1b512016-09-06 20:57:50 +0000170ELFRelocation::~ELFRelocation() {
171 if (reloc.is<ELFRel *>())
172 delete reloc.get<ELFRel *>();
173 else
174 delete reloc.get<ELFRela *>();
Stephen Wilson499b40e2011-03-30 16:07:05 +0000175}
176
Kate Stoneb9c1b512016-09-06 20:57:50 +0000177bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,
178 lldb::offset_t *offset) {
179 if (reloc.is<ELFRel *>())
180 return reloc.get<ELFRel *>()->Parse(data, offset);
181 else
182 return reloc.get<ELFRela *>()->Parse(data, offset);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000183}
184
Kate Stoneb9c1b512016-09-06 20:57:50 +0000185unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {
186 if (rel.reloc.is<ELFRel *>())
187 return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>());
188 else
189 return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000190}
191
Kate Stoneb9c1b512016-09-06 20:57:50 +0000192unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {
193 if (rel.reloc.is<ELFRel *>())
194 return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>());
195 else
196 return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000197}
198
Kate Stoneb9c1b512016-09-06 20:57:50 +0000199unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {
200 if (rel.reloc.is<ELFRel *>())
201 return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>());
202 else
203 return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000204}
205
Kate Stoneb9c1b512016-09-06 20:57:50 +0000206unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {
207 if (rel.reloc.is<ELFRel *>())
208 return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>());
209 else
210 return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000211}
212
Kate Stoneb9c1b512016-09-06 20:57:50 +0000213unsigned ELFRelocation::RelocOffset32(const ELFRelocation &rel) {
214 if (rel.reloc.is<ELFRel *>())
215 return rel.reloc.get<ELFRel *>()->r_offset;
216 else
217 return rel.reloc.get<ELFRela *>()->r_offset;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000218}
219
Kate Stoneb9c1b512016-09-06 20:57:50 +0000220unsigned ELFRelocation::RelocOffset64(const ELFRelocation &rel) {
221 if (rel.reloc.is<ELFRel *>())
222 return rel.reloc.get<ELFRel *>()->r_offset;
223 else
224 return rel.reloc.get<ELFRela *>()->r_offset;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000225}
226
Kate Stoneb9c1b512016-09-06 20:57:50 +0000227unsigned ELFRelocation::RelocAddend32(const ELFRelocation &rel) {
228 if (rel.reloc.is<ELFRel *>())
229 return 0;
230 else
231 return rel.reloc.get<ELFRela *>()->r_addend;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000232}
233
Kate Stoneb9c1b512016-09-06 20:57:50 +0000234unsigned ELFRelocation::RelocAddend64(const ELFRelocation &rel) {
235 if (rel.reloc.is<ELFRel *>())
236 return 0;
237 else
238 return rel.reloc.get<ELFRela *>()->r_addend;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000239}
240
Stephen Wilson499b40e2011-03-30 16:07:05 +0000241} // end anonymous namespace
242
Pavel Labathf55aea72019-01-09 16:50:45 +0000243static user_id_t SegmentID(size_t PHdrIndex) { return ~PHdrIndex; }
244
Kate Stoneb9c1b512016-09-06 20:57:50 +0000245bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {
246 // Read all fields.
247 if (data.GetU32(offset, &n_namesz, 3) == NULL)
248 return false;
Ed Mastec113ff82013-12-02 17:49:13 +0000249
Adrian Prantl05097242018-04-30 16:49:04 +0000250 // The name field is required to be nul-terminated, and n_namesz includes the
251 // terminating nul in observed implementations (contrary to the ELF-64 spec).
252 // A special case is needed for cores generated by some older Linux versions,
253 // which write a note named "CORE" without a nul terminator and n_namesz = 4.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000254 if (n_namesz == 4) {
255 char buf[4];
256 if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)
257 return false;
258 if (strncmp(buf, "CORE", 4) == 0) {
259 n_name = "CORE";
260 *offset += 4;
261 return true;
Ed Mastec113ff82013-12-02 17:49:13 +0000262 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000263 }
Ed Mastec113ff82013-12-02 17:49:13 +0000264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));
266 if (cstr == NULL) {
267 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
268 if (log)
269 log->Printf("Failed to parse note name lacking nul terminator");
Ed Mastec113ff82013-12-02 17:49:13 +0000270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271 return false;
272 }
273 n_name = cstr;
274 return true;
Ed Mastec113ff82013-12-02 17:49:13 +0000275}
276
Kate Stoneb9c1b512016-09-06 20:57:50 +0000277static uint32_t kalimbaVariantFromElfFlags(const elf::elf_word e_flags) {
278 const uint32_t dsp_rev = e_flags & 0xFF;
279 uint32_t kal_arch_variant = LLDB_INVALID_CPUTYPE;
280 switch (dsp_rev) {
281 // TODO(mg11) Support more variants
282 case 10:
283 kal_arch_variant = llvm::Triple::KalimbaSubArch_v3;
284 break;
285 case 14:
286 kal_arch_variant = llvm::Triple::KalimbaSubArch_v4;
287 break;
288 case 17:
289 case 20:
290 kal_arch_variant = llvm::Triple::KalimbaSubArch_v5;
291 break;
292 default:
293 break;
294 }
295 return kal_arch_variant;
Matthew Gardiner5f675792014-08-27 12:09:39 +0000296}
297
Nitesh Jain706c5202017-03-31 11:06:25 +0000298static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) {
299 const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH;
300 uint32_t endian = header.e_ident[EI_DATA];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000301 uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;
Nitesh Jain706c5202017-03-31 11:06:25 +0000302 uint32_t fileclass = header.e_ident[EI_CLASS];
303
Adrian Prantl05097242018-04-30 16:49:04 +0000304 // If there aren't any elf flags available (e.g core elf file) then return
305 // default
Nitesh Jain706c5202017-03-31 11:06:25 +0000306 // 32 or 64 bit arch (without any architecture revision) based on object file's class.
307 if (header.e_type == ET_CORE) {
308 switch (fileclass) {
309 case llvm::ELF::ELFCLASS32:
310 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
311 : ArchSpec::eMIPSSubType_mips32;
312 case llvm::ELF::ELFCLASS64:
313 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
314 : ArchSpec::eMIPSSubType_mips64;
315 default:
316 return arch_variant;
317 }
318 }
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000319
Kate Stoneb9c1b512016-09-06 20:57:50 +0000320 switch (mips_arch) {
321 case llvm::ELF::EF_MIPS_ARCH_1:
322 case llvm::ELF::EF_MIPS_ARCH_2:
323 case llvm::ELF::EF_MIPS_ARCH_32:
324 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
325 : ArchSpec::eMIPSSubType_mips32;
326 case llvm::ELF::EF_MIPS_ARCH_32R2:
327 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el
328 : ArchSpec::eMIPSSubType_mips32r2;
329 case llvm::ELF::EF_MIPS_ARCH_32R6:
330 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el
331 : ArchSpec::eMIPSSubType_mips32r6;
332 case llvm::ELF::EF_MIPS_ARCH_3:
333 case llvm::ELF::EF_MIPS_ARCH_4:
334 case llvm::ELF::EF_MIPS_ARCH_5:
335 case llvm::ELF::EF_MIPS_ARCH_64:
336 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
337 : ArchSpec::eMIPSSubType_mips64;
338 case llvm::ELF::EF_MIPS_ARCH_64R2:
339 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el
340 : ArchSpec::eMIPSSubType_mips64r2;
341 case llvm::ELF::EF_MIPS_ARCH_64R6:
342 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el
343 : ArchSpec::eMIPSSubType_mips64r6;
344 default:
345 break;
346 }
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000347
Kate Stoneb9c1b512016-09-06 20:57:50 +0000348 return arch_variant;
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000349}
350
Kate Stoneb9c1b512016-09-06 20:57:50 +0000351static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {
352 if (header.e_machine == llvm::ELF::EM_MIPS)
Nitesh Jain706c5202017-03-31 11:06:25 +0000353 return mipsVariantFromElfFlags(header);
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000354
Kate Stoneb9c1b512016-09-06 20:57:50 +0000355 return llvm::ELF::EM_CSR_KALIMBA == header.e_machine
356 ? kalimbaVariantFromElfFlags(header.e_flags)
357 : LLDB_INVALID_CPUTYPE;
Matthew Gardiner5f675792014-08-27 12:09:39 +0000358}
359
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000360//! The kalimba toolchain identifies a code section as being
361//! one with the SHT_PROGBITS set in the section sh_type and the top
362//! bit in the 32-bit address field set.
363static lldb::SectionType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000364kalimbaSectionType(const elf::ELFHeader &header,
365 const elf::ELFSectionHeader &sect_hdr) {
366 if (llvm::ELF::EM_CSR_KALIMBA != header.e_machine) {
Matthew Gardiner6e7b0a02014-10-15 08:21:54 +0000367 return eSectionTypeOther;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000368 }
369
370 if (llvm::ELF::SHT_NOBITS == sect_hdr.sh_type) {
371 return eSectionTypeZeroFill;
372 }
373
374 if (llvm::ELF::SHT_PROGBITS == sect_hdr.sh_type) {
375 const lldb::addr_t KAL_CODE_BIT = 1 << 31;
376 return KAL_CODE_BIT & sect_hdr.sh_addr ? eSectionTypeCode
377 : eSectionTypeData;
378 }
379
380 return eSectionTypeOther;
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000381}
382
Todd Fiala4339f3a2014-03-25 19:29:09 +0000383// Arbitrary constant used as UUID prefix for core files.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000384const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000385
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000386//------------------------------------------------------------------
387// Static methods.
388//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389void ObjectFileELF::Initialize() {
390 PluginManager::RegisterPlugin(GetPluginNameStatic(),
391 GetPluginDescriptionStatic(), CreateInstance,
392 CreateMemoryInstance, GetModuleSpecifications);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000393}
394
Kate Stoneb9c1b512016-09-06 20:57:50 +0000395void ObjectFileELF::Terminate() {
396 PluginManager::UnregisterPlugin(CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000397}
398
Kate Stoneb9c1b512016-09-06 20:57:50 +0000399lldb_private::ConstString ObjectFileELF::GetPluginNameStatic() {
400 static ConstString g_name("elf");
401 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000402}
403
Kate Stoneb9c1b512016-09-06 20:57:50 +0000404const char *ObjectFileELF::GetPluginDescriptionStatic() {
405 return "ELF object file reader.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000406}
407
Kate Stoneb9c1b512016-09-06 20:57:50 +0000408ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp,
409 DataBufferSP &data_sp,
410 lldb::offset_t data_offset,
411 const lldb_private::FileSpec *file,
412 lldb::offset_t file_offset,
413 lldb::offset_t length) {
414 if (!data_sp) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000415 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000416 if (!data_sp)
417 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000418 data_offset = 0;
419 }
420
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000421 assert(data_sp);
422
423 if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset))
424 return nullptr;
425
426 const uint8_t *magic = data_sp->GetBytes() + data_offset;
427 if (!ELFHeader::MagicBytesMatch(magic))
428 return nullptr;
429
430 // Update the data to contain the entire file if it doesn't already
431 if (data_sp->GetByteSize() < length) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000432 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000433 if (!data_sp)
434 return nullptr;
435 data_offset = 0;
436 magic = data_sp->GetBytes();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000437 }
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000438
439 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
440 if (address_size == 4 || address_size == 8) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000441 std::unique_ptr<ObjectFileELF> objfile_up(new ObjectFileELF(
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000442 module_sp, data_sp, data_offset, file, file_offset, length));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000443 ArchSpec spec = objfile_up->GetArchitecture();
444 if (spec && objfile_up->SetModulesArchitecture(spec))
445 return objfile_up.release();
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000446 }
447
Kate Stoneb9c1b512016-09-06 20:57:50 +0000448 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000449}
450
Kate Stoneb9c1b512016-09-06 20:57:50 +0000451ObjectFile *ObjectFileELF::CreateMemoryInstance(
452 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
453 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
454 if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) {
455 const uint8_t *magic = data_sp->GetBytes();
456 if (ELFHeader::MagicBytesMatch(magic)) {
457 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
458 if (address_size == 4 || address_size == 8) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000459 std::unique_ptr<ObjectFileELF> objfile_up(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000461 ArchSpec spec = objfile_up->GetArchitecture();
462 if (spec && objfile_up->SetModulesArchitecture(spec))
463 return objfile_up.release();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464 }
Andrew MacPherson17220c12014-03-05 10:12:43 +0000465 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000466 }
467 return NULL;
Greg Claytonc9660542012-02-05 02:38:54 +0000468}
469
Kate Stoneb9c1b512016-09-06 20:57:50 +0000470bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp,
471 lldb::addr_t data_offset,
472 lldb::addr_t data_length) {
473 if (data_sp &&
474 data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
475 const uint8_t *magic = data_sp->GetBytes() + data_offset;
476 return ELFHeader::MagicBytesMatch(magic);
477 }
478 return false;
Michael Sartain9f0013d2013-05-17 00:20:21 +0000479}
Greg Claytonc9660542012-02-05 02:38:54 +0000480
Michael Sartain9f4517a2013-07-03 01:52:14 +0000481/*
482 * crc function from http://svnweb.freebsd.org/base/head/sys/libkern/crc32.c
483 *
484 * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or
485 * code or tables extracted from it, as desired without restriction.
486 */
Kate Stoneb9c1b512016-09-06 20:57:50 +0000487static uint32_t calc_crc32(uint32_t crc, const void *buf, size_t size) {
488 static const uint32_t g_crc32_tab[] = {
489 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
490 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
491 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
492 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
493 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
494 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
495 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
496 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
497 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
498 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
499 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
500 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
501 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
502 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
503 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
504 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
505 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
506 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
507 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
508 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
509 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
510 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
511 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
512 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
513 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
514 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
515 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
516 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
517 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
518 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
519 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
520 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
521 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
522 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
523 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
524 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
525 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
526 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
527 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
528 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
529 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
530 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
531 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};
532 const uint8_t *p = (const uint8_t *)buf;
Michael Sartain9f4517a2013-07-03 01:52:14 +0000533
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534 crc = crc ^ ~0U;
535 while (size--)
536 crc = g_crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
537 return crc ^ ~0U;
Michael Sartain9f4517a2013-07-03 01:52:14 +0000538}
539
Kate Stoneb9c1b512016-09-06 20:57:50 +0000540static uint32_t calc_gnu_debuglink_crc32(const void *buf, size_t size) {
541 return calc_crc32(0U, buf, size);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000542}
543
Kate Stoneb9c1b512016-09-06 20:57:50 +0000544uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32(
545 const ProgramHeaderColl &program_headers, DataExtractor &object_data) {
Todd Fiala4339f3a2014-03-25 19:29:09 +0000546
Kate Stoneb9c1b512016-09-06 20:57:50 +0000547 uint32_t core_notes_crc = 0;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000548
Pavel Labath5ea7ecd2018-12-12 14:20:28 +0000549 for (const ELFProgramHeader &H : program_headers) {
550 if (H.p_type == llvm::ELF::PT_NOTE) {
551 const elf_off ph_offset = H.p_offset;
552 const size_t ph_size = H.p_filesz;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000553
Kate Stoneb9c1b512016-09-06 20:57:50 +0000554 DataExtractor segment_data;
555 if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {
Adrian Prantl05097242018-04-30 16:49:04 +0000556 // The ELF program header contained incorrect data, probably corefile
557 // is incomplete or corrupted.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 break;
559 }
Todd Fiala4339f3a2014-03-25 19:29:09 +0000560
Kate Stoneb9c1b512016-09-06 20:57:50 +0000561 core_notes_crc = calc_crc32(core_notes_crc, segment_data.GetDataStart(),
562 segment_data.GetByteSize());
Todd Fiala4339f3a2014-03-25 19:29:09 +0000563 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000564 }
Todd Fiala4339f3a2014-03-25 19:29:09 +0000565
Kate Stoneb9c1b512016-09-06 20:57:50 +0000566 return core_notes_crc;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000567}
568
Kate Stoneb9c1b512016-09-06 20:57:50 +0000569static const char *OSABIAsCString(unsigned char osabi_byte) {
570#define _MAKE_OSABI_CASE(x) \
571 case x: \
572 return #x
573 switch (osabi_byte) {
574 _MAKE_OSABI_CASE(ELFOSABI_NONE);
575 _MAKE_OSABI_CASE(ELFOSABI_HPUX);
576 _MAKE_OSABI_CASE(ELFOSABI_NETBSD);
577 _MAKE_OSABI_CASE(ELFOSABI_GNU);
578 _MAKE_OSABI_CASE(ELFOSABI_HURD);
579 _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);
580 _MAKE_OSABI_CASE(ELFOSABI_AIX);
581 _MAKE_OSABI_CASE(ELFOSABI_IRIX);
582 _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);
583 _MAKE_OSABI_CASE(ELFOSABI_TRU64);
584 _MAKE_OSABI_CASE(ELFOSABI_MODESTO);
585 _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);
586 _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);
587 _MAKE_OSABI_CASE(ELFOSABI_NSK);
588 _MAKE_OSABI_CASE(ELFOSABI_AROS);
589 _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);
590 _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);
591 _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);
592 _MAKE_OSABI_CASE(ELFOSABI_ARM);
593 _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);
594 default:
595 return "<unknown-osabi>";
596 }
Todd Fialab91de782014-06-27 16:52:49 +0000597#undef _MAKE_OSABI_CASE
598}
599
Ed Mastef6a13122015-06-05 13:03:08 +0000600//
601// WARNING : This function is being deprecated
Adrian Prantl05097242018-04-30 16:49:04 +0000602// It's functionality has moved to ArchSpec::SetArchitecture This function is
603// only being kept to validate the move.
Ed Mastef6a13122015-06-05 13:03:08 +0000604//
605// TODO : Remove this function
Kate Stoneb9c1b512016-09-06 20:57:50 +0000606static bool GetOsFromOSABI(unsigned char osabi_byte,
607 llvm::Triple::OSType &ostype) {
608 switch (osabi_byte) {
609 case ELFOSABI_AIX:
610 ostype = llvm::Triple::OSType::AIX;
611 break;
612 case ELFOSABI_FREEBSD:
613 ostype = llvm::Triple::OSType::FreeBSD;
614 break;
615 case ELFOSABI_GNU:
616 ostype = llvm::Triple::OSType::Linux;
617 break;
618 case ELFOSABI_NETBSD:
619 ostype = llvm::Triple::OSType::NetBSD;
620 break;
621 case ELFOSABI_OPENBSD:
622 ostype = llvm::Triple::OSType::OpenBSD;
623 break;
624 case ELFOSABI_SOLARIS:
625 ostype = llvm::Triple::OSType::Solaris;
626 break;
627 default:
628 ostype = llvm::Triple::OSType::UnknownOS;
629 }
630 return ostype != llvm::Triple::OSType::UnknownOS;
Todd Fialab91de782014-06-27 16:52:49 +0000631}
632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633size_t ObjectFileELF::GetModuleSpecifications(
634 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
635 lldb::offset_t data_offset, lldb::offset_t file_offset,
636 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
637 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
Todd Fialab91de782014-06-27 16:52:49 +0000638
Kate Stoneb9c1b512016-09-06 20:57:50 +0000639 const size_t initial_count = specs.GetSize();
Michael Sartainc836ae72013-05-23 20:57:03 +0000640
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
642 DataExtractor data;
643 data.SetData(data_sp);
644 elf::ELFHeader header;
Pavel Labath23ccc292017-01-31 23:09:46 +0000645 lldb::offset_t header_offset = data_offset;
646 if (header.Parse(data, &header_offset)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000647 if (data_sp) {
648 ModuleSpec spec(file);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000649
Kate Stoneb9c1b512016-09-06 20:57:50 +0000650 const uint32_t sub_type = subTypeFromElfHeader(header);
651 spec.GetArchitecture().SetArchitecture(
652 eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000653
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 if (spec.GetArchitecture().IsValid()) {
655 llvm::Triple::OSType ostype;
656 llvm::Triple::VendorType vendor;
657 llvm::Triple::OSType spec_ostype =
658 spec.GetArchitecture().GetTriple().getOS();
Todd Fialab91de782014-06-27 16:52:49 +0000659
Kate Stoneb9c1b512016-09-06 20:57:50 +0000660 if (log)
661 log->Printf("ObjectFileELF::%s file '%s' module OSABI: %s",
662 __FUNCTION__, file.GetPath().c_str(),
663 OSABIAsCString(header.e_ident[EI_OSABI]));
Ed Mastef6a13122015-06-05 13:03:08 +0000664
Kate Stoneb9c1b512016-09-06 20:57:50 +0000665 // SetArchitecture should have set the vendor to unknown
666 vendor = spec.GetArchitecture().GetTriple().getVendor();
667 assert(vendor == llvm::Triple::UnknownVendor);
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +0000668 UNUSED_IF_ASSERT_DISABLED(vendor);
Ed Mastef6a13122015-06-05 13:03:08 +0000669
Kate Stoneb9c1b512016-09-06 20:57:50 +0000670 //
671 // Validate it is ok to remove GetOsFromOSABI
672 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
673 assert(spec_ostype == ostype);
674 if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
675 if (log)
676 log->Printf("ObjectFileELF::%s file '%s' set ELF module OS type "
677 "from ELF header OSABI.",
678 __FUNCTION__, file.GetPath().c_str());
679 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000680
Pavel Labath4f033122018-02-05 17:25:40 +0000681 data_sp = MapFileData(file, -1, file_offset);
682 if (data_sp)
683 data.SetData(data_sp);
Adrian Prantl05097242018-04-30 16:49:04 +0000684 // In case there is header extension in the section #0, the header we
685 // parsed above could have sentinel values for e_phnum, e_shnum, and
686 // e_shstrndx. In this case we need to reparse the header with a
687 // bigger data source to get the actual values.
Pavel Labath4f033122018-02-05 17:25:40 +0000688 if (header.HasHeaderExtension()) {
689 lldb::offset_t header_offset = data_offset;
690 header.Parse(data, &header_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000691 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000692
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 uint32_t gnu_debuglink_crc = 0;
694 std::string gnu_debuglink_file;
695 SectionHeaderColl section_headers;
696 lldb_private::UUID &uuid = spec.GetUUID();
Michael Sartain9f4517a2013-07-03 01:52:14 +0000697
Pavel Labathdf1a0d12017-06-20 08:11:47 +0000698 GetSectionHeaderInfo(section_headers, data, header, uuid,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000699 gnu_debuglink_file, gnu_debuglink_crc,
700 spec.GetArchitecture());
Ravitheja Addepally15f89c42016-01-19 12:55:21 +0000701
Kate Stoneb9c1b512016-09-06 20:57:50 +0000702 llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
Todd Fialab91de782014-06-27 16:52:49 +0000703
Kate Stoneb9c1b512016-09-06 20:57:50 +0000704 if (log)
705 log->Printf("ObjectFileELF::%s file '%s' module set to triple: %s "
706 "(architecture %s)",
707 __FUNCTION__, file.GetPath().c_str(),
708 spec_triple.getTriple().c_str(),
709 spec.GetArchitecture().GetArchitectureName());
Todd Fialab91de782014-06-27 16:52:49 +0000710
Kate Stoneb9c1b512016-09-06 20:57:50 +0000711 if (!uuid.IsValid()) {
712 uint32_t core_notes_crc = 0;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000713
Kate Stoneb9c1b512016-09-06 20:57:50 +0000714 if (!gnu_debuglink_crc) {
Pavel Labathf9d16472017-05-15 13:02:37 +0000715 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000716 lldb_private::Timer scoped_timer(
Pavel Labathf9d16472017-05-15 13:02:37 +0000717 func_cat,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000718 "Calculating module crc32 %s with size %" PRIu64 " KiB",
719 file.GetLastPathComponent().AsCString(),
Jonas Devlieghere59b78bc2018-11-01 04:45:28 +0000720 (FileSystem::Instance().GetByteSize(file) - file_offset) /
721 1024);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000722
Kate Stoneb9c1b512016-09-06 20:57:50 +0000723 // For core files - which usually don't happen to have a
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000724 // gnu_debuglink, and are pretty bulky - calculating whole
725 // contents crc32 would be too much of luxury. Thus we will need
726 // to fallback to something simpler.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000727 if (header.e_type == llvm::ELF::ET_CORE) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000728 ProgramHeaderColl program_headers;
Pavel Labathdf1a0d12017-06-20 08:11:47 +0000729 GetProgramHeaderInfo(program_headers, data, header);
Michael Sartainc836ae72013-05-23 20:57:03 +0000730
Kate Stoneb9c1b512016-09-06 20:57:50 +0000731 core_notes_crc =
732 CalculateELFNotesSegmentsCRC32(program_headers, data);
733 } else {
Pavel Labath4f033122018-02-05 17:25:40 +0000734 gnu_debuglink_crc = calc_gnu_debuglink_crc32(
735 data.GetDataStart(), data.GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000736 }
737 }
Pavel Labath77c397f2018-06-29 11:20:29 +0000738 using u32le = llvm::support::ulittle32_t;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000739 if (gnu_debuglink_crc) {
740 // Use 4 bytes of crc from the .gnu_debuglink section.
Pavel Labath77c397f2018-06-29 11:20:29 +0000741 u32le data(gnu_debuglink_crc);
742 uuid = UUID::fromData(&data, sizeof(data));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 } else if (core_notes_crc) {
744 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
Adrian Prantl05097242018-04-30 16:49:04 +0000745 // it look different form .gnu_debuglink crc followed by 4 bytes
746 // of note segments crc.
Pavel Labath77c397f2018-06-29 11:20:29 +0000747 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
748 uuid = UUID::fromData(data, sizeof(data));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000749 }
750 }
751
752 specs.Append(spec);
753 }
754 }
755 }
756 }
757
758 return specs.GetSize() - initial_count;
Greg Claytonf4d6de62013-04-24 22:29:28 +0000759}
760
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000761//------------------------------------------------------------------
762// PluginInterface protocol
763//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000764lldb_private::ConstString ObjectFileELF::GetPluginName() {
765 return GetPluginNameStatic();
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000766}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000767
Kate Stoneb9c1b512016-09-06 20:57:50 +0000768uint32_t ObjectFileELF::GetPluginVersion() { return m_plugin_version; }
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000769//------------------------------------------------------------------
770// ObjectFile protocol
771//------------------------------------------------------------------
772
Kate Stoneb9c1b512016-09-06 20:57:50 +0000773ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
774 DataBufferSP &data_sp, lldb::offset_t data_offset,
775 const FileSpec *file, lldb::offset_t file_offset,
776 lldb::offset_t length)
777 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
778 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
779 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000780 m_filespec_up(), m_entry_point_address(), m_arch_spec() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000781 if (file)
782 m_file = *file;
783 ::memset(&m_header, 0, sizeof(m_header));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000784}
785
Kate Stoneb9c1b512016-09-06 20:57:50 +0000786ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
787 DataBufferSP &header_data_sp,
788 const lldb::ProcessSP &process_sp,
789 addr_t header_addr)
790 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
791 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
792 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000793 m_filespec_up(), m_entry_point_address(), m_arch_spec() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000794 ::memset(&m_header, 0, sizeof(m_header));
Andrew MacPherson17220c12014-03-05 10:12:43 +0000795}
796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797ObjectFileELF::~ObjectFileELF() {}
798
799bool ObjectFileELF::IsExecutable() const {
800 return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000801}
802
Kate Stoneb9c1b512016-09-06 20:57:50 +0000803bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
804 bool value_is_offset) {
805 ModuleSP module_sp = GetModule();
806 if (module_sp) {
807 size_t num_loaded_sections = 0;
808 SectionList *section_list = GetSectionList();
809 if (section_list) {
810 if (!value_is_offset) {
Pavel Labath976af432019-01-10 09:32:31 +0000811 addr_t base = GetBaseAddress().GetFileAddress();
812 if (base == LLDB_INVALID_ADDRESS)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000813 return false;
Pavel Labath976af432019-01-10 09:32:31 +0000814 value -= base;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000815 }
816
817 const size_t num_sections = section_list->GetSize();
818 size_t sect_idx = 0;
819
820 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +0000821 // Iterate through the object file sections to find all of the sections
822 // that have SHF_ALLOC in their flag bits.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000823 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
Pavel Labathf55aea72019-01-09 16:50:45 +0000824 if (section_sp->Test(SHF_ALLOC) ||
825 section_sp->GetType() == eSectionTypeContainer) {
Pavel Labathec03d7e2018-02-28 20:42:29 +0000826 lldb::addr_t load_addr = section_sp->GetFileAddress();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000827 // We don't want to update the load address of a section with type
828 // eSectionTypeAbsoluteAddress as they already have the absolute load
Adrian Prantl05097242018-04-30 16:49:04 +0000829 // address already specified
Kate Stoneb9c1b512016-09-06 20:57:50 +0000830 if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
831 load_addr += value;
832
833 // On 32-bit systems the load address have to fit into 4 bytes. The
Adrian Prantl05097242018-04-30 16:49:04 +0000834 // rest of the bytes are the overflow from the addition.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000835 if (GetAddressByteSize() == 4)
836 load_addr &= 0xFFFFFFFF;
837
838 if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
839 load_addr))
840 ++num_loaded_sections;
841 }
842 }
843 return num_loaded_sections > 0;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000844 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000845 }
846 return false;
847}
848
849ByteOrder ObjectFileELF::GetByteOrder() const {
850 if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
851 return eByteOrderBig;
852 if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
853 return eByteOrderLittle;
854 return eByteOrderInvalid;
855}
856
857uint32_t ObjectFileELF::GetAddressByteSize() const {
858 return m_data.GetAddressByteSize();
859}
860
861AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
862 Symtab *symtab = GetSymtab();
863 if (!symtab)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000864 return AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000865
Adrian Prantl05097242018-04-30 16:49:04 +0000866 // The address class is determined based on the symtab. Ask it from the
867 // object file what contains the symtab information.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000868 ObjectFile *symtab_objfile = symtab->GetObjectFile();
869 if (symtab_objfile != nullptr && symtab_objfile != this)
870 return symtab_objfile->GetAddressClass(file_addr);
871
872 auto res = ObjectFile::GetAddressClass(file_addr);
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000873 if (res != AddressClass::eCode)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000874 return res;
875
876 auto ub = m_address_class_map.upper_bound(file_addr);
877 if (ub == m_address_class_map.begin()) {
Adrian Prantl05097242018-04-30 16:49:04 +0000878 // No entry in the address class map before the address. Return default
879 // address class for an address in a code section.
Tatyana Krasnukha04803b32018-06-26 13:06:54 +0000880 return AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000881 }
882
883 // Move iterator to the address class entry preceding address
884 --ub;
885
886 return ub->second;
887}
888
889size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
Pavel Labath0d38e4f2018-12-18 15:56:45 +0000890 return std::distance(m_section_headers.begin(), I);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000891}
892
893size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
Pavel Labath0d38e4f2018-12-18 15:56:45 +0000894 return std::distance(m_section_headers.begin(), I);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000895}
896
897bool ObjectFileELF::ParseHeader() {
898 lldb::offset_t offset = 0;
Pavel Labathdf1a0d12017-06-20 08:11:47 +0000899 return m_header.Parse(m_data, &offset);
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000900}
901
Pavel Labathbd334ef2019-02-11 16:14:02 +0000902UUID ObjectFileELF::GetUUID() {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000903 // Need to parse the section list to get the UUIDs, so make sure that's been
904 // done.
905 if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
Pavel Labathbd334ef2019-02-11 16:14:02 +0000906 return UUID();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907
Pavel Labathbd334ef2019-02-11 16:14:02 +0000908 if (!m_uuid) {
909 using u32le = llvm::support::ulittle32_t;
910 if (GetType() == ObjectFile::eTypeCoreFile) {
911 uint32_t core_notes_crc = 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000912
Pavel Labathbd334ef2019-02-11 16:14:02 +0000913 if (!ParseProgramHeaders())
914 return UUID();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000915
Pavel Labathbd334ef2019-02-11 16:14:02 +0000916 core_notes_crc =
917 CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000918
Pavel Labathbd334ef2019-02-11 16:14:02 +0000919 if (core_notes_crc) {
920 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
921 // look different form .gnu_debuglink crc - followed by 4 bytes of note
922 // segments crc.
923 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
924 m_uuid = UUID::fromData(data, sizeof(data));
925 }
926 } else {
927 if (!m_gnu_debuglink_crc)
928 m_gnu_debuglink_crc = calc_gnu_debuglink_crc32(m_data.GetDataStart(),
929 m_data.GetByteSize());
930 if (m_gnu_debuglink_crc) {
931 // Use 4 bytes of crc from the .gnu_debuglink section.
932 u32le data(m_gnu_debuglink_crc);
933 m_uuid = UUID::fromData(&data, sizeof(data));
934 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000935 }
936 }
937
Pavel Labathbd334ef2019-02-11 16:14:02 +0000938 return m_uuid;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000939}
940
Kate Stoneb9c1b512016-09-06 20:57:50 +0000941lldb_private::FileSpecList ObjectFileELF::GetDebugSymbolFilePaths() {
942 FileSpecList file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000943
Kate Stoneb9c1b512016-09-06 20:57:50 +0000944 if (!m_gnu_debuglink_file.empty()) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000945 FileSpec file_spec(m_gnu_debuglink_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000946 file_spec_list.Append(file_spec);
947 }
948 return file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000949}
950
Kate Stoneb9c1b512016-09-06 20:57:50 +0000951uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
952 size_t num_modules = ParseDependentModules();
953 uint32_t num_specs = 0;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000954
Kate Stoneb9c1b512016-09-06 20:57:50 +0000955 for (unsigned i = 0; i < num_modules; ++i) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +0000956 if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i)))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957 num_specs++;
958 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000959
Kate Stoneb9c1b512016-09-06 20:57:50 +0000960 return num_specs;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000961}
962
Kate Stoneb9c1b512016-09-06 20:57:50 +0000963Address ObjectFileELF::GetImageInfoAddress(Target *target) {
964 if (!ParseDynamicSymbols())
Stephen Wilson2ab0a582011-01-15 00:08:44 +0000965 return Address();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966
967 SectionList *section_list = GetSectionList();
968 if (!section_list)
969 return Address();
970
971 // Find the SHT_DYNAMIC (.dynamic) section.
972 SectionSP dynsym_section_sp(
973 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
974 if (!dynsym_section_sp)
975 return Address();
976 assert(dynsym_section_sp->GetObjectFile() == this);
977
978 user_id_t dynsym_id = dynsym_section_sp->GetID();
979 const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
980 if (!dynsym_hdr)
981 return Address();
982
983 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
984 ELFDynamic &symbol = m_dynamic_symbols[i];
985
986 if (symbol.d_tag == DT_DEBUG) {
Adrian Prantl05097242018-04-30 16:49:04 +0000987 // Compute the offset as the number of previous entries plus the size of
988 // d_tag.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000989 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
990 return Address(dynsym_section_sp, offset);
991 }
992 // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
993 // exists in non-PIE.
994 else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
995 symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
996 target) {
997 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
998 addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
999 if (dyn_base == LLDB_INVALID_ADDRESS)
1000 return Address();
1001
Zachary Turner97206d52017-05-12 04:51:55 +00001002 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001003 if (symbol.d_tag == DT_MIPS_RLD_MAP) {
1004 // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
1005 Address addr;
1006 if (target->ReadPointerFromMemory(dyn_base + offset, false, error,
1007 addr))
1008 return addr;
1009 }
1010 if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
1011 // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
1012 // relative to the address of the tag.
1013 uint64_t rel_offset;
1014 rel_offset = target->ReadUnsignedIntegerFromMemory(
1015 dyn_base + offset, false, GetAddressByteSize(), UINT64_MAX, error);
1016 if (error.Success() && rel_offset != UINT64_MAX) {
1017 Address addr;
1018 addr_t debug_ptr_address =
1019 dyn_base + (offset - GetAddressByteSize()) + rel_offset;
1020 addr.SetOffset(debug_ptr_address);
1021 return addr;
1022 }
1023 }
1024 }
1025 }
1026
1027 return Address();
Stephen Wilson2ab0a582011-01-15 00:08:44 +00001028}
1029
Kate Stoneb9c1b512016-09-06 20:57:50 +00001030lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
1031 if (m_entry_point_address.IsValid())
Stephen Wilsond126c8c2011-03-08 04:12:15 +00001032 return m_entry_point_address;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001033
1034 if (!ParseHeader() || !IsExecutable())
1035 return m_entry_point_address;
1036
1037 SectionList *section_list = GetSectionList();
1038 addr_t offset = m_header.e_entry;
1039
1040 if (!section_list)
1041 m_entry_point_address.SetOffset(offset);
1042 else
1043 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
1044 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00001045}
1046
Pavel Labath976af432019-01-10 09:32:31 +00001047Address ObjectFileELF::GetBaseAddress() {
1048 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
1049 const ELFProgramHeader &H = EnumPHdr.value();
Pavel Labath43ddbc02019-01-11 10:18:40 +00001050 if (H.p_type != PT_LOAD)
Pavel Labath976af432019-01-10 09:32:31 +00001051 continue;
1052
1053 return Address(
1054 GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0);
1055 }
1056 return LLDB_INVALID_ADDRESS;
1057}
1058
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001059//----------------------------------------------------------------------
1060// ParseDependentModules
1061//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001062size_t ObjectFileELF::ParseDependentModules() {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001063 if (m_filespec_up)
1064 return m_filespec_up->GetSize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001065
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001066 m_filespec_up.reset(new FileSpecList());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001067
1068 if (!ParseSectionHeaders())
1069 return 0;
1070
1071 SectionList *section_list = GetSectionList();
1072 if (!section_list)
1073 return 0;
1074
1075 // Find the SHT_DYNAMIC section.
1076 Section *dynsym =
1077 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
1078 .get();
1079 if (!dynsym)
1080 return 0;
1081 assert(dynsym->GetObjectFile() == this);
1082
1083 const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
1084 if (!header)
1085 return 0;
1086 // sh_link: section header index of string table used by entries in the
1087 // section.
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001088 Section *dynstr = section_list->FindSectionByID(header->sh_link).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001089 if (!dynstr)
1090 return 0;
1091
1092 DataExtractor dynsym_data;
1093 DataExtractor dynstr_data;
1094 if (ReadSectionData(dynsym, dynsym_data) &&
1095 ReadSectionData(dynstr, dynstr_data)) {
1096 ELFDynamic symbol;
1097 const lldb::offset_t section_size = dynsym_data.GetByteSize();
1098 lldb::offset_t offset = 0;
1099
1100 // The only type of entries we are concerned with are tagged DT_NEEDED,
1101 // yielding the name of a required library.
1102 while (offset < section_size) {
1103 if (!symbol.Parse(dynsym_data, &offset))
1104 break;
1105
1106 if (symbol.d_tag != DT_NEEDED)
1107 continue;
1108
1109 uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
1110 const char *lib_name = dynstr_data.PeekCStr(str_index);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001111 FileSpec file_spec(lib_name);
1112 FileSystem::Instance().Resolve(file_spec);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001113 m_filespec_up->Append(file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001114 }
1115 }
1116
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001117 return m_filespec_up->GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001118}
1119
1120//----------------------------------------------------------------------
Todd Fiala4339f3a2014-03-25 19:29:09 +00001121// GetProgramHeaderInfo
1122//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001123size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001124 DataExtractor &object_data,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001125 const ELFHeader &header) {
1126 // We have already parsed the program headers
1127 if (!program_headers.empty())
Todd Fiala4339f3a2014-03-25 19:29:09 +00001128 return program_headers.size();
1129
Kate Stoneb9c1b512016-09-06 20:57:50 +00001130 // If there are no program headers to read we are done.
1131 if (header.e_phnum == 0)
1132 return 0;
1133
1134 program_headers.resize(header.e_phnum);
1135 if (program_headers.size() != header.e_phnum)
1136 return 0;
1137
1138 const size_t ph_size = header.e_phnum * header.e_phentsize;
1139 const elf_off ph_offset = header.e_phoff;
1140 DataExtractor data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001141 if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 return 0;
1143
1144 uint32_t idx;
1145 lldb::offset_t offset;
1146 for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001147 if (!program_headers[idx].Parse(data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001148 break;
1149 }
1150
1151 if (idx < program_headers.size())
1152 program_headers.resize(idx);
1153
1154 return program_headers.size();
Todd Fiala4339f3a2014-03-25 19:29:09 +00001155}
1156
1157//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001158// ParseProgramHeaders
1159//----------------------------------------------------------------------
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00001160bool ObjectFileELF::ParseProgramHeaders() {
1161 return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001162}
1163
Zachary Turner97206d52017-05-12 04:51:55 +00001164lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
1166 lldb_private::ArchSpec &arch_spec,
1167 lldb_private::UUID &uuid) {
1168 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
Zachary Turner97206d52017-05-12 04:51:55 +00001169 Status error;
Todd Fialab91de782014-06-27 16:52:49 +00001170
Kate Stoneb9c1b512016-09-06 20:57:50 +00001171 lldb::offset_t offset = 0;
Michael Sartainc836ae72013-05-23 20:57:03 +00001172
Kate Stoneb9c1b512016-09-06 20:57:50 +00001173 while (true) {
1174 // Parse the note header. If this fails, bail out.
1175 const lldb::offset_t note_offset = offset;
1176 ELFNote note = ELFNote();
1177 if (!note.Parse(data, &offset)) {
1178 // We're done.
1179 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001180 }
Todd Fialab91de782014-06-27 16:52:49 +00001181
Kate Stoneb9c1b512016-09-06 20:57:50 +00001182 if (log)
1183 log->Printf("ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1184 __FUNCTION__, note.n_name.c_str(), note.n_type);
1185
1186 // Process FreeBSD ELF notes.
1187 if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1188 (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
1189 (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
1190 // Pull out the min version info.
1191 uint32_t version_info;
1192 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1193 error.SetErrorString("failed to read FreeBSD ABI note payload");
1194 return error;
1195 }
1196
1197 // Convert the version info into a major/minor number.
1198 const uint32_t version_major = version_info / 100000;
1199 const uint32_t version_minor = (version_info / 1000) % 100;
1200
1201 char os_name[32];
1202 snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1203 version_major, version_minor);
1204
1205 // Set the elf OS version to FreeBSD. Also clear the vendor.
1206 arch_spec.GetTriple().setOSName(os_name);
1207 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1208
1209 if (log)
1210 log->Printf("ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1211 ".%" PRIu32,
1212 __FUNCTION__, version_major, version_minor,
1213 static_cast<uint32_t>(version_info % 1000));
1214 }
1215 // Process GNU ELF notes.
1216 else if (note.n_name == LLDB_NT_OWNER_GNU) {
1217 switch (note.n_type) {
1218 case LLDB_NT_GNU_ABI_TAG:
1219 if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1220 // Pull out the min OS version supporting the ABI.
1221 uint32_t version_info[4];
1222 if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1223 nullptr) {
1224 error.SetErrorString("failed to read GNU ABI note payload");
1225 return error;
1226 }
1227
1228 // Set the OS per the OS field.
1229 switch (version_info[0]) {
1230 case LLDB_NT_GNU_ABI_OS_LINUX:
1231 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1232 arch_spec.GetTriple().setVendor(
1233 llvm::Triple::VendorType::UnknownVendor);
1234 if (log)
1235 log->Printf(
1236 "ObjectFileELF::%s detected Linux, min version %" PRIu32
1237 ".%" PRIu32 ".%" PRIu32,
1238 __FUNCTION__, version_info[1], version_info[2],
1239 version_info[3]);
1240 // FIXME we have the minimal version number, we could be propagating
1241 // that. version_info[1] = OS Major, version_info[2] = OS Minor,
1242 // version_info[3] = Revision.
1243 break;
1244 case LLDB_NT_GNU_ABI_OS_HURD:
1245 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1246 arch_spec.GetTriple().setVendor(
1247 llvm::Triple::VendorType::UnknownVendor);
1248 if (log)
1249 log->Printf("ObjectFileELF::%s detected Hurd (unsupported), min "
1250 "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1251 __FUNCTION__, version_info[1], version_info[2],
1252 version_info[3]);
1253 break;
1254 case LLDB_NT_GNU_ABI_OS_SOLARIS:
1255 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1256 arch_spec.GetTriple().setVendor(
1257 llvm::Triple::VendorType::UnknownVendor);
1258 if (log)
1259 log->Printf(
1260 "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1261 ".%" PRIu32 ".%" PRIu32,
1262 __FUNCTION__, version_info[1], version_info[2],
1263 version_info[3]);
1264 break;
1265 default:
1266 if (log)
1267 log->Printf(
1268 "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1269 ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1270 __FUNCTION__, version_info[0], version_info[1],
1271 version_info[2], version_info[3]);
1272 break;
1273 }
1274 }
1275 break;
1276
1277 case LLDB_NT_GNU_BUILD_ID_TAG:
1278 // Only bother processing this if we don't already have the uuid set.
1279 if (!uuid.IsValid()) {
1280 // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
Pavel Labath77c397f2018-06-29 11:20:29 +00001281 // build-id of a different length. Accept it as long as it's at least
1282 // 4 bytes as it will be better than our own crc32.
1283 if (note.n_descsz >= 4) {
1284 if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
1285 // Save the build id as the UUID for the module.
1286 uuid = UUID::fromData(buf, note.n_descsz);
1287 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001288 error.SetErrorString("failed to read GNU_BUILD_ID note payload");
1289 return error;
1290 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001291 }
1292 }
1293 break;
1294 }
Nitesh Jain706c5202017-03-31 11:06:25 +00001295 if (arch_spec.IsMIPS() &&
1296 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
1297 // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
1298 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001299 }
Michal Gorny4f134fb2019-02-20 14:31:06 +00001300 // Process NetBSD ELF executables and shared libraries
Kate Stoneb9c1b512016-09-06 20:57:50 +00001301 else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
Michal Gorny4f134fb2019-02-20 14:31:06 +00001302 (note.n_type == LLDB_NT_NETBSD_IDENT_TAG) &&
1303 (note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ) &&
1304 (note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)) {
1305 // Pull out the version info.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001306 uint32_t version_info;
1307 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1308 error.SetErrorString("failed to read NetBSD ABI note payload");
1309 return error;
1310 }
Michal Gorny4f134fb2019-02-20 14:31:06 +00001311 // Convert the version info into a major/minor/patch number.
1312 // #define __NetBSD_Version__ MMmmrrpp00
1313 //
1314 // M = major version
1315 // m = minor version; a minor number of 99 indicates current.
1316 // r = 0 (since NetBSD 3.0 not used)
1317 // p = patchlevel
1318 const uint32_t version_major = version_info / 100000000;
1319 const uint32_t version_minor = (version_info % 100000000) / 1000000;
1320 const uint32_t version_patch = (version_info % 10000) / 100;
1321 // Set the elf OS version to NetBSD. Also clear the vendor.
1322 arch_spec.GetTriple().setOSName(
1323 llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,
1324 version_patch).str());
1325 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1326 }
1327 // Process NetBSD ELF core(5) notes
1328 else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&
1329 (note.n_type == LLDB_NT_NETBSD_PROCINFO)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001330 // 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);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001333 }
Kamil Rytarowski12801f12017-03-26 15:34:57 +00001334 // Process OpenBSD ELF notes.
1335 else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
1336 // Set the elf OS version to OpenBSD. Also clear the vendor.
1337 arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
1338 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1339 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001340 // Process CSR kalimba notes
1341 else if ((note.n_type == LLDB_NT_GNU_ABI_TAG) &&
1342 (note.n_name == LLDB_NT_OWNER_CSR)) {
1343 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1344 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::CSR);
1345
1346 // TODO At some point the description string could be processed.
Adrian Prantl05097242018-04-30 16:49:04 +00001347 // It could provide a steer towards the kalimba variant which this ELF
1348 // targets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001349 if (note.n_descsz) {
1350 const char *cstr =
1351 data.GetCStr(&offset, llvm::alignTo(note.n_descsz, 4));
1352 (void)cstr;
1353 }
1354 } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1355 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1356 arch_spec.GetTriple().setEnvironment(
1357 llvm::Triple::EnvironmentType::Android);
1358 } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1359 // This is sometimes found in core files and usually contains extended
1360 // register info
1361 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1362 } else if (note.n_name == LLDB_NT_OWNER_CORE) {
Adrian Prantl05097242018-04-30 16:49:04 +00001363 // Parse the NT_FILE to look for stuff in paths to shared libraries As
1364 // the contents look like this in a 64 bit ELF core file: count =
1365 // 0x000000000000000a (10) page_size = 0x0000000000001000 (4096) Index
1366 // start end file_ofs path =====
1367 // ------------------ ------------------ ------------------
1368 // ------------------------------------- [ 0] 0x0000000000400000
1369 // 0x0000000000401000 0x0000000000000000 /tmp/a.out [ 1]
1370 // 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out [
1371 // 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
Kate Stoneb9c1b512016-09-06 20:57:50 +00001372 // [ 3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000
Adrian Prantl05097242018-04-30 16:49:04 +00001373 // /lib/x86_64-linux-gnu/libc-2.19.so [ 4] 0x00007fa79cba8000
1374 // 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-
1375 // gnu/libc-2.19.so [ 5] 0x00007fa79cda7000 0x00007fa79cdab000
1376 // 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so [ 6]
1377 // 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64
1378 // -linux-gnu/libc-2.19.so [ 7] 0x00007fa79cdb2000 0x00007fa79cdd5000
1379 // 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so [ 8]
1380 // 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64
1381 // -linux-gnu/ld-2.19.so [ 9] 0x00007fa79cfd5000 0x00007fa79cfd6000
1382 // 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so In the 32 bit ELFs
1383 // the count, page_size, start, end, file_ofs are uint32_t For reference:
1384 // see readelf source code (in binutils).
Kate Stoneb9c1b512016-09-06 20:57:50 +00001385 if (note.n_type == NT_FILE) {
1386 uint64_t count = data.GetAddress(&offset);
1387 const char *cstr;
1388 data.GetAddress(&offset); // Skip page size
1389 offset += count * 3 *
1390 data.GetAddressByteSize(); // Skip all start/end/file_ofs
1391 for (size_t i = 0; i < count; ++i) {
1392 cstr = data.GetCStr(&offset);
1393 if (cstr == nullptr) {
1394 error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
1395 "at an offset after the end "
1396 "(GetCStr returned nullptr)",
1397 __FUNCTION__);
1398 return error;
1399 }
1400 llvm::StringRef path(cstr);
Richard Chamberlaina0c82e12016-10-13 12:11:00 +00001401 if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1403 break;
1404 }
1405 }
Nitesh Jain706c5202017-03-31 11:06:25 +00001406 if (arch_spec.IsMIPS() &&
1407 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
Adrian Prantl05097242018-04-30 16:49:04 +00001408 // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
1409 // cases (e.g. compile with -nostdlib) Hence set OS to Linux
Leonard Mosescu9ba51572018-08-07 18:00:30 +00001410 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001411 }
1412 }
1413
Adrian Prantl05097242018-04-30 16:49:04 +00001414 // Calculate the offset of the next note just in case "offset" has been
1415 // used to poke at the contents of the note data
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416 offset = note_offset + note.GetByteSize();
1417 }
1418
1419 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001420}
Michael Sartaina7499c92013-07-01 19:45:50 +00001421
Kate Stoneb9c1b512016-09-06 20:57:50 +00001422void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
1423 ArchSpec &arch_spec) {
1424 lldb::offset_t Offset = 0;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001425
Kate Stoneb9c1b512016-09-06 20:57:50 +00001426 uint8_t FormatVersion = data.GetU8(&Offset);
1427 if (FormatVersion != llvm::ARMBuildAttrs::Format_Version)
1428 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001429
Kate Stoneb9c1b512016-09-06 20:57:50 +00001430 Offset = Offset + sizeof(uint32_t); // Section Length
1431 llvm::StringRef VendorName = data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001432
Kate Stoneb9c1b512016-09-06 20:57:50 +00001433 if (VendorName != "aeabi")
1434 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001435
Kate Stoneb9c1b512016-09-06 20:57:50 +00001436 if (arch_spec.GetTriple().getEnvironment() ==
1437 llvm::Triple::UnknownEnvironment)
1438 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001439
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 while (Offset < length) {
1441 uint8_t Tag = data.GetU8(&Offset);
1442 uint32_t Size = data.GetU32(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001443
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1445 continue;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001446
Kate Stoneb9c1b512016-09-06 20:57:50 +00001447 while (Offset < length) {
1448 uint64_t Tag = data.GetULEB128(&Offset);
1449 switch (Tag) {
1450 default:
1451 if (Tag < 32)
1452 data.GetULEB128(&Offset);
1453 else if (Tag % 2 == 0)
1454 data.GetULEB128(&Offset);
1455 else
1456 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001457
Kate Stoneb9c1b512016-09-06 20:57:50 +00001458 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001459
Kate Stoneb9c1b512016-09-06 20:57:50 +00001460 case llvm::ARMBuildAttrs::CPU_raw_name:
1461 case llvm::ARMBuildAttrs::CPU_name:
1462 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001463
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001465
Kate Stoneb9c1b512016-09-06 20:57:50 +00001466 case llvm::ARMBuildAttrs::ABI_VFP_args: {
1467 uint64_t VFPArgs = data.GetULEB128(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001468
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1470 if (arch_spec.GetTriple().getEnvironment() ==
1471 llvm::Triple::UnknownEnvironment ||
1472 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1473 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001474
Kate Stoneb9c1b512016-09-06 20:57:50 +00001475 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1476 } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1477 if (arch_spec.GetTriple().getEnvironment() ==
1478 llvm::Triple::UnknownEnvironment ||
1479 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1480 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001481
Kate Stoneb9c1b512016-09-06 20:57:50 +00001482 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001483 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001484
1485 break;
1486 }
1487 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001488 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001489 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001490}
Todd Fialab91de782014-06-27 16:52:49 +00001491
Michael Sartaina7499c92013-07-01 19:45:50 +00001492//----------------------------------------------------------------------
1493// GetSectionHeaderInfo
1494//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001495size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001496 DataExtractor &object_data,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001497 const elf::ELFHeader &header,
1498 lldb_private::UUID &uuid,
1499 std::string &gnu_debuglink_file,
1500 uint32_t &gnu_debuglink_crc,
1501 ArchSpec &arch_spec) {
1502 // Don't reparse the section headers if we already did that.
1503 if (!section_headers.empty())
1504 return section_headers.size();
Todd Fiala6477ea82014-07-11 15:13:33 +00001505
Kate Stoneb9c1b512016-09-06 20:57:50 +00001506 // Only initialize the arch_spec to okay defaults if they're not already set.
1507 // We'll refine this with note data as we parse the notes.
1508 if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1509 llvm::Triple::OSType ostype;
1510 llvm::Triple::OSType spec_ostype;
1511 const uint32_t sub_type = subTypeFromElfHeader(header);
1512 arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1513 header.e_ident[EI_OSABI]);
Leonard Mosescu9ba51572018-08-07 18:00:30 +00001514
Adrian Prantl05097242018-04-30 16:49:04 +00001515 // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
1516 // determined based on EI_OSABI flag and the info extracted from ELF notes
1517 // (see RefineModuleDetailsFromNote). However in some cases that still
1518 // might be not enough: for example a shared library might not have any
1519 // notes at all and have EI_OSABI flag set to System V, as result the OS
1520 // will be set to UnknownOS.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001521 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1522 spec_ostype = arch_spec.GetTriple().getOS();
1523 assert(spec_ostype == ostype);
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001524 UNUSED_IF_ASSERT_DISABLED(spec_ostype);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001525 }
1526
1527 if (arch_spec.GetMachine() == llvm::Triple::mips ||
1528 arch_spec.GetMachine() == llvm::Triple::mipsel ||
1529 arch_spec.GetMachine() == llvm::Triple::mips64 ||
1530 arch_spec.GetMachine() == llvm::Triple::mips64el) {
1531 switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1532 case llvm::ELF::EF_MIPS_MICROMIPS:
1533 arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
1534 break;
1535 case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1536 arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
1537 break;
1538 case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1539 arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
1540 break;
1541 default:
1542 break;
Todd Fialab91de782014-06-27 16:52:49 +00001543 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001544 }
Todd Fialab91de782014-06-27 16:52:49 +00001545
Kate Stoneb9c1b512016-09-06 20:57:50 +00001546 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1547 arch_spec.GetMachine() == llvm::Triple::thumb) {
1548 if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1549 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1550 else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1551 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1552 }
Jaydeep Patil501a7812015-07-16 03:51:55 +00001553
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554 // If there are no section headers we are done.
1555 if (header.e_shnum == 0)
Michael Sartaina7499c92013-07-01 19:45:50 +00001556 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001557
1558 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1559
1560 section_headers.resize(header.e_shnum);
1561 if (section_headers.size() != header.e_shnum)
1562 return 0;
1563
1564 const size_t sh_size = header.e_shnum * header.e_shentsize;
1565 const elf_off sh_offset = header.e_shoff;
1566 DataExtractor sh_data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001567 if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001568 return 0;
1569
1570 uint32_t idx;
1571 lldb::offset_t offset;
1572 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001573 if (!section_headers[idx].Parse(sh_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001574 break;
1575 }
1576 if (idx < section_headers.size())
1577 section_headers.resize(idx);
1578
1579 const unsigned strtab_idx = header.e_shstrndx;
1580 if (strtab_idx && strtab_idx < section_headers.size()) {
1581 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1582 const size_t byte_size = sheader.sh_size;
1583 const Elf64_Off offset = sheader.sh_offset;
1584 lldb_private::DataExtractor shstr_data;
1585
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001586 if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001587 for (SectionHeaderCollIter I = section_headers.begin();
1588 I != section_headers.end(); ++I) {
1589 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1590 const ELFSectionHeaderInfo &sheader = *I;
1591 const uint64_t section_size =
1592 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1593 ConstString name(shstr_data.PeekCStr(I->sh_name));
1594
1595 I->section_name = name;
1596
1597 if (arch_spec.IsMIPS()) {
1598 uint32_t arch_flags = arch_spec.GetFlags();
1599 DataExtractor data;
1600 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1601
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001602 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1603 section_size) == section_size)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001604 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1605 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1606 arch_flags |= data.GetU32(&offset);
1607
1608 // The floating point ABI is at offset 7
1609 offset = 7;
1610 switch (data.GetU8(&offset)) {
1611 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1612 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
1613 break;
1614 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1615 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
1616 break;
1617 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1618 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
1619 break;
1620 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1621 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
1622 break;
1623 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1624 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
1625 break;
1626 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1627 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
1628 break;
1629 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1630 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
1631 break;
1632 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1633 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
1634 break;
1635 }
1636 }
1637 }
1638 // Settings appropriate ArchSpec ABI Flags
1639 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1640 case llvm::ELF::EF_MIPS_ABI_O32:
1641 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
1642 break;
1643 case EF_MIPS_ABI_O64:
1644 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
1645 break;
1646 case EF_MIPS_ABI_EABI32:
1647 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
1648 break;
1649 case EF_MIPS_ABI_EABI64:
1650 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
1651 break;
1652 default:
1653 // ABI Mask doesn't cover N32 and N64 ABI.
1654 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1655 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
Mehdi Aminid16a6e32017-06-23 18:20:13 +00001656 else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001657 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
1658 break;
1659 }
1660 arch_spec.SetFlags(arch_flags);
1661 }
1662
1663 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1664 arch_spec.GetMachine() == llvm::Triple::thumb) {
1665 DataExtractor data;
1666
1667 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001668 data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001669 ParseARMAttributes(data, section_size, arch_spec);
1670 }
1671
1672 if (name == g_sect_name_gnu_debuglink) {
1673 DataExtractor data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001674 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1675 section_size) == section_size)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001676 lldb::offset_t gnu_debuglink_offset = 0;
1677 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1678 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1679 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1680 }
1681 }
1682
1683 // Process ELF note section entries.
1684 bool is_note_header = (sheader.sh_type == SHT_NOTE);
1685
1686 // The section header ".note.android.ident" is stored as a
1687 // PROGBITS type header but it is actually a note header.
1688 static ConstString g_sect_name_android_ident(".note.android.ident");
1689 if (!is_note_header && name == g_sect_name_android_ident)
1690 is_note_header = true;
1691
1692 if (is_note_header) {
1693 // Allow notes to refine module info.
1694 DataExtractor data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001695 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1696 section_size) == section_size)) {
Zachary Turner97206d52017-05-12 04:51:55 +00001697 Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001698 if (error.Fail()) {
1699 if (log)
1700 log->Printf("ObjectFileELF::%s ELF note processing failed: %s",
1701 __FUNCTION__, error.AsCString());
1702 }
1703 }
1704 }
1705 }
1706
1707 // Make any unknown triple components to be unspecified unknowns.
1708 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1709 arch_spec.GetTriple().setVendorName(llvm::StringRef());
1710 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1711 arch_spec.GetTriple().setOSName(llvm::StringRef());
1712
1713 return section_headers.size();
1714 }
1715 }
1716
1717 section_headers.clear();
1718 return 0;
Michael Sartaina7499c92013-07-01 19:45:50 +00001719}
1720
Pavel Labath4d35d6b2017-05-02 10:17:30 +00001721llvm::StringRef
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1723 size_t pos = symbol_name.find('@');
Pavel Labath4d35d6b2017-05-02 10:17:30 +00001724 return symbol_name.substr(0, pos);
Pavel Labathc6ae7ea2015-03-04 10:25:22 +00001725}
1726
Michael Sartaina7499c92013-07-01 19:45:50 +00001727//----------------------------------------------------------------------
1728// ParseSectionHeaders
1729//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730size_t ObjectFileELF::ParseSectionHeaders() {
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001731 return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid,
1732 m_gnu_debuglink_file, m_gnu_debuglink_crc,
1733 m_arch_spec);
Michael Sartaina7499c92013-07-01 19:45:50 +00001734}
1735
Michael Sartaina7499c92013-07-01 19:45:50 +00001736const ObjectFileELF::ELFSectionHeaderInfo *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001737ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001738 if (!ParseSectionHeaders())
Michael Sartaina7499c92013-07-01 19:45:50 +00001739 return NULL;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001740
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001741 if (id < m_section_headers.size())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001742 return &m_section_headers[id];
1743
1744 return NULL;
Michael Sartaina7499c92013-07-01 19:45:50 +00001745}
1746
Kate Stoneb9c1b512016-09-06 20:57:50 +00001747lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
1748 if (!name || !name[0] || !ParseSectionHeaders())
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001749 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001750 for (size_t i = 1; i < m_section_headers.size(); ++i)
1751 if (m_section_headers[i].section_name == ConstString(name))
1752 return i;
1753 return 0;
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001754}
1755
Pavel Labath62a82542018-12-15 13:45:38 +00001756static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
Pavel Labathef8683a2018-12-12 15:46:18 +00001757 return llvm::StringSwitch<SectionType>(Name)
1758 .Case(".ARM.exidx", eSectionTypeARMexidx)
1759 .Case(".ARM.extab", eSectionTypeARMextab)
1760 .Cases(".bss", ".tbss", eSectionTypeZeroFill)
1761 .Cases(".data", ".tdata", eSectionTypeData)
1762 .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
1763 .Case(".debug_abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo)
1764 .Case(".debug_addr", eSectionTypeDWARFDebugAddr)
1765 .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
1766 .Case(".debug_cu_index", eSectionTypeDWARFDebugCuIndex)
1767 .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
1768 .Case(".debug_info", eSectionTypeDWARFDebugInfo)
1769 .Case(".debug_info.dwo", eSectionTypeDWARFDebugInfoDwo)
1770 .Cases(".debug_line", ".debug_line.dwo", eSectionTypeDWARFDebugLine)
1771 .Cases(".debug_line_str", ".debug_line_str.dwo",
1772 eSectionTypeDWARFDebugLineStr)
1773 .Cases(".debug_loc", ".debug_loc.dwo", eSectionTypeDWARFDebugLoc)
1774 .Cases(".debug_loclists", ".debug_loclists.dwo",
1775 eSectionTypeDWARFDebugLocLists)
1776 .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
1777 .Cases(".debug_macro", ".debug_macro.dwo", eSectionTypeDWARFDebugMacro)
1778 .Case(".debug_names", eSectionTypeDWARFDebugNames)
1779 .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
1780 .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
1781 .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
1782 .Case(".debug_rnglists", eSectionTypeDWARFDebugRngLists)
1783 .Case(".debug_str", eSectionTypeDWARFDebugStr)
1784 .Case(".debug_str.dwo", eSectionTypeDWARFDebugStrDwo)
1785 .Case(".debug_str_offsets", eSectionTypeDWARFDebugStrOffsets)
1786 .Case(".debug_str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo)
1787 .Case(".debug_types", eSectionTypeDWARFDebugTypes)
1788 .Case(".eh_frame", eSectionTypeEHFrame)
1789 .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
1790 .Case(".gosymtab", eSectionTypeGoSymtab)
1791 .Case(".text", eSectionTypeCode)
1792 .Default(eSectionTypeOther);
1793}
1794
Pavel Labath62a82542018-12-15 13:45:38 +00001795SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const {
1796 switch (H.sh_type) {
1797 case SHT_PROGBITS:
1798 if (H.sh_flags & SHF_EXECINSTR)
1799 return eSectionTypeCode;
1800 break;
1801 case SHT_SYMTAB:
1802 return eSectionTypeELFSymbolTable;
1803 case SHT_DYNSYM:
1804 return eSectionTypeELFDynamicSymbols;
1805 case SHT_RELA:
1806 case SHT_REL:
1807 return eSectionTypeELFRelocationEntries;
1808 case SHT_DYNAMIC:
1809 return eSectionTypeELFDynamicLinkInfo;
1810 }
1811 SectionType Type = GetSectionTypeFromName(H.section_name.GetStringRef());
1812 if (Type == eSectionTypeOther) {
1813 // the kalimba toolchain assumes that ELF section names are free-form.
1814 // It does support linkscripts which (can) give rise to various
1815 // arbitrarily named sections being "Code" or "Data".
1816 Type = kalimbaSectionType(m_header, H);
1817 }
1818 return Type;
1819}
1820
1821static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {
1822 switch (Type) {
1823 case eSectionTypeData:
1824 case eSectionTypeZeroFill:
1825 return arch.GetDataByteSize();
1826 case eSectionTypeCode:
1827 return arch.GetCodeByteSize();
1828 default:
1829 return 1;
1830 }
1831}
1832
1833static Permissions GetPermissions(const ELFSectionHeader &H) {
1834 Permissions Perm = Permissions(0);
1835 if (H.sh_flags & SHF_ALLOC)
1836 Perm |= ePermissionsReadable;
1837 if (H.sh_flags & SHF_WRITE)
1838 Perm |= ePermissionsWritable;
1839 if (H.sh_flags & SHF_EXECINSTR)
1840 Perm |= ePermissionsExecutable;
1841 return Perm;
1842}
1843
Pavel Labathf55aea72019-01-09 16:50:45 +00001844static Permissions GetPermissions(const ELFProgramHeader &H) {
1845 Permissions Perm = Permissions(0);
1846 if (H.p_flags & PF_R)
1847 Perm |= ePermissionsReadable;
1848 if (H.p_flags & PF_W)
1849 Perm |= ePermissionsWritable;
1850 if (H.p_flags & PF_X)
1851 Perm |= ePermissionsExecutable;
1852 return Perm;
1853}
1854
Pavel Labath62a82542018-12-15 13:45:38 +00001855namespace {
Pavel Labathf55aea72019-01-09 16:50:45 +00001856
1857using VMRange = lldb_private::Range<addr_t, addr_t>;
1858
1859struct SectionAddressInfo {
1860 SectionSP Segment;
1861 VMRange Range;
1862};
1863
Pavel Labath62a82542018-12-15 13:45:38 +00001864// (Unlinked) ELF object files usually have 0 for every section address, meaning
1865// we need to compute synthetic addresses in order for "file addresses" from
1866// different sections to not overlap. This class handles that logic.
1867class VMAddressProvider {
Pavel Labathf55aea72019-01-09 16:50:45 +00001868 using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
1869 llvm::IntervalMapHalfOpenInfo<addr_t>>;
1870
1871 ObjectFile::Type ObjectType;
1872 addr_t NextVMAddress = 0;
1873 VMMap::Allocator Alloc;
1874 VMMap Segments = VMMap(Alloc);
1875 VMMap Sections = VMMap(Alloc);
1876 lldb_private::Log *Log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES);
1877
1878 VMRange GetVMRange(const ELFSectionHeader &H) {
1879 addr_t Address = H.sh_addr;
1880 addr_t Size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
1881 if (ObjectType == ObjectFile::Type::eTypeObjectFile && Segments.empty() && (H.sh_flags & SHF_ALLOC)) {
1882 NextVMAddress =
1883 llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
1884 Address = NextVMAddress;
1885 NextVMAddress += Size;
1886 }
1887 return VMRange(Address, Size);
1888 }
Pavel Labath62a82542018-12-15 13:45:38 +00001889
1890public:
Pavel Labathf55aea72019-01-09 16:50:45 +00001891 VMAddressProvider(ObjectFile::Type Type) : ObjectType(Type) {}
Pavel Labath62a82542018-12-15 13:45:38 +00001892
Pavel Labathf55aea72019-01-09 16:50:45 +00001893 llvm::Optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
1894 if (H.p_memsz == 0) {
1895 LLDB_LOG(Log,
1896 "Ignoring zero-sized PT_LOAD segment. Corrupt object file?");
1897 return llvm::None;
Pavel Labath62a82542018-12-15 13:45:38 +00001898 }
Pavel Labathf55aea72019-01-09 16:50:45 +00001899
1900 if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
1901 LLDB_LOG(Log,
1902 "Ignoring overlapping PT_LOAD segment. Corrupt object file?");
1903 return llvm::None;
1904 }
1905 return VMRange(H.p_vaddr, H.p_memsz);
1906 }
1907
1908 llvm::Optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
1909 VMRange Range = GetVMRange(H);
1910 SectionSP Segment;
1911 auto It = Segments.find(Range.GetRangeBase());
1912 if ((H.sh_flags & SHF_ALLOC) && It.valid()) {
1913 addr_t MaxSize;
1914 if (It.start() <= Range.GetRangeBase()) {
1915 MaxSize = It.stop() - Range.GetRangeBase();
1916 Segment = *It;
1917 } else
1918 MaxSize = It.start() - Range.GetRangeBase();
1919 if (Range.GetByteSize() > MaxSize) {
1920 LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
1921 "Corrupt object file?");
1922 Range.SetByteSize(MaxSize);
1923 }
1924 }
1925 if (Range.GetByteSize() > 0 &&
1926 Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())) {
1927 LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
1928 return llvm::None;
1929 }
1930 if (Segment)
1931 Range.Slide(-Segment->GetFileAddress());
1932 return SectionAddressInfo{Segment, Range};
1933 }
1934
1935 void AddSegment(const VMRange &Range, SectionSP Seg) {
1936 Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
1937 }
1938
1939 void AddSection(SectionAddressInfo Info, SectionSP Sect) {
1940 if (Info.Range.GetByteSize() == 0)
1941 return;
1942 if (Info.Segment)
1943 Info.Range.Slide(Info.Segment->GetFileAddress());
1944 Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
1945 std::move(Sect));
Pavel Labath62a82542018-12-15 13:45:38 +00001946 }
1947};
1948}
1949
Kate Stoneb9c1b512016-09-06 20:57:50 +00001950void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001951 if (m_sections_up)
Pavel Labathf55aea72019-01-09 16:50:45 +00001952 return;
Andrew MacPherson17220c12014-03-05 10:12:43 +00001953
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001954 m_sections_up = llvm::make_unique<SectionList>();
Pavel Labathf55aea72019-01-09 16:50:45 +00001955 VMAddressProvider address_provider(CalculateType());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001956
Pavel Labathf55aea72019-01-09 16:50:45 +00001957 size_t LoadID = 0;
1958 for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
1959 const ELFProgramHeader &PHdr = EnumPHdr.value();
1960 if (PHdr.p_type != PT_LOAD)
1961 continue;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001962
Pavel Labathf55aea72019-01-09 16:50:45 +00001963 auto InfoOr = address_provider.GetAddressInfo(PHdr);
1964 if (!InfoOr)
1965 continue;
Davide Italiano1e6a01f2018-05-12 01:25:48 +00001966
Pavel Labathf55aea72019-01-09 16:50:45 +00001967 ConstString Name(("PT_LOAD[" + llvm::Twine(LoadID++) + "]").str());
1968 uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
1969 SectionSP Segment = std::make_shared<Section>(
1970 GetModule(), this, SegmentID(EnumPHdr.index()), Name,
1971 eSectionTypeContainer, InfoOr->GetRangeBase(), InfoOr->GetByteSize(),
1972 PHdr.p_offset, PHdr.p_filesz, Log2Align, /*flags*/ 0);
1973 Segment->SetPermissions(GetPermissions(PHdr));
Jonas Devlieghered5b44032019-02-13 06:25:41 +00001974 m_sections_up->AddSection(Segment);
Pavel Labathedb01272018-04-30 13:23:47 +00001975
Pavel Labathf55aea72019-01-09 16:50:45 +00001976 address_provider.AddSegment(*InfoOr, std::move(Segment));
1977 }
Pavel Labath62a82542018-12-15 13:45:38 +00001978
Pavel Labathf55aea72019-01-09 16:50:45 +00001979 ParseSectionHeaders();
1980 if (m_section_headers.empty())
1981 return;
Ed Masted13f6912017-10-02 14:35:07 +00001982
Pavel Labathf55aea72019-01-09 16:50:45 +00001983 for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
1984 I != m_section_headers.end(); ++I) {
1985 const ELFSectionHeaderInfo &header = *I;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001986
Pavel Labathf55aea72019-01-09 16:50:45 +00001987 ConstString &name = I->section_name;
1988 const uint64_t file_size =
1989 header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
1990
1991 auto InfoOr = address_provider.GetAddressInfo(header);
1992 if (!InfoOr)
1993 continue;
1994
1995 SectionType sect_type = GetSectionType(header);
1996
1997 const uint32_t target_bytes_size =
1998 GetTargetByteSize(sect_type, m_arch_spec);
1999
2000 elf::elf_xword log2align =
2001 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
2002
2003 SectionSP section_sp(new Section(
2004 InfoOr->Segment, GetModule(), // Module to which this section belongs.
2005 this, // ObjectFile to which this section belongs and should
2006 // read section data from.
2007 SectionIndex(I), // Section ID.
2008 name, // Section name.
2009 sect_type, // Section type.
2010 InfoOr->Range.GetRangeBase(), // VM address.
2011 InfoOr->Range.GetByteSize(), // VM size in bytes of this section.
2012 header.sh_offset, // Offset of this section in the file.
2013 file_size, // Size of the section as found in the file.
2014 log2align, // Alignment of the section
2015 header.sh_flags, // Flags for this section.
2016 target_bytes_size)); // Number of host bytes per target byte
2017
2018 section_sp->SetPermissions(GetPermissions(header));
2019 section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002020 (InfoOr->Segment ? InfoOr->Segment->GetChildren() : *m_sections_up)
Pavel Labathf55aea72019-01-09 16:50:45 +00002021 .AddSection(section_sp);
2022 address_provider.AddSection(std::move(*InfoOr), std::move(section_sp));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002023 }
2024
Pavel Labath3ef4eeb2018-03-09 12:30:09 +00002025 // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the
2026 // unified section list.
2027 if (GetType() != eTypeDebugInfo)
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002028 unified_section_list = *m_sections_up;
Greg Clayton3046e662013-07-10 01:23:25 +00002029}
2030
Kate Stoneb9c1b512016-09-06 20:57:50 +00002031// Find the arm/aarch64 mapping symbol character in the given symbol name.
Adrian Prantl05097242018-04-30 16:49:04 +00002032// Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
2033// recognize cases when the mapping symbol prefixed by an arbitrary string
2034// because if a symbol prefix added to each symbol in the object file with
Kate Stoneb9c1b512016-09-06 20:57:50 +00002035// objcopy then the mapping symbols are also prefixed.
2036static char FindArmAarch64MappingSymbol(const char *symbol_name) {
2037 if (!symbol_name)
2038 return '\0';
2039
2040 const char *dollar_pos = ::strchr(symbol_name, '$');
2041 if (!dollar_pos || dollar_pos[1] == '\0')
2042 return '\0';
2043
2044 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
2045 return dollar_pos[1];
2046 return '\0';
2047}
2048
2049#define STO_MIPS_ISA (3 << 6)
2050#define STO_MICROMIPS (2 << 6)
2051#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
2052
2053// private
2054unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
2055 SectionList *section_list,
2056 const size_t num_symbols,
2057 const DataExtractor &symtab_data,
2058 const DataExtractor &strtab_data) {
2059 ELFSymbol symbol;
2060 lldb::offset_t offset = 0;
2061
2062 static ConstString text_section_name(".text");
2063 static ConstString init_section_name(".init");
2064 static ConstString fini_section_name(".fini");
2065 static ConstString ctors_section_name(".ctors");
2066 static ConstString dtors_section_name(".dtors");
2067
2068 static ConstString data_section_name(".data");
2069 static ConstString rodata_section_name(".rodata");
2070 static ConstString rodata1_section_name(".rodata1");
2071 static ConstString data2_section_name(".data1");
2072 static ConstString bss_section_name(".bss");
2073 static ConstString opd_section_name(".opd"); // For ppc64
2074
2075 // On Android the oatdata and the oatexec symbols in the oat and odex files
Adrian Prantl05097242018-04-30 16:49:04 +00002076 // covers the full .text section what causes issues with displaying unusable
2077 // symbol name to the user and very slow unwinding speed because the
2078 // instruction emulation based unwind plans try to emulate all instructions
2079 // in these symbols. Don't add these symbols to the symbol list as they have
2080 // no use for the debugger and they are causing a lot of trouble. Filtering
2081 // can't be restricted to Android because this special object file don't
2082 // contain the note section specifying the environment to Android but the
2083 // custom extension and file name makes it highly unlikely that this will
2084 // collide with anything else.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002085 ConstString file_extension = m_file.GetFileNameExtension();
Jonas Devliegheread8d48f2018-06-13 16:23:21 +00002086 bool skip_oatdata_oatexec = file_extension == ConstString(".oat") ||
2087 file_extension == ConstString(".odex");
Kate Stoneb9c1b512016-09-06 20:57:50 +00002088
Pavel Labathf760f5a2019-01-03 10:37:19 +00002089 ArchSpec arch = GetArchitecture();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002090 ModuleSP module_sp(GetModule());
2091 SectionList *module_section_list =
2092 module_sp ? module_sp->GetSectionList() : nullptr;
2093
2094 // Local cache to avoid doing a FindSectionByName for each symbol. The "const
Adrian Prantl05097242018-04-30 16:49:04 +00002095 // char*" key must came from a ConstString object so they can be compared by
2096 // pointer
Kate Stoneb9c1b512016-09-06 20:57:50 +00002097 std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
2098
2099 unsigned i;
2100 for (i = 0; i < num_symbols; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002101 if (!symbol.Parse(symtab_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002102 break;
2103
2104 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2105 if (!symbol_name)
2106 symbol_name = "";
2107
2108 // No need to add non-section symbols that have no names
2109 if (symbol.getType() != STT_SECTION &&
2110 (symbol_name == nullptr || symbol_name[0] == '\0'))
2111 continue;
2112
2113 // Skipping oatdata and oatexec sections if it is requested. See details
Adrian Prantl05097242018-04-30 16:49:04 +00002114 // above the definition of skip_oatdata_oatexec for the reasons.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002115 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
2116 ::strcmp(symbol_name, "oatexec") == 0))
2117 continue;
2118
2119 SectionSP symbol_section_sp;
2120 SymbolType symbol_type = eSymbolTypeInvalid;
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002121 Elf64_Half shndx = symbol.st_shndx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002122
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002123 switch (shndx) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002124 case SHN_ABS:
2125 symbol_type = eSymbolTypeAbsolute;
2126 break;
2127 case SHN_UNDEF:
2128 symbol_type = eSymbolTypeUndefined;
2129 break;
2130 default:
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002131 symbol_section_sp = section_list->FindSectionByID(shndx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002132 break;
2133 }
2134
2135 // If a symbol is undefined do not process it further even if it has a STT
2136 // type
2137 if (symbol_type != eSymbolTypeUndefined) {
2138 switch (symbol.getType()) {
2139 default:
2140 case STT_NOTYPE:
2141 // The symbol's type is not specified.
2142 break;
2143
2144 case STT_OBJECT:
Adrian Prantl05097242018-04-30 16:49:04 +00002145 // The symbol is associated with a data object, such as a variable, an
2146 // array, etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002147 symbol_type = eSymbolTypeData;
2148 break;
2149
2150 case STT_FUNC:
2151 // The symbol is associated with a function or other executable code.
2152 symbol_type = eSymbolTypeCode;
2153 break;
2154
2155 case STT_SECTION:
2156 // The symbol is associated with a section. Symbol table entries of
Adrian Prantl05097242018-04-30 16:49:04 +00002157 // this type exist primarily for relocation and normally have STB_LOCAL
2158 // binding.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 break;
2160
2161 case STT_FILE:
Adrian Prantl05097242018-04-30 16:49:04 +00002162 // Conventionally, the symbol's name gives the name of the source file
2163 // associated with the object file. A file symbol has STB_LOCAL
Kate Stoneb9c1b512016-09-06 20:57:50 +00002164 // binding, its section index is SHN_ABS, and it precedes the other
2165 // STB_LOCAL symbols for the file, if it is present.
2166 symbol_type = eSymbolTypeSourceFile;
2167 break;
2168
2169 case STT_GNU_IFUNC:
2170 // The symbol is associated with an indirect function. The actual
2171 // function will be resolved if it is referenced.
2172 symbol_type = eSymbolTypeResolver;
2173 break;
2174 }
2175 }
2176
2177 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2178 if (symbol_section_sp) {
Adrian Prantl0e4c4822019-03-06 21:22:25 +00002179 ConstString sect_name = symbol_section_sp->GetName();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002180 if (sect_name == text_section_name || sect_name == init_section_name ||
2181 sect_name == fini_section_name || sect_name == ctors_section_name ||
2182 sect_name == dtors_section_name) {
2183 symbol_type = eSymbolTypeCode;
2184 } else if (sect_name == data_section_name ||
2185 sect_name == data2_section_name ||
2186 sect_name == rodata_section_name ||
2187 sect_name == rodata1_section_name ||
2188 sect_name == bss_section_name) {
2189 symbol_type = eSymbolTypeData;
2190 }
2191 }
2192 }
2193
2194 int64_t symbol_value_offset = 0;
2195 uint32_t additional_flags = 0;
2196
2197 if (arch.IsValid()) {
2198 if (arch.GetMachine() == llvm::Triple::arm) {
2199 if (symbol.getBinding() == STB_LOCAL) {
2200 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2201 if (symbol_type == eSymbolTypeCode) {
2202 switch (mapping_symbol) {
2203 case 'a':
2204 // $a[.<any>]* - marks an ARM instruction sequence
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002205 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002206 break;
2207 case 'b':
2208 case 't':
2209 // $b[.<any>]* - marks a THUMB BL instruction sequence
2210 // $t[.<any>]* - marks a THUMB instruction sequence
2211 m_address_class_map[symbol.st_value] =
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002212 AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002213 break;
2214 case 'd':
2215 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002216 m_address_class_map[symbol.st_value] = AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002217 break;
2218 }
2219 }
2220 if (mapping_symbol)
2221 continue;
2222 }
2223 } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2224 if (symbol.getBinding() == STB_LOCAL) {
2225 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2226 if (symbol_type == eSymbolTypeCode) {
2227 switch (mapping_symbol) {
2228 case 'x':
2229 // $x[.<any>]* - marks an A64 instruction sequence
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002230 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002231 break;
2232 case 'd':
2233 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002234 m_address_class_map[symbol.st_value] = AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002235 break;
2236 }
2237 }
2238 if (mapping_symbol)
2239 continue;
2240 }
2241 }
2242
2243 if (arch.GetMachine() == llvm::Triple::arm) {
2244 if (symbol_type == eSymbolTypeCode) {
2245 if (symbol.st_value & 1) {
Adrian Prantl05097242018-04-30 16:49:04 +00002246 // Subtracting 1 from the address effectively unsets the low order
2247 // bit, which results in the address actually pointing to the
2248 // beginning of the symbol. This delta will be used below in
2249 // conjunction with symbol.st_value to produce the final
2250 // symbol_value that we store in the symtab.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002251 symbol_value_offset = -1;
2252 m_address_class_map[symbol.st_value ^ 1] =
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002253 AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002254 } else {
2255 // This address is ARM
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002256 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002257 }
2258 }
2259 }
2260
2261 /*
2262 * MIPS:
2263 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2264 * MIPS).
2265 * This allows processor to switch between microMIPS and MIPS without any
2266 * need
2267 * for special mode-control register. However, apart from .debug_line,
2268 * none of
2269 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2270 * st_other
2271 * flag to check whether the symbol is microMIPS and then set the address
2272 * class
2273 * accordingly.
2274 */
2275 const llvm::Triple::ArchType llvm_arch = arch.GetMachine();
2276 if (llvm_arch == llvm::Triple::mips ||
2277 llvm_arch == llvm::Triple::mipsel ||
2278 llvm_arch == llvm::Triple::mips64 ||
2279 llvm_arch == llvm::Triple::mips64el) {
2280 if (IS_MICROMIPS(symbol.st_other))
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002281 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002282 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2283 symbol.st_value = symbol.st_value & (~1ull);
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002284 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002285 } else {
2286 if (symbol_type == eSymbolTypeCode)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002287 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002288 else if (symbol_type == eSymbolTypeData)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002289 m_address_class_map[symbol.st_value] = AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002290 else
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002291 m_address_class_map[symbol.st_value] = AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002292 }
2293 }
2294 }
2295
2296 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
Adrian Prantl05097242018-04-30 16:49:04 +00002297 // symbols. See above for more details.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002298 uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2299
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002300 if (symbol_section_sp == nullptr && shndx == SHN_ABS &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00002301 symbol.st_size != 0) {
2302 // We don't have a section for a symbol with non-zero size. Create a new
Adrian Prantl05097242018-04-30 16:49:04 +00002303 // section for it so the address range covered by the symbol is also
2304 // covered by the module (represented through the section list). It is
2305 // needed so module lookup for the addresses covered by this symbol will
2306 // be successfull. This case happens for absolute symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002307 ConstString fake_section_name(std::string(".absolute.") + symbol_name);
2308 symbol_section_sp =
2309 std::make_shared<Section>(module_sp, this, SHN_ABS, fake_section_name,
2310 eSectionTypeAbsoluteAddress, symbol_value,
2311 symbol.st_size, 0, 0, 0, SHF_ALLOC);
2312
2313 module_section_list->AddSection(symbol_section_sp);
2314 section_list->AddSection(symbol_section_sp);
2315 }
2316
2317 if (symbol_section_sp &&
2318 CalculateType() != ObjectFile::Type::eTypeObjectFile)
2319 symbol_value -= symbol_section_sp->GetFileAddress();
2320
2321 if (symbol_section_sp && module_section_list &&
2322 module_section_list != section_list) {
Adrian Prantl0e4c4822019-03-06 21:22:25 +00002323 ConstString sect_name = symbol_section_sp->GetName();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002324 auto section_it = section_name_to_section.find(sect_name.GetCString());
2325 if (section_it == section_name_to_section.end())
2326 section_it =
2327 section_name_to_section
2328 .emplace(sect_name.GetCString(),
2329 module_section_list->FindSectionByName(sect_name))
2330 .first;
Pavel Labathefddda3d2017-05-02 12:40:31 +00002331 if (section_it->second)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002332 symbol_section_sp = section_it->second;
2333 }
2334
2335 bool is_global = symbol.getBinding() == STB_GLOBAL;
2336 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2337 bool is_mangled = (symbol_name[0] == '_' && symbol_name[1] == 'Z');
2338
2339 llvm::StringRef symbol_ref(symbol_name);
2340
2341 // Symbol names may contain @VERSION suffixes. Find those and strip them
2342 // temporarily.
2343 size_t version_pos = symbol_ref.find('@');
2344 bool has_suffix = version_pos != llvm::StringRef::npos;
2345 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2346 Mangled mangled(ConstString(symbol_bare), is_mangled);
2347
2348 // Now append the suffix back to mangled and unmangled names. Only do it if
Adrian Prantl05097242018-04-30 16:49:04 +00002349 // the demangling was successful (string is not empty).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002350 if (has_suffix) {
2351 llvm::StringRef suffix = symbol_ref.substr(version_pos);
2352
2353 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2354 if (!mangled_name.empty())
2355 mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2356
2357 ConstString demangled =
2358 mangled.GetDemangledName(lldb::eLanguageTypeUnknown);
2359 llvm::StringRef demangled_name = demangled.GetStringRef();
2360 if (!demangled_name.empty())
2361 mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2362 }
2363
2364 // In ELF all symbol should have a valid size but it is not true for some
Adrian Prantl05097242018-04-30 16:49:04 +00002365 // function symbols coming from hand written assembly. As none of the
2366 // function symbol should have 0 size we try to calculate the size for
2367 // these symbols in the symtab with saying that their original size is not
2368 // valid.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002369 bool symbol_size_valid =
2370 symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2371
2372 Symbol dc_symbol(
2373 i + start_id, // ID is the original symbol table index.
2374 mangled,
2375 symbol_type, // Type of this symbol
2376 is_global, // Is this globally visible?
2377 false, // Is this symbol debug info?
2378 false, // Is this symbol a trampoline?
2379 false, // Is this symbol artificial?
2380 AddressRange(symbol_section_sp, // Section in which this symbol is
2381 // defined or null.
2382 symbol_value, // Offset in section or symbol value.
2383 symbol.st_size), // Size in bytes of this symbol.
2384 symbol_size_valid, // Symbol size is valid
2385 has_suffix, // Contains linker annotations?
2386 flags); // Symbol flags.
2387 symtab->AddSymbol(dc_symbol);
2388 }
2389 return i;
2390}
2391
2392unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
2393 user_id_t start_id,
2394 lldb_private::Section *symtab) {
2395 if (symtab->GetObjectFile() != this) {
2396 // If the symbol table section is owned by a different object file, have it
Adrian Prantl05097242018-04-30 16:49:04 +00002397 // do the parsing.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002398 ObjectFileELF *obj_file_elf =
2399 static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2400 return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2401 }
2402
2403 // Get section list for this object file.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002404 SectionList *section_list = m_sections_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002405 if (!section_list)
2406 return 0;
2407
2408 user_id_t symtab_id = symtab->GetID();
2409 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2410 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2411 symtab_hdr->sh_type == SHT_DYNSYM);
2412
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002413 // sh_link: section header index of associated string table.
2414 user_id_t strtab_id = symtab_hdr->sh_link;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002415 Section *strtab = section_list->FindSectionByID(strtab_id).get();
2416
2417 if (symtab && strtab) {
2418 assert(symtab->GetObjectFile() == this);
2419 assert(strtab->GetObjectFile() == this);
2420
2421 DataExtractor symtab_data;
2422 DataExtractor strtab_data;
2423 if (ReadSectionData(symtab, symtab_data) &&
2424 ReadSectionData(strtab, strtab_data)) {
2425 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2426
2427 return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2428 symtab_data, strtab_data);
2429 }
2430 }
2431
2432 return 0;
2433}
2434
2435size_t ObjectFileELF::ParseDynamicSymbols() {
2436 if (m_dynamic_symbols.size())
2437 return m_dynamic_symbols.size();
2438
2439 SectionList *section_list = GetSectionList();
2440 if (!section_list)
2441 return 0;
2442
2443 // Find the SHT_DYNAMIC section.
2444 Section *dynsym =
2445 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
2446 .get();
2447 if (!dynsym)
2448 return 0;
2449 assert(dynsym->GetObjectFile() == this);
2450
2451 ELFDynamic symbol;
2452 DataExtractor dynsym_data;
2453 if (ReadSectionData(dynsym, dynsym_data)) {
2454 const lldb::offset_t section_size = dynsym_data.GetByteSize();
2455 lldb::offset_t cursor = 0;
2456
2457 while (cursor < section_size) {
2458 if (!symbol.Parse(dynsym_data, &cursor))
2459 break;
2460
2461 m_dynamic_symbols.push_back(symbol);
2462 }
2463 }
2464
2465 return m_dynamic_symbols.size();
2466}
2467
2468const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
2469 if (!ParseDynamicSymbols())
2470 return NULL;
2471
2472 DynamicSymbolCollIter I = m_dynamic_symbols.begin();
2473 DynamicSymbolCollIter E = m_dynamic_symbols.end();
2474 for (; I != E; ++I) {
2475 ELFDynamic *symbol = &*I;
2476
2477 if (symbol->d_tag == tag)
2478 return symbol;
2479 }
2480
2481 return NULL;
2482}
2483
2484unsigned ObjectFileELF::PLTRelocationType() {
2485 // DT_PLTREL
2486 // This member specifies the type of relocation entry to which the
2487 // procedure linkage table refers. The d_val member holds DT_REL or
2488 // DT_RELA, as appropriate. All relocations in a procedure linkage table
2489 // must use the same relocation.
2490 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2491
2492 if (symbol)
2493 return symbol->d_val;
2494
2495 return 0;
2496}
2497
Adrian Prantl05097242018-04-30 16:49:04 +00002498// Returns the size of the normal plt entries and the offset of the first
2499// normal plt entry. The 0th entry in the plt table is usually a resolution
2500// entry which have different size in some architectures then the rest of the
2501// plt entries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002502static std::pair<uint64_t, uint64_t>
2503GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
2504 const ELFSectionHeader *plt_hdr) {
2505 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2506
Adrian Prantl05097242018-04-30 16:49:04 +00002507 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
2508 // 16 bytes. So round the entsize up by the alignment if addralign is set.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002509 elf_xword plt_entsize =
2510 plt_hdr->sh_addralign
2511 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2512 : plt_hdr->sh_entsize;
2513
2514 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2515 // PLT entries relocation code in general requires multiple instruction and
2516 // should be greater than 4 bytes in most cases. Try to guess correct size
2517 // just in case.
2518 if (plt_entsize <= 4) {
2519 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
Adrian Prantl05097242018-04-30 16:49:04 +00002520 // size of the plt entries based on the number of entries and the size of
2521 // the plt section with the assumption that the size of the 0th entry is at
2522 // least as big as the size of the normal entries and it isn't much bigger
2523 // then that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002524 if (plt_hdr->sh_addralign)
2525 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2526 (num_relocations + 1) * plt_hdr->sh_addralign;
2527 else
2528 plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2529 }
2530
2531 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2532
2533 return std::make_pair(plt_entsize, plt_offset);
2534}
2535
2536static unsigned ParsePLTRelocations(
2537 Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2538 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2539 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2540 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2541 DataExtractor &symtab_data, DataExtractor &strtab_data) {
2542 ELFRelocation rel(rel_type);
2543 ELFSymbol symbol;
2544 lldb::offset_t offset = 0;
2545
2546 uint64_t plt_offset, plt_entsize;
2547 std::tie(plt_entsize, plt_offset) =
2548 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2549 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2550
2551 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2552 reloc_info_fn reloc_type;
2553 reloc_info_fn reloc_symbol;
2554
2555 if (hdr->Is32Bit()) {
2556 reloc_type = ELFRelocation::RelocType32;
2557 reloc_symbol = ELFRelocation::RelocSymbol32;
2558 } else {
2559 reloc_type = ELFRelocation::RelocType64;
2560 reloc_symbol = ELFRelocation::RelocSymbol64;
2561 }
2562
2563 unsigned slot_type = hdr->GetRelocationJumpSlotType();
2564 unsigned i;
2565 for (i = 0; i < num_relocations; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002566 if (!rel.Parse(rel_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002567 break;
2568
2569 if (reloc_type(rel) != slot_type)
2570 continue;
2571
2572 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2573 if (!symbol.Parse(symtab_data, &symbol_offset))
2574 break;
2575
2576 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2577 bool is_mangled =
2578 symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
2579 uint64_t plt_index = plt_offset + i * plt_entsize;
2580
2581 Symbol jump_symbol(
2582 i + start_id, // Symbol table index
2583 symbol_name, // symbol name.
2584 is_mangled, // is the symbol name mangled?
2585 eSymbolTypeTrampoline, // Type of this symbol
2586 false, // Is this globally visible?
2587 false, // Is this symbol debug info?
2588 true, // Is this symbol a trampoline?
2589 true, // Is this symbol artificial?
2590 plt_section_sp, // Section in which this symbol is defined or null.
2591 plt_index, // Offset in section or symbol value.
2592 plt_entsize, // Size in bytes of this symbol.
2593 true, // Size is valid
2594 false, // Contains linker annotations?
2595 0); // Symbol flags.
2596
2597 symbol_table->AddSymbol(jump_symbol);
2598 }
2599
2600 return i;
2601}
2602
2603unsigned
2604ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
2605 const ELFSectionHeaderInfo *rel_hdr,
2606 user_id_t rel_id) {
2607 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2608
2609 // The link field points to the associated symbol table.
2610 user_id_t symtab_id = rel_hdr->sh_link;
2611
2612 // If the link field doesn't point to the appropriate symbol name table then
2613 // try to find it by name as some compiler don't fill in the link fields.
2614 if (!symtab_id)
2615 symtab_id = GetSectionIndexByName(".dynsym");
2616
2617 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers
2618 // point that to the .got.plt or .got section instead of .plt.
2619 user_id_t plt_id = GetSectionIndexByName(".plt");
2620
2621 if (!symtab_id || !plt_id)
2622 return 0;
2623
Kate Stoneb9c1b512016-09-06 20:57:50 +00002624 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2625 if (!plt_hdr)
2626 return 0;
2627
2628 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2629 if (!sym_hdr)
2630 return 0;
2631
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002632 SectionList *section_list = m_sections_up.get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002633 if (!section_list)
2634 return 0;
2635
2636 Section *rel_section = section_list->FindSectionByID(rel_id).get();
2637 if (!rel_section)
2638 return 0;
2639
2640 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2641 if (!plt_section_sp)
2642 return 0;
2643
2644 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2645 if (!symtab)
2646 return 0;
2647
2648 // sh_link points to associated string table.
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002649 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002650 if (!strtab)
2651 return 0;
2652
2653 DataExtractor rel_data;
2654 if (!ReadSectionData(rel_section, rel_data))
2655 return 0;
2656
2657 DataExtractor symtab_data;
2658 if (!ReadSectionData(symtab, symtab_data))
2659 return 0;
2660
2661 DataExtractor strtab_data;
2662 if (!ReadSectionData(strtab, strtab_data))
2663 return 0;
2664
2665 unsigned rel_type = PLTRelocationType();
2666 if (!rel_type)
2667 return 0;
2668
2669 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2670 rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2671 rel_data, symtab_data, strtab_data);
2672}
2673
Ed Masted13f6912017-10-02 14:35:07 +00002674unsigned ObjectFileELF::ApplyRelocations(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002675 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2676 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
2677 DataExtractor &rel_data, DataExtractor &symtab_data,
2678 DataExtractor &debug_data, Section *rel_section) {
2679 ELFRelocation rel(rel_hdr->sh_type);
2680 lldb::addr_t offset = 0;
2681 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2682 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2683 reloc_info_fn reloc_type;
2684 reloc_info_fn reloc_symbol;
2685
2686 if (hdr->Is32Bit()) {
2687 reloc_type = ELFRelocation::RelocType32;
2688 reloc_symbol = ELFRelocation::RelocSymbol32;
2689 } else {
2690 reloc_type = ELFRelocation::RelocType64;
2691 reloc_symbol = ELFRelocation::RelocSymbol64;
2692 }
2693
2694 for (unsigned i = 0; i < num_relocations; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002695 if (!rel.Parse(rel_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002696 break;
2697
2698 Symbol *symbol = NULL;
2699
2700 if (hdr->Is32Bit()) {
2701 switch (reloc_type(rel)) {
2702 case R_386_32:
2703 case R_386_PC32:
2704 default:
Zachary Turnera6d54642017-12-02 00:15:29 +00002705 // FIXME: This asserts with this input:
2706 //
2707 // foo.cpp
2708 // int main(int argc, char **argv) { return 0; }
2709 //
2710 // clang++.exe --target=i686-unknown-linux-gnu -g -c foo.cpp -o foo.o
2711 //
2712 // and running this on the foo.o module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 assert(false && "unexpected relocation type");
2714 }
2715 } else {
2716 switch (reloc_type(rel)) {
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002717 case R_AARCH64_ABS64:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002718 case R_X86_64_64: {
2719 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2720 if (symbol) {
2721 addr_t value = symbol->GetAddressRef().GetFileAddress();
2722 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2723 uint64_t *dst = reinterpret_cast<uint64_t *>(
2724 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2725 ELFRelocation::RelocOffset64(rel));
Davide Italianob37f1ec2018-11-06 17:11:34 +00002726 uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
2727 memcpy(dst, &val_offset, sizeof(uint64_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002728 }
2729 break;
2730 }
2731 case R_X86_64_32:
Stephane Sezer9e2fe8b2018-08-17 00:35:47 +00002732 case R_X86_64_32S:
2733 case R_AARCH64_ABS32: {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002734 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2735 if (symbol) {
2736 addr_t value = symbol->GetAddressRef().GetFileAddress();
2737 value += ELFRelocation::RelocAddend32(rel);
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002738 if ((reloc_type(rel) == R_X86_64_32 && (value > UINT32_MAX)) ||
Stephane Sezer0c679b72018-08-06 22:21:28 +00002739 (reloc_type(rel) == R_X86_64_32S &&
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002740 ((int64_t)value > INT32_MAX && (int64_t)value < INT32_MIN)) ||
2741 (reloc_type(rel) == R_AARCH64_ABS32 &&
2742 ((int64_t)value > INT32_MAX && (int64_t)value < INT32_MIN))) {
Stephane Sezer9e2fe8b2018-08-17 00:35:47 +00002743 Log *log =
2744 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES);
2745 log->Printf("Failed to apply debug info relocations");
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002746 break;
Stephane Sezer9e2fe8b2018-08-17 00:35:47 +00002747 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002748 uint32_t truncated_addr = (value & 0xFFFFFFFF);
2749 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2750 uint32_t *dst = reinterpret_cast<uint32_t *>(
2751 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2752 ELFRelocation::RelocOffset32(rel));
Davide Italianob37f1ec2018-11-06 17:11:34 +00002753 memcpy(dst, &truncated_addr, sizeof(uint32_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002754 }
2755 break;
2756 }
2757 case R_X86_64_PC32:
2758 default:
2759 assert(false && "unexpected relocation type");
2760 }
2761 }
2762 }
2763
2764 return 0;
2765}
2766
2767unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
Ed Masted13f6912017-10-02 14:35:07 +00002768 user_id_t rel_id,
2769 lldb_private::Symtab *thetab) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002770 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2771
2772 // Parse in the section list if needed.
2773 SectionList *section_list = GetSectionList();
2774 if (!section_list)
2775 return 0;
2776
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002777 user_id_t symtab_id = rel_hdr->sh_link;
2778 user_id_t debug_id = rel_hdr->sh_info;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002779
2780 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2781 if (!symtab_hdr)
2782 return 0;
2783
2784 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
2785 if (!debug_hdr)
2786 return 0;
2787
2788 Section *rel = section_list->FindSectionByID(rel_id).get();
2789 if (!rel)
2790 return 0;
2791
2792 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2793 if (!symtab)
2794 return 0;
2795
2796 Section *debug = section_list->FindSectionByID(debug_id).get();
2797 if (!debug)
2798 return 0;
2799
2800 DataExtractor rel_data;
2801 DataExtractor symtab_data;
2802 DataExtractor debug_data;
2803
Ed Masted13f6912017-10-02 14:35:07 +00002804 if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&
2805 GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&
2806 GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {
2807 ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
2808 rel_data, symtab_data, debug_data, debug);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002809 }
2810
2811 return 0;
2812}
2813
2814Symtab *ObjectFileELF::GetSymtab() {
2815 ModuleSP module_sp(GetModule());
2816 if (!module_sp)
2817 return NULL;
2818
2819 // We always want to use the main object file so we (hopefully) only have one
Adrian Prantl05097242018-04-30 16:49:04 +00002820 // cached copy of our symtab, dynamic sections, etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 ObjectFile *module_obj_file = module_sp->GetObjectFile();
2822 if (module_obj_file && module_obj_file != this)
2823 return module_obj_file->GetSymtab();
2824
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002825 if (m_symtab_up == NULL) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002826 SectionList *section_list = module_sp->GetSectionList();
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002827 if (!section_list)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002828 return NULL;
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002829
Kate Stoneb9c1b512016-09-06 20:57:50 +00002830 uint64_t symbol_id = 0;
2831 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002832
Kate Stoneb9c1b512016-09-06 20:57:50 +00002833 // Sharable objects and dynamic executables usually have 2 distinct symbol
2834 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
Adrian Prantl05097242018-04-30 16:49:04 +00002835 // smaller version of the symtab that only contains global symbols. The
2836 // information found in the dynsym is therefore also found in the symtab,
2837 // while the reverse is not necessarily true.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002838 Section *symtab =
2839 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
2840 if (!symtab) {
2841 // The symtab section is non-allocable and can be stripped, so if it
Adrian Prantl05097242018-04-30 16:49:04 +00002842 // doesn't exist then use the dynsym section which should always be
2843 // there.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002844 symtab =
2845 section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
2846 .get();
2847 }
2848 if (symtab) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002849 m_symtab_up.reset(new Symtab(symtab->GetObjectFile()));
2850 symbol_id += ParseSymbolTable(m_symtab_up.get(), symbol_id, symtab);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002851 }
2852
2853 // DT_JMPREL
2854 // If present, this entry's d_ptr member holds the address of
2855 // relocation
2856 // entries associated solely with the procedure linkage table.
2857 // Separating
2858 // these relocation entries lets the dynamic linker ignore them during
2859 // process initialization, if lazy binding is enabled. If this entry is
2860 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
2861 // also be present.
2862 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
2863 if (symbol) {
2864 // Synthesize trampoline symbols to help navigate the PLT.
2865 addr_t addr = symbol->d_ptr;
2866 Section *reloc_section =
2867 section_list->FindSectionContainingFileAddress(addr).get();
2868 if (reloc_section) {
2869 user_id_t reloc_id = reloc_section->GetID();
2870 const ELFSectionHeaderInfo *reloc_header =
2871 GetSectionHeaderByIndex(reloc_id);
2872 assert(reloc_header);
2873
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002874 if (m_symtab_up == nullptr)
2875 m_symtab_up.reset(new Symtab(reloc_section->GetObjectFile()));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002876
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002877 ParseTrampolineSymbols(m_symtab_up.get(), symbol_id, reloc_header,
Kate Stoneb9c1b512016-09-06 20:57:50 +00002878 reloc_id);
2879 }
2880 }
2881
Pavel Labath66d88322019-02-14 14:40:10 +00002882 if (DWARFCallFrameInfo *eh_frame =
2883 GetModule()->GetUnwindTable().GetEHFrameInfo()) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002884 if (m_symtab_up == nullptr)
2885 m_symtab_up.reset(new Symtab(this));
2886 ParseUnwindSymbols(m_symtab_up.get(), eh_frame);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002887 }
2888
2889 // If we still don't have any symtab then create an empty instance to avoid
Adrian Prantl05097242018-04-30 16:49:04 +00002890 // do the section lookup next time.
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002891 if (m_symtab_up == nullptr)
2892 m_symtab_up.reset(new Symtab(this));
Davide Italiano407c6912018-11-02 21:59:14 +00002893
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002894 m_symtab_up->CalculateSymbolSizes();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002895 }
2896
Jonas Devlieghered5b44032019-02-13 06:25:41 +00002897 return m_symtab_up.get();
Ed Masted13f6912017-10-02 14:35:07 +00002898}
2899
2900void ObjectFileELF::RelocateSection(lldb_private::Section *section)
2901{
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002902 static const char *debug_prefix = ".debug";
Ed Masted13f6912017-10-02 14:35:07 +00002903
Adrian Prantl05097242018-04-30 16:49:04 +00002904 // Set relocated bit so we stop getting called, regardless of whether we
2905 // actually relocate.
Ed Masted13f6912017-10-02 14:35:07 +00002906 section->SetIsRelocated(true);
2907
2908 // We only relocate in ELF relocatable files
2909 if (CalculateType() != eTypeObjectFile)
2910 return;
2911
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002912 const char *section_name = section->GetName().GetCString();
Ed Masted13f6912017-10-02 14:35:07 +00002913 // Can't relocate that which can't be named
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002914 if (section_name == nullptr)
Ed Masted13f6912017-10-02 14:35:07 +00002915 return;
2916
2917 // We don't relocate non-debug sections at the moment
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002918 if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
Ed Masted13f6912017-10-02 14:35:07 +00002919 return;
2920
2921 // Relocation section names to look for
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002922 std::string needle = std::string(".rel") + section_name;
2923 std::string needlea = std::string(".rela") + section_name;
Ed Masted13f6912017-10-02 14:35:07 +00002924
Kate Stoneb9c1b512016-09-06 20:57:50 +00002925 for (SectionHeaderCollIter I = m_section_headers.begin();
2926 I != m_section_headers.end(); ++I) {
2927 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
Ed Masted13f6912017-10-02 14:35:07 +00002928 const char *hay_name = I->section_name.GetCString();
2929 if (hay_name == nullptr)
2930 continue;
2931 if (needle == hay_name || needlea == hay_name) {
2932 const ELFSectionHeader &reloc_header = *I;
2933 user_id_t reloc_id = SectionIndex(I);
2934 RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
2935 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002936 }
2937 }
2938 }
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002939}
Tamas Berghammer5bfd4d02016-02-10 12:10:58 +00002940
Kate Stoneb9c1b512016-09-06 20:57:50 +00002941void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
2942 DWARFCallFrameInfo *eh_frame) {
2943 SectionList *section_list = GetSectionList();
2944 if (!section_list)
2945 return;
2946
2947 // First we save the new symbols into a separate list and add them to the
Adrian Prantl05097242018-04-30 16:49:04 +00002948 // symbol table after we colleced all symbols we want to add. This is
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002949 // neccessary because adding a new symbol invalidates the internal index of
Adrian Prantl05097242018-04-30 16:49:04 +00002950 // the symtab what causing the next lookup to be slow because it have to
2951 // recalculate the index first.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002952 std::vector<Symbol> new_symbols;
2953
2954 eh_frame->ForEachFDEEntries([this, symbol_table, section_list, &new_symbols](
2955 lldb::addr_t file_addr, uint32_t size, dw_offset_t) {
2956 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
2957 if (symbol) {
2958 if (!symbol->GetByteSizeIsValid()) {
2959 symbol->SetByteSize(size);
2960 symbol->SetSizeIsSynthesized(true);
2961 }
2962 } else {
2963 SectionSP section_sp =
2964 section_list->FindSectionContainingFileAddress(file_addr);
2965 if (section_sp) {
2966 addr_t offset = file_addr - section_sp->GetFileAddress();
2967 const char *symbol_name = GetNextSyntheticSymbolName().GetCString();
2968 uint64_t symbol_id = symbol_table->GetNumSymbols();
2969 Symbol eh_symbol(
2970 symbol_id, // Symbol table index.
2971 symbol_name, // Symbol name.
2972 false, // Is the symbol name mangled?
2973 eSymbolTypeCode, // Type of this symbol.
2974 true, // Is this globally visible?
2975 false, // Is this symbol debug info?
2976 false, // Is this symbol a trampoline?
2977 true, // Is this symbol artificial?
2978 section_sp, // Section in which this symbol is defined or null.
2979 offset, // Offset in section or symbol value.
2980 0, // Size: Don't specify the size as an FDE can
2981 false, // Size is valid: cover multiple symbols.
2982 false, // Contains linker annotations?
2983 0); // Symbol flags.
2984 new_symbols.push_back(eh_symbol);
2985 }
2986 }
2987 return true;
2988 });
2989
2990 for (const Symbol &s : new_symbols)
2991 symbol_table->AddSymbol(s);
2992}
2993
2994bool ObjectFileELF::IsStripped() {
2995 // TODO: determine this for ELF
2996 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002997}
2998
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002999//===----------------------------------------------------------------------===//
3000// Dump
3001//
3002// Dump the specifics of the runtime file container (such as any headers
3003// segments, sections, etc).
3004//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003005void ObjectFileELF::Dump(Stream *s) {
3006 ModuleSP module_sp(GetModule());
3007 if (!module_sp) {
3008 return;
3009 }
Adrian McCarthy543725c2016-04-04 21:21:49 +00003010
Kate Stoneb9c1b512016-09-06 20:57:50 +00003011 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
3012 s->Printf("%p: ", static_cast<void *>(this));
3013 s->Indent();
3014 s->PutCString("ObjectFileELF");
Adrian McCarthy543725c2016-04-04 21:21:49 +00003015
Pavel Labathf760f5a2019-01-03 10:37:19 +00003016 ArchSpec header_arch = GetArchitecture();
Adrian McCarthy543725c2016-04-04 21:21:49 +00003017
Kate Stoneb9c1b512016-09-06 20:57:50 +00003018 *s << ", file = '" << m_file
3019 << "', arch = " << header_arch.GetArchitectureName() << "\n";
Adrian McCarthy543725c2016-04-04 21:21:49 +00003020
Kate Stoneb9c1b512016-09-06 20:57:50 +00003021 DumpELFHeader(s, m_header);
3022 s->EOL();
3023 DumpELFProgramHeaders(s);
3024 s->EOL();
3025 DumpELFSectionHeaders(s);
3026 s->EOL();
3027 SectionList *section_list = GetSectionList();
3028 if (section_list)
3029 section_list->Dump(s, NULL, true, UINT32_MAX);
3030 Symtab *symtab = GetSymtab();
3031 if (symtab)
3032 symtab->Dump(s, NULL, eSortOrderNone);
3033 s->EOL();
3034 DumpDependentModules(s);
3035 s->EOL();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003036}
3037
3038//----------------------------------------------------------------------
3039// DumpELFHeader
3040//
3041// Dump the ELF header to the specified output stream
3042//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003043void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
3044 s->PutCString("ELF Header\n");
3045 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
3046 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
3047 header.e_ident[EI_MAG1]);
3048 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
3049 header.e_ident[EI_MAG2]);
3050 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
3051 header.e_ident[EI_MAG3]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003052
Kate Stoneb9c1b512016-09-06 20:57:50 +00003053 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
3054 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
3055 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
3056 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
3057 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003058
Kate Stoneb9c1b512016-09-06 20:57:50 +00003059 s->Printf("e_type = 0x%4.4x ", header.e_type);
3060 DumpELFHeader_e_type(s, header.e_type);
3061 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
3062 s->Printf("e_version = 0x%8.8x\n", header.e_version);
3063 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
3064 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
3065 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
3066 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
3067 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
3068 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
Pavel Labath23ccc292017-01-31 23:09:46 +00003069 s->Printf("e_phnum = 0x%8.8x\n", header.e_phnum);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003070 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
Pavel Labath23ccc292017-01-31 23:09:46 +00003071 s->Printf("e_shnum = 0x%8.8x\n", header.e_shnum);
3072 s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003073}
3074
3075//----------------------------------------------------------------------
3076// DumpELFHeader_e_type
3077//
3078// Dump an token value for the ELF header member e_type
3079//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003080void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
3081 switch (e_type) {
3082 case ET_NONE:
3083 *s << "ET_NONE";
3084 break;
3085 case ET_REL:
3086 *s << "ET_REL";
3087 break;
3088 case ET_EXEC:
3089 *s << "ET_EXEC";
3090 break;
3091 case ET_DYN:
3092 *s << "ET_DYN";
3093 break;
3094 case ET_CORE:
3095 *s << "ET_CORE";
3096 break;
3097 default:
3098 break;
3099 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003100}
3101
3102//----------------------------------------------------------------------
3103// DumpELFHeader_e_ident_EI_DATA
3104//
3105// Dump an token value for the ELF header member e_ident[EI_DATA]
3106//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003107void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
3108 unsigned char ei_data) {
3109 switch (ei_data) {
3110 case ELFDATANONE:
3111 *s << "ELFDATANONE";
3112 break;
3113 case ELFDATA2LSB:
3114 *s << "ELFDATA2LSB - Little Endian";
3115 break;
3116 case ELFDATA2MSB:
3117 *s << "ELFDATA2MSB - Big Endian";
3118 break;
3119 default:
3120 break;
3121 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003122}
3123
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003124//----------------------------------------------------------------------
3125// DumpELFProgramHeader
3126//
3127// Dump a single ELF program header to the specified output stream
3128//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003129void ObjectFileELF::DumpELFProgramHeader(Stream *s,
3130 const ELFProgramHeader &ph) {
3131 DumpELFProgramHeader_p_type(s, ph.p_type);
3132 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3133 ph.p_vaddr, ph.p_paddr);
3134 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3135 ph.p_flags);
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003136
Kate Stoneb9c1b512016-09-06 20:57:50 +00003137 DumpELFProgramHeader_p_flags(s, ph.p_flags);
3138 s->Printf(") %8.8" PRIx64, ph.p_align);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003139}
3140
3141//----------------------------------------------------------------------
3142// DumpELFProgramHeader_p_type
3143//
Adrian Prantl05097242018-04-30 16:49:04 +00003144// Dump an token value for the ELF program header member p_type which describes
3145// the type of the program header
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003146// ----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003147void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
3148 const int kStrWidth = 15;
3149 switch (p_type) {
3150 CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3151 CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3152 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3153 CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3154 CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3155 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3156 CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3157 CASE_AND_STREAM(s, PT_TLS, kStrWidth);
Filipe Cabecinhas477d86d2013-05-23 23:01:14 +00003158 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159 default:
3160 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3161 break;
3162 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003163}
3164
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003165//----------------------------------------------------------------------
3166// DumpELFProgramHeader_p_flags
3167//
3168// Dump an token value for the ELF program header member p_flags
3169//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003170void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
3171 *s << ((p_flags & PF_X) ? "PF_X" : " ")
3172 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3173 << ((p_flags & PF_W) ? "PF_W" : " ")
3174 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3175 << ((p_flags & PF_R) ? "PF_R" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003176}
3177
3178//----------------------------------------------------------------------
3179// DumpELFProgramHeaders
3180//
3181// Dump all of the ELF program header to the specified output stream
3182//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003183void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
3184 if (!ParseProgramHeaders())
3185 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003186
Kate Stoneb9c1b512016-09-06 20:57:50 +00003187 s->PutCString("Program Headers\n");
3188 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
3189 "p_filesz p_memsz p_flags p_align\n");
3190 s->PutCString("==== --------------- -------- -------- -------- "
3191 "-------- -------- ------------------------- --------\n");
Ed Maste3a8ab6e2015-02-23 15:33:11 +00003192
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003193 for (const auto &H : llvm::enumerate(m_program_headers)) {
3194 s->Format("[{0,2}] ", H.index());
3195 ObjectFileELF::DumpELFProgramHeader(s, H.value());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003196 s->EOL();
3197 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003198}
3199
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003200//----------------------------------------------------------------------
3201// DumpELFSectionHeader
3202//
3203// Dump a single ELF section header to the specified output stream
3204//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003205void ObjectFileELF::DumpELFSectionHeader(Stream *s,
3206 const ELFSectionHeaderInfo &sh) {
3207 s->Printf("%8.8x ", sh.sh_name);
3208 DumpELFSectionHeader_sh_type(s, sh.sh_type);
3209 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3210 DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
3211 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3212 sh.sh_offset, sh.sh_size);
3213 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3214 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003215}
3216
3217//----------------------------------------------------------------------
3218// DumpELFSectionHeader_sh_type
3219//
3220// Dump an token value for the ELF section header member sh_type which
3221// describes the type of the section
3222//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003223void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
3224 const int kStrWidth = 12;
3225 switch (sh_type) {
3226 CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3227 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3228 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3229 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3230 CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3231 CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3232 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3233 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3234 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3235 CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3236 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3237 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3238 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3239 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3240 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3241 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3242 default:
3243 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3244 break;
3245 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003246}
3247
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003248//----------------------------------------------------------------------
3249// DumpELFSectionHeader_sh_flags
3250//
3251// Dump an token value for the ELF section header member sh_flags
3252//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003253void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
3254 elf_xword sh_flags) {
3255 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
3256 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3257 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
3258 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3259 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003260}
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003261
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003262//----------------------------------------------------------------------
3263// DumpELFSectionHeaders
3264//
3265// Dump all of the ELF section header to the specified output stream
3266//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003267void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
3268 if (!ParseSectionHeaders())
3269 return;
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003270
Kate Stoneb9c1b512016-09-06 20:57:50 +00003271 s->PutCString("Section Headers\n");
3272 s->PutCString("IDX name type flags "
3273 "addr offset size link info addralgn "
3274 "entsize Name\n");
3275 s->PutCString("==== -------- ------------ -------------------------------- "
3276 "-------- -------- -------- -------- -------- -------- "
3277 "-------- ====================\n");
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003278
Kate Stoneb9c1b512016-09-06 20:57:50 +00003279 uint32_t idx = 0;
3280 for (SectionHeaderCollConstIter I = m_section_headers.begin();
3281 I != m_section_headers.end(); ++I, ++idx) {
3282 s->Printf("[%2u] ", idx);
3283 ObjectFileELF::DumpELFSectionHeader(s, *I);
3284 const char *section_name = I->section_name.AsCString("");
3285 if (section_name)
3286 *s << ' ' << section_name << "\n";
3287 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003288}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003289
Kate Stoneb9c1b512016-09-06 20:57:50 +00003290void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
3291 size_t num_modules = ParseDependentModules();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003292
Kate Stoneb9c1b512016-09-06 20:57:50 +00003293 if (num_modules > 0) {
3294 s->PutCString("Dependent Modules:\n");
3295 for (unsigned i = 0; i < num_modules; ++i) {
Jonas Devlieghered5b44032019-02-13 06:25:41 +00003296 const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003297 s->Printf(" %s\n", spec.GetFilename().GetCString());
3298 }
3299 }
3300}
3301
Pavel Labathf760f5a2019-01-03 10:37:19 +00003302ArchSpec ObjectFileELF::GetArchitecture() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003303 if (!ParseHeader())
Pavel Labathf760f5a2019-01-03 10:37:19 +00003304 return ArchSpec();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003305
3306 if (m_section_headers.empty()) {
3307 // Allow elf notes to be parsed which may affect the detected architecture.
3308 ParseSectionHeaders();
3309 }
3310
3311 if (CalculateType() == eTypeCoreFile &&
Alex Langfordbee015e2019-02-26 23:50:19 +00003312 !m_arch_spec.TripleOSWasSpecified()) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003313 // Core files don't have section headers yet they have PT_NOTE program
Adrian Prantl05097242018-04-30 16:49:04 +00003314 // headers that might shed more light on the architecture
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003315 for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
3316 if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
3317 continue;
3318 DataExtractor data;
3319 if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {
3320 UUID uuid;
3321 RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003322 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003323 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003324 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00003325 return m_arch_spec;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003326}
3327
Kate Stoneb9c1b512016-09-06 20:57:50 +00003328ObjectFile::Type ObjectFileELF::CalculateType() {
3329 switch (m_header.e_type) {
3330 case llvm::ELF::ET_NONE:
3331 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003332 return eTypeUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003333
3334 case llvm::ELF::ET_REL:
3335 // 1 - Relocatable file
3336 return eTypeObjectFile;
3337
3338 case llvm::ELF::ET_EXEC:
3339 // 2 - Executable file
3340 return eTypeExecutable;
3341
3342 case llvm::ELF::ET_DYN:
3343 // 3 - Shared object file
3344 return eTypeSharedLibrary;
3345
3346 case ET_CORE:
3347 // 4 - Core file
3348 return eTypeCoreFile;
3349
3350 default:
3351 break;
3352 }
3353 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003354}
3355
Kate Stoneb9c1b512016-09-06 20:57:50 +00003356ObjectFile::Strata ObjectFileELF::CalculateStrata() {
3357 switch (m_header.e_type) {
3358 case llvm::ELF::ET_NONE:
3359 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003360 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003361
Kate Stoneb9c1b512016-09-06 20:57:50 +00003362 case llvm::ELF::ET_REL:
3363 // 1 - Relocatable file
3364 return eStrataUnknown;
3365
3366 case llvm::ELF::ET_EXEC:
3367 // 2 - Executable file
3368 // TODO: is there any way to detect that an executable is a kernel
Adrian Prantl05097242018-04-30 16:49:04 +00003369 // related executable by inspecting the program headers, section headers,
3370 // symbols, or any other flag bits???
Kate Stoneb9c1b512016-09-06 20:57:50 +00003371 return eStrataUser;
3372
3373 case llvm::ELF::ET_DYN:
3374 // 3 - Shared object file
3375 // TODO: is there any way to detect that an shared library is a kernel
Adrian Prantl05097242018-04-30 16:49:04 +00003376 // related executable by inspecting the program headers, section headers,
3377 // symbols, or any other flag bits???
Kate Stoneb9c1b512016-09-06 20:57:50 +00003378 return eStrataUnknown;
3379
3380 case ET_CORE:
3381 // 4 - Core file
3382 // TODO: is there any way to detect that an core file is a kernel
Adrian Prantl05097242018-04-30 16:49:04 +00003383 // related executable by inspecting the program headers, section headers,
3384 // symbols, or any other flag bits???
Kate Stoneb9c1b512016-09-06 20:57:50 +00003385 return eStrataUnknown;
3386
3387 default:
3388 break;
3389 }
3390 return eStrataUnknown;
3391}
Pavel Labathe2867bc2017-12-15 14:23:58 +00003392
3393size_t ObjectFileELF::ReadSectionData(Section *section,
3394 lldb::offset_t section_offset, void *dst,
3395 size_t dst_len) {
3396 // If some other objectfile owns this data, pass this to them.
3397 if (section->GetObjectFile() != this)
3398 return section->GetObjectFile()->ReadSectionData(section, section_offset,
3399 dst, dst_len);
3400
3401 if (!section->Test(SHF_COMPRESSED))
3402 return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
3403
3404 // For compressed sections we need to read to full data to be able to
3405 // decompress.
3406 DataExtractor data;
3407 ReadSectionData(section, data);
3408 return data.CopyData(section_offset, dst_len, dst);
3409}
3410
3411size_t ObjectFileELF::ReadSectionData(Section *section,
3412 DataExtractor &section_data) {
3413 // If some other objectfile owns this data, pass this to them.
3414 if (section->GetObjectFile() != this)
3415 return section->GetObjectFile()->ReadSectionData(section, section_data);
3416
Pavel Labathe2867bc2017-12-15 14:23:58 +00003417 size_t result = ObjectFile::ReadSectionData(section, section_data);
3418 if (result == 0 || !section->Test(SHF_COMPRESSED))
3419 return result;
3420
3421 auto Decompressor = llvm::object::Decompressor::create(
3422 section->GetName().GetStringRef(),
3423 {reinterpret_cast<const char *>(section_data.GetDataStart()),
Pavel Labath4c2eb8b2017-12-15 14:39:12 +00003424 size_t(section_data.GetByteSize())},
Pavel Labathe2867bc2017-12-15 14:23:58 +00003425 GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8);
3426 if (!Decompressor) {
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003427 GetModule()->ReportWarning(
3428 "Unable to initialize decompressor for section '%s': %s",
3429 section->GetName().GetCString(),
3430 llvm::toString(Decompressor.takeError()).c_str());
3431 section_data.Clear();
3432 return 0;
Pavel Labathe2867bc2017-12-15 14:23:58 +00003433 }
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003434
Pavel Labathe2867bc2017-12-15 14:23:58 +00003435 auto buffer_sp =
3436 std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003437 if (auto error = Decompressor->decompress(
Pavel Labathe2867bc2017-12-15 14:23:58 +00003438 {reinterpret_cast<char *>(buffer_sp->GetBytes()),
Pavel Labath4c2eb8b2017-12-15 14:39:12 +00003439 size_t(buffer_sp->GetByteSize())})) {
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003440 GetModule()->ReportWarning(
3441 "Decompression of section '%s' failed: %s",
3442 section->GetName().GetCString(),
3443 llvm::toString(std::move(error)).c_str());
3444 section_data.Clear();
3445 return 0;
Pavel Labathe2867bc2017-12-15 14:23:58 +00003446 }
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003447
Pavel Labathe2867bc2017-12-15 14:23:58 +00003448 section_data.SetData(buffer_sp);
3449 return buffer_sp->GetByteSize();
3450}
Pavel Labath16064d32018-03-20 11:56:24 +00003451
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003452llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
3453 ParseProgramHeaders();
3454 return m_program_headers;
3455}
3456
3457DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) {
3458 return DataExtractor(m_data, H.p_offset, H.p_filesz);
3459}
3460
Pavel Labath16064d32018-03-20 11:56:24 +00003461bool ObjectFileELF::AnySegmentHasPhysicalAddress() {
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003462 for (const ELFProgramHeader &H : ProgramHeaders()) {
3463 if (H.p_paddr != 0)
Pavel Labath16064d32018-03-20 11:56:24 +00003464 return true;
3465 }
3466 return false;
3467}
3468
3469std::vector<ObjectFile::LoadableData>
3470ObjectFileELF::GetLoadableData(Target &target) {
Adrian Prantl05097242018-04-30 16:49:04 +00003471 // Create a list of loadable data from loadable segments, using physical
3472 // addresses if they aren't all null
Pavel Labath16064d32018-03-20 11:56:24 +00003473 std::vector<LoadableData> loadables;
Pavel Labath16064d32018-03-20 11:56:24 +00003474 bool should_use_paddr = AnySegmentHasPhysicalAddress();
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003475 for (const ELFProgramHeader &H : ProgramHeaders()) {
Pavel Labath16064d32018-03-20 11:56:24 +00003476 LoadableData loadable;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003477 if (H.p_type != llvm::ELF::PT_LOAD)
Pavel Labath16064d32018-03-20 11:56:24 +00003478 continue;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003479 loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
Pavel Labath16064d32018-03-20 11:56:24 +00003480 if (loadable.Dest == LLDB_INVALID_ADDRESS)
3481 continue;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003482 if (H.p_filesz == 0)
Pavel Labath16064d32018-03-20 11:56:24 +00003483 continue;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003484 auto segment_data = GetSegmentData(H);
Pavel Labath16064d32018-03-20 11:56:24 +00003485 loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
3486 segment_data.GetByteSize());
3487 loadables.push_back(loadable);
3488 }
3489 return loadables;
3490}