blob: e3a86f352c0855130932f2e4f5bb4141abd21847 [file] [log] [blame]
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001//===-- ObjectFileELF.cpp ------------------------------------- -*- C++ -*-===//
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "ObjectFileELF.h"
11
Chris Lattner30fdc8d2010-06-08 16:52:24 +000012#include <algorithm>
Kate Stoneb9c1b512016-09-06 20:57:50 +000013#include <cassert>
Tamas Berghammer9fa11472015-10-27 10:43:27 +000014#include <unordered_map>
Chris Lattner30fdc8d2010-06-08 16:52:24 +000015
Stephen Wilsonf325ba92010-07-13 23:07:23 +000016#include "lldb/Core/FileSpecList.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000017#include "lldb/Core/Module.h"
Greg Claytonf4d6de62013-04-24 22:29:28 +000018#include "lldb/Core/ModuleSpec.h"
Chris Lattner30fdc8d2010-06-08 16:52:24 +000019#include "lldb/Core/PluginManager.h"
20#include "lldb/Core/Section.h"
Jonas Devlieghere59b78bc2018-11-01 04:45:28 +000021#include "lldb/Host/FileSystem.h"
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +000022#include "lldb/Symbol/DWARFCallFrameInfo.h"
Jim Ingham672e6f52011-03-07 23:44:08 +000023#include "lldb/Symbol/SymbolContext.h"
Steve Pucci9e02dac2014-02-06 19:02:19 +000024#include "lldb/Target/SectionLoadList.h"
Ed Maste54803652013-10-11 17:39:07 +000025#include "lldb/Target/Target.h"
Pavel Labath5f19b902017-11-13 16:16:33 +000026#include "lldb/Utility/ArchSpec.h"
Pavel Labathe2867bc2017-12-15 14:23:58 +000027#include "lldb/Utility/DataBufferHeap.h"
Zachary Turner6f9e6902017-03-03 20:56:28 +000028#include "lldb/Utility/Log.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
Stephen Wilson499b40e2011-03-30 16:07:05 +000033#include "llvm/ADT/PointerUnion.h"
Zachary Turner97a14e62014-08-19 17:18:29 +000034#include "llvm/ADT/StringRef.h"
Pavel Labathe2867bc2017-12-15 14:23:58 +000035#include "llvm/Object/Decompressor.h"
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +000036#include "llvm/Support/ARMBuildAttributes.h"
Zachary Turner736d4d82014-06-25 05:42:32 +000037#include "llvm/Support/MathExtras.h"
Zachary Turner3f4a4b32017-02-24 18:56:49 +000038#include "llvm/Support/MemoryBuffer.h"
Sagar Thakurad5b55a2016-05-24 14:52:50 +000039#include "llvm/Support/MipsABIFlags.h"
Stephen Wilson499b40e2011-03-30 16:07:05 +000040
Kate Stoneb9c1b512016-09-06 20:57:50 +000041#define CASE_AND_STREAM(s, def, width) \
42 case def: \
43 s->Printf("%-*s", width, #def); \
44 break;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000045
Chris Lattner30fdc8d2010-06-08 16:52:24 +000046using namespace lldb;
47using namespace lldb_private;
Stephen Wilsonf325ba92010-07-13 23:07:23 +000048using namespace elf;
49using namespace llvm::ELF;
Chris Lattner30fdc8d2010-06-08 16:52:24 +000050
Stephen Wilson499b40e2011-03-30 16:07:05 +000051namespace {
Todd Fialab91de782014-06-27 16:52:49 +000052
53// ELF note owner definitions
54const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";
Kate Stoneb9c1b512016-09-06 20:57:50 +000055const char *const LLDB_NT_OWNER_GNU = "GNU";
56const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";
Kamil Rytarowski12801f12017-03-26 15:34:57 +000057const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD";
Kate Stoneb9c1b512016-09-06 20:57:50 +000058const char *const LLDB_NT_OWNER_CSR = "csr";
Tamas Berghammerdb037d92015-03-18 10:36:27 +000059const char *const LLDB_NT_OWNER_ANDROID = "Android";
Kate Stoneb9c1b512016-09-06 20:57:50 +000060const char *const LLDB_NT_OWNER_CORE = "CORE";
61const char *const LLDB_NT_OWNER_LINUX = "LINUX";
Todd Fialab91de782014-06-27 16:52:49 +000062
63// ELF note type definitions
Kate Stoneb9c1b512016-09-06 20:57:50 +000064const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01;
Todd Fialab91de782014-06-27 16:52:49 +000065const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4;
66
Kate Stoneb9c1b512016-09-06 20:57:50 +000067const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;
68const elf_word LLDB_NT_GNU_ABI_SIZE = 16;
Todd Fialab91de782014-06-27 16:52:49 +000069
70const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03;
71
Kate Stoneb9c1b512016-09-06 20:57:50 +000072const elf_word LLDB_NT_NETBSD_ABI_TAG = 0x01;
73const elf_word LLDB_NT_NETBSD_ABI_SIZE = 4;
Todd Fialab91de782014-06-27 16:52:49 +000074
75// GNU ABI note OS constants
Kate Stoneb9c1b512016-09-06 20:57:50 +000076const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00;
77const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01;
Todd Fialab91de782014-06-27 16:52:49 +000078const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02;
79
Greg Claytonb704b692015-10-28 18:04:38 +000080// LLDB_NT_OWNER_CORE and LLDB_NT_OWNER_LINUX note contants
Kate Stoneb9c1b512016-09-06 20:57:50 +000081#define NT_PRSTATUS 1
82#define NT_PRFPREG 2
83#define NT_PRPSINFO 3
84#define NT_TASKSTRUCT 4
85#define NT_AUXV 6
86#define NT_SIGINFO 0x53494749
87#define NT_FILE 0x46494c45
88#define NT_PRXFPREG 0x46e62b7f
89#define NT_PPC_VMX 0x100
90#define NT_PPC_SPE 0x101
91#define NT_PPC_VSX 0x102
92#define NT_386_TLS 0x200
93#define NT_386_IOPERM 0x201
94#define NT_X86_XSTATE 0x202
95#define NT_S390_HIGH_GPRS 0x300
96#define NT_S390_TIMER 0x301
97#define NT_S390_TODCMP 0x302
98#define NT_S390_TODPREG 0x303
99#define NT_S390_CTRS 0x304
100#define NT_S390_PREFIX 0x305
101#define NT_S390_LAST_BREAK 0x306
102#define NT_S390_SYSTEM_CALL 0x307
103#define NT_S390_TDB 0x308
104#define NT_S390_VXRS_LOW 0x309
105#define NT_S390_VXRS_HIGH 0x30a
106#define NT_ARM_VFP 0x400
107#define NT_ARM_TLS 0x401
108#define NT_ARM_HW_BREAK 0x402
109#define NT_ARM_HW_WATCH 0x403
110#define NT_ARM_SYSTEM_CALL 0x404
111#define NT_METAG_CBUF 0x500
112#define NT_METAG_RPIPE 0x501
113#define NT_METAG_TLS 0x502
Greg Claytonb704b692015-10-28 18:04:38 +0000114
Stephen Wilson499b40e2011-03-30 16:07:05 +0000115//===----------------------------------------------------------------------===//
116/// @class ELFRelocation
Adrian Prantld8f460e2018-05-02 16:55:16 +0000117/// Generic wrapper for ELFRel and ELFRela.
Stephen Wilson499b40e2011-03-30 16:07:05 +0000118///
119/// This helper class allows us to parse both ELFRel and ELFRela relocation
120/// entries in a generic manner.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000121class ELFRelocation {
Stephen Wilson499b40e2011-03-30 16:07:05 +0000122public:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000123 /// Constructs an ELFRelocation entry with a personality as given by @p
124 /// type.
125 ///
126 /// @param type Either DT_REL or DT_RELA. Any other value is invalid.
127 ELFRelocation(unsigned type);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000128
Kate Stoneb9c1b512016-09-06 20:57:50 +0000129 ~ELFRelocation();
Ed Maste81b4c5f2016-01-04 01:43:47 +0000130
Kate Stoneb9c1b512016-09-06 20:57:50 +0000131 bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000132
Kate Stoneb9c1b512016-09-06 20:57:50 +0000133 static unsigned RelocType32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000134
Kate Stoneb9c1b512016-09-06 20:57:50 +0000135 static unsigned RelocType64(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000136
Kate Stoneb9c1b512016-09-06 20:57:50 +0000137 static unsigned RelocSymbol32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000138
Kate Stoneb9c1b512016-09-06 20:57:50 +0000139 static unsigned RelocSymbol64(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000140
Kate Stoneb9c1b512016-09-06 20:57:50 +0000141 static unsigned RelocOffset32(const ELFRelocation &rel);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000142
Kate Stoneb9c1b512016-09-06 20:57:50 +0000143 static unsigned RelocOffset64(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000144
Kate Stoneb9c1b512016-09-06 20:57:50 +0000145 static unsigned RelocAddend32(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000146
Kate Stoneb9c1b512016-09-06 20:57:50 +0000147 static unsigned RelocAddend64(const ELFRelocation &rel);
Andrew MacPherson17220c12014-03-05 10:12:43 +0000148
Stephen Wilson499b40e2011-03-30 16:07:05 +0000149private:
Kate Stoneb9c1b512016-09-06 20:57:50 +0000150 typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;
Stephen Wilson499b40e2011-03-30 16:07:05 +0000151
Kate Stoneb9c1b512016-09-06 20:57:50 +0000152 RelocUnion reloc;
Stephen Wilson499b40e2011-03-30 16:07:05 +0000153};
154
Kate Stoneb9c1b512016-09-06 20:57:50 +0000155ELFRelocation::ELFRelocation(unsigned type) {
156 if (type == DT_REL || type == SHT_REL)
157 reloc = new ELFRel();
158 else if (type == DT_RELA || type == SHT_RELA)
159 reloc = new ELFRela();
160 else {
161 assert(false && "unexpected relocation type");
162 reloc = static_cast<ELFRel *>(NULL);
163 }
Stephen Wilson499b40e2011-03-30 16:07:05 +0000164}
165
Kate Stoneb9c1b512016-09-06 20:57:50 +0000166ELFRelocation::~ELFRelocation() {
167 if (reloc.is<ELFRel *>())
168 delete reloc.get<ELFRel *>();
169 else
170 delete reloc.get<ELFRela *>();
Stephen Wilson499b40e2011-03-30 16:07:05 +0000171}
172
Kate Stoneb9c1b512016-09-06 20:57:50 +0000173bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,
174 lldb::offset_t *offset) {
175 if (reloc.is<ELFRel *>())
176 return reloc.get<ELFRel *>()->Parse(data, offset);
177 else
178 return reloc.get<ELFRela *>()->Parse(data, offset);
Stephen Wilson499b40e2011-03-30 16:07:05 +0000179}
180
Kate Stoneb9c1b512016-09-06 20:57:50 +0000181unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {
182 if (rel.reloc.is<ELFRel *>())
183 return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>());
184 else
185 return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000186}
187
Kate Stoneb9c1b512016-09-06 20:57:50 +0000188unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {
189 if (rel.reloc.is<ELFRel *>())
190 return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>());
191 else
192 return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000193}
194
Kate Stoneb9c1b512016-09-06 20:57:50 +0000195unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {
196 if (rel.reloc.is<ELFRel *>())
197 return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>());
198 else
199 return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000200}
201
Kate Stoneb9c1b512016-09-06 20:57:50 +0000202unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {
203 if (rel.reloc.is<ELFRel *>())
204 return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>());
205 else
206 return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>());
Stephen Wilson499b40e2011-03-30 16:07:05 +0000207}
208
Kate Stoneb9c1b512016-09-06 20:57:50 +0000209unsigned ELFRelocation::RelocOffset32(const ELFRelocation &rel) {
210 if (rel.reloc.is<ELFRel *>())
211 return rel.reloc.get<ELFRel *>()->r_offset;
212 else
213 return rel.reloc.get<ELFRela *>()->r_offset;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000214}
215
Kate Stoneb9c1b512016-09-06 20:57:50 +0000216unsigned ELFRelocation::RelocOffset64(const ELFRelocation &rel) {
217 if (rel.reloc.is<ELFRel *>())
218 return rel.reloc.get<ELFRel *>()->r_offset;
219 else
220 return rel.reloc.get<ELFRela *>()->r_offset;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000221}
222
Kate Stoneb9c1b512016-09-06 20:57:50 +0000223unsigned ELFRelocation::RelocAddend32(const ELFRelocation &rel) {
224 if (rel.reloc.is<ELFRel *>())
225 return 0;
226 else
227 return rel.reloc.get<ELFRela *>()->r_addend;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000228}
229
Kate Stoneb9c1b512016-09-06 20:57:50 +0000230unsigned ELFRelocation::RelocAddend64(const ELFRelocation &rel) {
231 if (rel.reloc.is<ELFRel *>())
232 return 0;
233 else
234 return rel.reloc.get<ELFRela *>()->r_addend;
Andrew MacPherson17220c12014-03-05 10:12:43 +0000235}
236
Stephen Wilson499b40e2011-03-30 16:07:05 +0000237} // end anonymous namespace
238
Kate Stoneb9c1b512016-09-06 20:57:50 +0000239bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {
240 // Read all fields.
241 if (data.GetU32(offset, &n_namesz, 3) == NULL)
242 return false;
Ed Mastec113ff82013-12-02 17:49:13 +0000243
Adrian Prantl05097242018-04-30 16:49:04 +0000244 // The name field is required to be nul-terminated, and n_namesz includes the
245 // terminating nul in observed implementations (contrary to the ELF-64 spec).
246 // A special case is needed for cores generated by some older Linux versions,
247 // which write a note named "CORE" without a nul terminator and n_namesz = 4.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000248 if (n_namesz == 4) {
249 char buf[4];
250 if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)
251 return false;
252 if (strncmp(buf, "CORE", 4) == 0) {
253 n_name = "CORE";
254 *offset += 4;
255 return true;
Ed Mastec113ff82013-12-02 17:49:13 +0000256 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000257 }
Ed Mastec113ff82013-12-02 17:49:13 +0000258
Kate Stoneb9c1b512016-09-06 20:57:50 +0000259 const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));
260 if (cstr == NULL) {
261 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
262 if (log)
263 log->Printf("Failed to parse note name lacking nul terminator");
Ed Mastec113ff82013-12-02 17:49:13 +0000264
Kate Stoneb9c1b512016-09-06 20:57:50 +0000265 return false;
266 }
267 n_name = cstr;
268 return true;
Ed Mastec113ff82013-12-02 17:49:13 +0000269}
270
Kate Stoneb9c1b512016-09-06 20:57:50 +0000271static uint32_t kalimbaVariantFromElfFlags(const elf::elf_word e_flags) {
272 const uint32_t dsp_rev = e_flags & 0xFF;
273 uint32_t kal_arch_variant = LLDB_INVALID_CPUTYPE;
274 switch (dsp_rev) {
275 // TODO(mg11) Support more variants
276 case 10:
277 kal_arch_variant = llvm::Triple::KalimbaSubArch_v3;
278 break;
279 case 14:
280 kal_arch_variant = llvm::Triple::KalimbaSubArch_v4;
281 break;
282 case 17:
283 case 20:
284 kal_arch_variant = llvm::Triple::KalimbaSubArch_v5;
285 break;
286 default:
287 break;
288 }
289 return kal_arch_variant;
Matthew Gardiner5f675792014-08-27 12:09:39 +0000290}
291
Nitesh Jain706c5202017-03-31 11:06:25 +0000292static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) {
293 const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH;
294 uint32_t endian = header.e_ident[EI_DATA];
Kate Stoneb9c1b512016-09-06 20:57:50 +0000295 uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;
Nitesh Jain706c5202017-03-31 11:06:25 +0000296 uint32_t fileclass = header.e_ident[EI_CLASS];
297
Adrian Prantl05097242018-04-30 16:49:04 +0000298 // If there aren't any elf flags available (e.g core elf file) then return
299 // default
Nitesh Jain706c5202017-03-31 11:06:25 +0000300 // 32 or 64 bit arch (without any architecture revision) based on object file's class.
301 if (header.e_type == ET_CORE) {
302 switch (fileclass) {
303 case llvm::ELF::ELFCLASS32:
304 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
305 : ArchSpec::eMIPSSubType_mips32;
306 case llvm::ELF::ELFCLASS64:
307 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
308 : ArchSpec::eMIPSSubType_mips64;
309 default:
310 return arch_variant;
311 }
312 }
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000313
Kate Stoneb9c1b512016-09-06 20:57:50 +0000314 switch (mips_arch) {
315 case llvm::ELF::EF_MIPS_ARCH_1:
316 case llvm::ELF::EF_MIPS_ARCH_2:
317 case llvm::ELF::EF_MIPS_ARCH_32:
318 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
319 : ArchSpec::eMIPSSubType_mips32;
320 case llvm::ELF::EF_MIPS_ARCH_32R2:
321 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el
322 : ArchSpec::eMIPSSubType_mips32r2;
323 case llvm::ELF::EF_MIPS_ARCH_32R6:
324 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el
325 : ArchSpec::eMIPSSubType_mips32r6;
326 case llvm::ELF::EF_MIPS_ARCH_3:
327 case llvm::ELF::EF_MIPS_ARCH_4:
328 case llvm::ELF::EF_MIPS_ARCH_5:
329 case llvm::ELF::EF_MIPS_ARCH_64:
330 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
331 : ArchSpec::eMIPSSubType_mips64;
332 case llvm::ELF::EF_MIPS_ARCH_64R2:
333 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el
334 : ArchSpec::eMIPSSubType_mips64r2;
335 case llvm::ELF::EF_MIPS_ARCH_64R6:
336 return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el
337 : ArchSpec::eMIPSSubType_mips64r6;
338 default:
339 break;
340 }
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000341
Kate Stoneb9c1b512016-09-06 20:57:50 +0000342 return arch_variant;
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000343}
344
Kate Stoneb9c1b512016-09-06 20:57:50 +0000345static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {
346 if (header.e_machine == llvm::ELF::EM_MIPS)
Nitesh Jain706c5202017-03-31 11:06:25 +0000347 return mipsVariantFromElfFlags(header);
Mohit K. Bhakkad3df471c2015-03-17 11:43:56 +0000348
Kate Stoneb9c1b512016-09-06 20:57:50 +0000349 return llvm::ELF::EM_CSR_KALIMBA == header.e_machine
350 ? kalimbaVariantFromElfFlags(header.e_flags)
351 : LLDB_INVALID_CPUTYPE;
Matthew Gardiner5f675792014-08-27 12:09:39 +0000352}
353
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000354//! The kalimba toolchain identifies a code section as being
355//! one with the SHT_PROGBITS set in the section sh_type and the top
356//! bit in the 32-bit address field set.
357static lldb::SectionType
Kate Stoneb9c1b512016-09-06 20:57:50 +0000358kalimbaSectionType(const elf::ELFHeader &header,
359 const elf::ELFSectionHeader &sect_hdr) {
360 if (llvm::ELF::EM_CSR_KALIMBA != header.e_machine) {
Matthew Gardiner6e7b0a02014-10-15 08:21:54 +0000361 return eSectionTypeOther;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000362 }
363
364 if (llvm::ELF::SHT_NOBITS == sect_hdr.sh_type) {
365 return eSectionTypeZeroFill;
366 }
367
368 if (llvm::ELF::SHT_PROGBITS == sect_hdr.sh_type) {
369 const lldb::addr_t KAL_CODE_BIT = 1 << 31;
370 return KAL_CODE_BIT & sect_hdr.sh_addr ? eSectionTypeCode
371 : eSectionTypeData;
372 }
373
374 return eSectionTypeOther;
Matthew Gardinerf03e6d842014-09-29 08:02:24 +0000375}
376
Todd Fiala4339f3a2014-03-25 19:29:09 +0000377// Arbitrary constant used as UUID prefix for core files.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000378const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000379
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000380//------------------------------------------------------------------
381// Static methods.
382//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000383void ObjectFileELF::Initialize() {
384 PluginManager::RegisterPlugin(GetPluginNameStatic(),
385 GetPluginDescriptionStatic(), CreateInstance,
386 CreateMemoryInstance, GetModuleSpecifications);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000387}
388
Kate Stoneb9c1b512016-09-06 20:57:50 +0000389void ObjectFileELF::Terminate() {
390 PluginManager::UnregisterPlugin(CreateInstance);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000391}
392
Kate Stoneb9c1b512016-09-06 20:57:50 +0000393lldb_private::ConstString ObjectFileELF::GetPluginNameStatic() {
394 static ConstString g_name("elf");
395 return g_name;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000396}
397
Kate Stoneb9c1b512016-09-06 20:57:50 +0000398const char *ObjectFileELF::GetPluginDescriptionStatic() {
399 return "ELF object file reader.";
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000400}
401
Kate Stoneb9c1b512016-09-06 20:57:50 +0000402ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp,
403 DataBufferSP &data_sp,
404 lldb::offset_t data_offset,
405 const lldb_private::FileSpec *file,
406 lldb::offset_t file_offset,
407 lldb::offset_t length) {
408 if (!data_sp) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000409 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000410 if (!data_sp)
411 return nullptr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000412 data_offset = 0;
413 }
414
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000415 assert(data_sp);
416
417 if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset))
418 return nullptr;
419
420 const uint8_t *magic = data_sp->GetBytes() + data_offset;
421 if (!ELFHeader::MagicBytesMatch(magic))
422 return nullptr;
423
424 // Update the data to contain the entire file if it doesn't already
425 if (data_sp->GetByteSize() < length) {
Pavel Labath50251fc2017-12-21 10:54:30 +0000426 data_sp = MapFileData(*file, length, file_offset);
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000427 if (!data_sp)
428 return nullptr;
429 data_offset = 0;
430 magic = data_sp->GetBytes();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000431 }
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000432
433 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
434 if (address_size == 4 || address_size == 8) {
435 std::unique_ptr<ObjectFileELF> objfile_ap(new ObjectFileELF(
436 module_sp, data_sp, data_offset, file, file_offset, length));
Pavel Labathf760f5a2019-01-03 10:37:19 +0000437 ArchSpec spec = objfile_ap->GetArchitecture();
438 if (spec && objfile_ap->SetModulesArchitecture(spec))
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000439 return objfile_ap.release();
440 }
441
Kate Stoneb9c1b512016-09-06 20:57:50 +0000442 return NULL;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000443}
444
Kate Stoneb9c1b512016-09-06 20:57:50 +0000445ObjectFile *ObjectFileELF::CreateMemoryInstance(
446 const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
447 const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
448 if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) {
449 const uint8_t *magic = data_sp->GetBytes();
450 if (ELFHeader::MagicBytesMatch(magic)) {
451 unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
452 if (address_size == 4 || address_size == 8) {
Benjamin Kramere1a60742017-09-14 15:01:55 +0000453 std::unique_ptr<ObjectFileELF> objfile_ap(
Kate Stoneb9c1b512016-09-06 20:57:50 +0000454 new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));
Pavel Labathf760f5a2019-01-03 10:37:19 +0000455 ArchSpec spec = objfile_ap->GetArchitecture();
456 if (spec && objfile_ap->SetModulesArchitecture(spec))
Kate Stoneb9c1b512016-09-06 20:57:50 +0000457 return objfile_ap.release();
458 }
Andrew MacPherson17220c12014-03-05 10:12:43 +0000459 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000460 }
461 return NULL;
Greg Claytonc9660542012-02-05 02:38:54 +0000462}
463
Kate Stoneb9c1b512016-09-06 20:57:50 +0000464bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp,
465 lldb::addr_t data_offset,
466 lldb::addr_t data_length) {
467 if (data_sp &&
468 data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
469 const uint8_t *magic = data_sp->GetBytes() + data_offset;
470 return ELFHeader::MagicBytesMatch(magic);
471 }
472 return false;
Michael Sartain9f0013d2013-05-17 00:20:21 +0000473}
Greg Claytonc9660542012-02-05 02:38:54 +0000474
Michael Sartain9f4517a2013-07-03 01:52:14 +0000475/*
476 * crc function from http://svnweb.freebsd.org/base/head/sys/libkern/crc32.c
477 *
478 * COPYRIGHT (C) 1986 Gary S. Brown. You may use this program, or
479 * code or tables extracted from it, as desired without restriction.
480 */
Kate Stoneb9c1b512016-09-06 20:57:50 +0000481static uint32_t calc_crc32(uint32_t crc, const void *buf, size_t size) {
482 static const uint32_t g_crc32_tab[] = {
483 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f,
484 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988,
485 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2,
486 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7,
487 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9,
488 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172,
489 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c,
490 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59,
491 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423,
492 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924,
493 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106,
494 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433,
495 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d,
496 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e,
497 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950,
498 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65,
499 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7,
500 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0,
501 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa,
502 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f,
503 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81,
504 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a,
505 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84,
506 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1,
507 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb,
508 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc,
509 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e,
510 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b,
511 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55,
512 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236,
513 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28,
514 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d,
515 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f,
516 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38,
517 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242,
518 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777,
519 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69,
520 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2,
521 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc,
522 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9,
523 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693,
524 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94,
525 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d};
526 const uint8_t *p = (const uint8_t *)buf;
Michael Sartain9f4517a2013-07-03 01:52:14 +0000527
Kate Stoneb9c1b512016-09-06 20:57:50 +0000528 crc = crc ^ ~0U;
529 while (size--)
530 crc = g_crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8);
531 return crc ^ ~0U;
Michael Sartain9f4517a2013-07-03 01:52:14 +0000532}
533
Kate Stoneb9c1b512016-09-06 20:57:50 +0000534static uint32_t calc_gnu_debuglink_crc32(const void *buf, size_t size) {
535 return calc_crc32(0U, buf, size);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000536}
537
Kate Stoneb9c1b512016-09-06 20:57:50 +0000538uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32(
539 const ProgramHeaderColl &program_headers, DataExtractor &object_data) {
Todd Fiala4339f3a2014-03-25 19:29:09 +0000540
Kate Stoneb9c1b512016-09-06 20:57:50 +0000541 uint32_t core_notes_crc = 0;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000542
Pavel Labath5ea7ecd2018-12-12 14:20:28 +0000543 for (const ELFProgramHeader &H : program_headers) {
544 if (H.p_type == llvm::ELF::PT_NOTE) {
545 const elf_off ph_offset = H.p_offset;
546 const size_t ph_size = H.p_filesz;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000547
Kate Stoneb9c1b512016-09-06 20:57:50 +0000548 DataExtractor segment_data;
549 if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {
Adrian Prantl05097242018-04-30 16:49:04 +0000550 // The ELF program header contained incorrect data, probably corefile
551 // is incomplete or corrupted.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000552 break;
553 }
Todd Fiala4339f3a2014-03-25 19:29:09 +0000554
Kate Stoneb9c1b512016-09-06 20:57:50 +0000555 core_notes_crc = calc_crc32(core_notes_crc, segment_data.GetDataStart(),
556 segment_data.GetByteSize());
Todd Fiala4339f3a2014-03-25 19:29:09 +0000557 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000558 }
Todd Fiala4339f3a2014-03-25 19:29:09 +0000559
Kate Stoneb9c1b512016-09-06 20:57:50 +0000560 return core_notes_crc;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000561}
562
Kate Stoneb9c1b512016-09-06 20:57:50 +0000563static const char *OSABIAsCString(unsigned char osabi_byte) {
564#define _MAKE_OSABI_CASE(x) \
565 case x: \
566 return #x
567 switch (osabi_byte) {
568 _MAKE_OSABI_CASE(ELFOSABI_NONE);
569 _MAKE_OSABI_CASE(ELFOSABI_HPUX);
570 _MAKE_OSABI_CASE(ELFOSABI_NETBSD);
571 _MAKE_OSABI_CASE(ELFOSABI_GNU);
572 _MAKE_OSABI_CASE(ELFOSABI_HURD);
573 _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);
574 _MAKE_OSABI_CASE(ELFOSABI_AIX);
575 _MAKE_OSABI_CASE(ELFOSABI_IRIX);
576 _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);
577 _MAKE_OSABI_CASE(ELFOSABI_TRU64);
578 _MAKE_OSABI_CASE(ELFOSABI_MODESTO);
579 _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);
580 _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);
581 _MAKE_OSABI_CASE(ELFOSABI_NSK);
582 _MAKE_OSABI_CASE(ELFOSABI_AROS);
583 _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);
584 _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);
585 _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);
586 _MAKE_OSABI_CASE(ELFOSABI_ARM);
587 _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);
588 default:
589 return "<unknown-osabi>";
590 }
Todd Fialab91de782014-06-27 16:52:49 +0000591#undef _MAKE_OSABI_CASE
592}
593
Ed Mastef6a13122015-06-05 13:03:08 +0000594//
595// WARNING : This function is being deprecated
Adrian Prantl05097242018-04-30 16:49:04 +0000596// It's functionality has moved to ArchSpec::SetArchitecture This function is
597// only being kept to validate the move.
Ed Mastef6a13122015-06-05 13:03:08 +0000598//
599// TODO : Remove this function
Kate Stoneb9c1b512016-09-06 20:57:50 +0000600static bool GetOsFromOSABI(unsigned char osabi_byte,
601 llvm::Triple::OSType &ostype) {
602 switch (osabi_byte) {
603 case ELFOSABI_AIX:
604 ostype = llvm::Triple::OSType::AIX;
605 break;
606 case ELFOSABI_FREEBSD:
607 ostype = llvm::Triple::OSType::FreeBSD;
608 break;
609 case ELFOSABI_GNU:
610 ostype = llvm::Triple::OSType::Linux;
611 break;
612 case ELFOSABI_NETBSD:
613 ostype = llvm::Triple::OSType::NetBSD;
614 break;
615 case ELFOSABI_OPENBSD:
616 ostype = llvm::Triple::OSType::OpenBSD;
617 break;
618 case ELFOSABI_SOLARIS:
619 ostype = llvm::Triple::OSType::Solaris;
620 break;
621 default:
622 ostype = llvm::Triple::OSType::UnknownOS;
623 }
624 return ostype != llvm::Triple::OSType::UnknownOS;
Todd Fialab91de782014-06-27 16:52:49 +0000625}
626
Kate Stoneb9c1b512016-09-06 20:57:50 +0000627size_t ObjectFileELF::GetModuleSpecifications(
628 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
629 lldb::offset_t data_offset, lldb::offset_t file_offset,
630 lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
631 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
Todd Fialab91de782014-06-27 16:52:49 +0000632
Kate Stoneb9c1b512016-09-06 20:57:50 +0000633 const size_t initial_count = specs.GetSize();
Michael Sartainc836ae72013-05-23 20:57:03 +0000634
Kate Stoneb9c1b512016-09-06 20:57:50 +0000635 if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
636 DataExtractor data;
637 data.SetData(data_sp);
638 elf::ELFHeader header;
Pavel Labath23ccc292017-01-31 23:09:46 +0000639 lldb::offset_t header_offset = data_offset;
640 if (header.Parse(data, &header_offset)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000641 if (data_sp) {
642 ModuleSpec spec(file);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000643
Kate Stoneb9c1b512016-09-06 20:57:50 +0000644 const uint32_t sub_type = subTypeFromElfHeader(header);
645 spec.GetArchitecture().SetArchitecture(
646 eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
Matthew Gardiner5f675792014-08-27 12:09:39 +0000647
Kate Stoneb9c1b512016-09-06 20:57:50 +0000648 if (spec.GetArchitecture().IsValid()) {
649 llvm::Triple::OSType ostype;
650 llvm::Triple::VendorType vendor;
651 llvm::Triple::OSType spec_ostype =
652 spec.GetArchitecture().GetTriple().getOS();
Todd Fialab91de782014-06-27 16:52:49 +0000653
Kate Stoneb9c1b512016-09-06 20:57:50 +0000654 if (log)
655 log->Printf("ObjectFileELF::%s file '%s' module OSABI: %s",
656 __FUNCTION__, file.GetPath().c_str(),
657 OSABIAsCString(header.e_ident[EI_OSABI]));
Ed Mastef6a13122015-06-05 13:03:08 +0000658
Kate Stoneb9c1b512016-09-06 20:57:50 +0000659 // SetArchitecture should have set the vendor to unknown
660 vendor = spec.GetArchitecture().GetTriple().getVendor();
661 assert(vendor == llvm::Triple::UnknownVendor);
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +0000662 UNUSED_IF_ASSERT_DISABLED(vendor);
Ed Mastef6a13122015-06-05 13:03:08 +0000663
Kate Stoneb9c1b512016-09-06 20:57:50 +0000664 //
665 // Validate it is ok to remove GetOsFromOSABI
666 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
667 assert(spec_ostype == ostype);
668 if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
669 if (log)
670 log->Printf("ObjectFileELF::%s file '%s' set ELF module OS type "
671 "from ELF header OSABI.",
672 __FUNCTION__, file.GetPath().c_str());
673 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000674
Pavel Labath4f033122018-02-05 17:25:40 +0000675 data_sp = MapFileData(file, -1, file_offset);
676 if (data_sp)
677 data.SetData(data_sp);
Adrian Prantl05097242018-04-30 16:49:04 +0000678 // In case there is header extension in the section #0, the header we
679 // parsed above could have sentinel values for e_phnum, e_shnum, and
680 // e_shstrndx. In this case we need to reparse the header with a
681 // bigger data source to get the actual values.
Pavel Labath4f033122018-02-05 17:25:40 +0000682 if (header.HasHeaderExtension()) {
683 lldb::offset_t header_offset = data_offset;
684 header.Parse(data, &header_offset);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000685 }
Michael Sartaina7499c92013-07-01 19:45:50 +0000686
Kate Stoneb9c1b512016-09-06 20:57:50 +0000687 uint32_t gnu_debuglink_crc = 0;
688 std::string gnu_debuglink_file;
689 SectionHeaderColl section_headers;
690 lldb_private::UUID &uuid = spec.GetUUID();
Michael Sartain9f4517a2013-07-03 01:52:14 +0000691
Pavel Labathdf1a0d12017-06-20 08:11:47 +0000692 GetSectionHeaderInfo(section_headers, data, header, uuid,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000693 gnu_debuglink_file, gnu_debuglink_crc,
694 spec.GetArchitecture());
Ravitheja Addepally15f89c42016-01-19 12:55:21 +0000695
Kate Stoneb9c1b512016-09-06 20:57:50 +0000696 llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
Todd Fialab91de782014-06-27 16:52:49 +0000697
Kate Stoneb9c1b512016-09-06 20:57:50 +0000698 if (log)
699 log->Printf("ObjectFileELF::%s file '%s' module set to triple: %s "
700 "(architecture %s)",
701 __FUNCTION__, file.GetPath().c_str(),
702 spec_triple.getTriple().c_str(),
703 spec.GetArchitecture().GetArchitectureName());
Todd Fialab91de782014-06-27 16:52:49 +0000704
Kate Stoneb9c1b512016-09-06 20:57:50 +0000705 if (!uuid.IsValid()) {
706 uint32_t core_notes_crc = 0;
Todd Fiala4339f3a2014-03-25 19:29:09 +0000707
Kate Stoneb9c1b512016-09-06 20:57:50 +0000708 if (!gnu_debuglink_crc) {
Pavel Labathf9d16472017-05-15 13:02:37 +0000709 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000710 lldb_private::Timer scoped_timer(
Pavel Labathf9d16472017-05-15 13:02:37 +0000711 func_cat,
Kate Stoneb9c1b512016-09-06 20:57:50 +0000712 "Calculating module crc32 %s with size %" PRIu64 " KiB",
713 file.GetLastPathComponent().AsCString(),
Jonas Devlieghere59b78bc2018-11-01 04:45:28 +0000714 (FileSystem::Instance().GetByteSize(file) - file_offset) /
715 1024);
Todd Fiala4339f3a2014-03-25 19:29:09 +0000716
Kate Stoneb9c1b512016-09-06 20:57:50 +0000717 // For core files - which usually don't happen to have a
Zachary Turner3f4a4b32017-02-24 18:56:49 +0000718 // gnu_debuglink, and are pretty bulky - calculating whole
719 // contents crc32 would be too much of luxury. Thus we will need
720 // to fallback to something simpler.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000721 if (header.e_type == llvm::ELF::ET_CORE) {
Kate Stoneb9c1b512016-09-06 20:57:50 +0000722 ProgramHeaderColl program_headers;
Pavel Labathdf1a0d12017-06-20 08:11:47 +0000723 GetProgramHeaderInfo(program_headers, data, header);
Michael Sartainc836ae72013-05-23 20:57:03 +0000724
Kate Stoneb9c1b512016-09-06 20:57:50 +0000725 core_notes_crc =
726 CalculateELFNotesSegmentsCRC32(program_headers, data);
727 } else {
Pavel Labath4f033122018-02-05 17:25:40 +0000728 gnu_debuglink_crc = calc_gnu_debuglink_crc32(
729 data.GetDataStart(), data.GetByteSize());
Kate Stoneb9c1b512016-09-06 20:57:50 +0000730 }
731 }
Pavel Labath77c397f2018-06-29 11:20:29 +0000732 using u32le = llvm::support::ulittle32_t;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000733 if (gnu_debuglink_crc) {
734 // Use 4 bytes of crc from the .gnu_debuglink section.
Pavel Labath77c397f2018-06-29 11:20:29 +0000735 u32le data(gnu_debuglink_crc);
736 uuid = UUID::fromData(&data, sizeof(data));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000737 } else if (core_notes_crc) {
738 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
Adrian Prantl05097242018-04-30 16:49:04 +0000739 // it look different form .gnu_debuglink crc followed by 4 bytes
740 // of note segments crc.
Pavel Labath77c397f2018-06-29 11:20:29 +0000741 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
742 uuid = UUID::fromData(data, sizeof(data));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000743 }
744 }
745
746 specs.Append(spec);
747 }
748 }
749 }
750 }
751
752 return specs.GetSize() - initial_count;
Greg Claytonf4d6de62013-04-24 22:29:28 +0000753}
754
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000755//------------------------------------------------------------------
756// PluginInterface protocol
757//------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +0000758lldb_private::ConstString ObjectFileELF::GetPluginName() {
759 return GetPluginNameStatic();
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000760}
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000761
Kate Stoneb9c1b512016-09-06 20:57:50 +0000762uint32_t ObjectFileELF::GetPluginVersion() { return m_plugin_version; }
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000763//------------------------------------------------------------------
764// ObjectFile protocol
765//------------------------------------------------------------------
766
Kate Stoneb9c1b512016-09-06 20:57:50 +0000767ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
768 DataBufferSP &data_sp, lldb::offset_t data_offset,
769 const FileSpec *file, lldb::offset_t file_offset,
770 lldb::offset_t length)
771 : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
772 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
773 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
774 m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
775 if (file)
776 m_file = *file;
777 ::memset(&m_header, 0, sizeof(m_header));
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000778}
779
Kate Stoneb9c1b512016-09-06 20:57:50 +0000780ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
781 DataBufferSP &header_data_sp,
782 const lldb::ProcessSP &process_sp,
783 addr_t header_addr)
784 : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
785 m_header(), m_uuid(), m_gnu_debuglink_file(), m_gnu_debuglink_crc(0),
786 m_program_headers(), m_section_headers(), m_dynamic_symbols(),
787 m_filespec_ap(), m_entry_point_address(), m_arch_spec() {
788 ::memset(&m_header, 0, sizeof(m_header));
Andrew MacPherson17220c12014-03-05 10:12:43 +0000789}
790
Kate Stoneb9c1b512016-09-06 20:57:50 +0000791ObjectFileELF::~ObjectFileELF() {}
792
793bool ObjectFileELF::IsExecutable() const {
794 return ((m_header.e_type & ET_EXEC) != 0) || (m_header.e_entry != 0);
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000795}
796
Kate Stoneb9c1b512016-09-06 20:57:50 +0000797bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
798 bool value_is_offset) {
799 ModuleSP module_sp = GetModule();
800 if (module_sp) {
801 size_t num_loaded_sections = 0;
802 SectionList *section_list = GetSectionList();
803 if (section_list) {
804 if (!value_is_offset) {
805 bool found_offset = false;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +0000806 for (const ELFProgramHeader &H : ProgramHeaders()) {
807 if (H.p_type != PT_LOAD || H.p_offset != 0)
Kate Stoneb9c1b512016-09-06 20:57:50 +0000808 continue;
Jim Ingham5aee1622010-08-09 23:31:02 +0000809
Pavel Labath5ea7ecd2018-12-12 14:20:28 +0000810 value = value - H.p_vaddr;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000811 found_offset = true;
812 break;
Steve Pucci9e02dac2014-02-06 19:02:19 +0000813 }
Kate Stoneb9c1b512016-09-06 20:57:50 +0000814 if (!found_offset)
815 return false;
816 }
817
818 const size_t num_sections = section_list->GetSize();
819 size_t sect_idx = 0;
820
821 for (sect_idx = 0; sect_idx < num_sections; ++sect_idx) {
Adrian Prantl05097242018-04-30 16:49:04 +0000822 // Iterate through the object file sections to find all of the sections
823 // that have SHF_ALLOC in their flag bits.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000824 SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
825 if (section_sp && section_sp->Test(SHF_ALLOC)) {
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
Kate Stoneb9c1b512016-09-06 20:57:50 +0000902bool ObjectFileELF::GetUUID(lldb_private::UUID *uuid) {
903 // Need to parse the section list to get the UUIDs, so make sure that's been
904 // done.
905 if (!ParseSectionHeaders() && GetType() != ObjectFile::eTypeCoreFile)
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000906 return false;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000907
Pavel Labath77c397f2018-06-29 11:20:29 +0000908 using u32le = llvm::support::ulittle32_t;
Kate Stoneb9c1b512016-09-06 20:57:50 +0000909 if (m_uuid.IsValid()) {
910 // We have the full build id uuid.
911 *uuid = m_uuid;
912 return true;
913 } else if (GetType() == ObjectFile::eTypeCoreFile) {
914 uint32_t core_notes_crc = 0;
915
916 if (!ParseProgramHeaders())
917 return false;
918
919 core_notes_crc = CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
920
921 if (core_notes_crc) {
Adrian Prantl05097242018-04-30 16:49:04 +0000922 // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it look
923 // different form .gnu_debuglink crc - followed by 4 bytes of note
Kate Stoneb9c1b512016-09-06 20:57:50 +0000924 // segments crc.
Pavel Labath77c397f2018-06-29 11:20:29 +0000925 u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
926 m_uuid = UUID::fromData(data, sizeof(data));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000927 }
928 } else {
929 if (!m_gnu_debuglink_crc)
930 m_gnu_debuglink_crc =
931 calc_gnu_debuglink_crc32(m_data.GetDataStart(), m_data.GetByteSize());
932 if (m_gnu_debuglink_crc) {
933 // Use 4 bytes of crc from the .gnu_debuglink section.
Pavel Labath77c397f2018-06-29 11:20:29 +0000934 u32le data(m_gnu_debuglink_crc);
935 m_uuid = UUID::fromData(&data, sizeof(data));
Kate Stoneb9c1b512016-09-06 20:57:50 +0000936 }
937 }
938
939 if (m_uuid.IsValid()) {
940 *uuid = m_uuid;
941 return true;
942 }
943
944 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +0000945}
946
Kate Stoneb9c1b512016-09-06 20:57:50 +0000947lldb_private::FileSpecList ObjectFileELF::GetDebugSymbolFilePaths() {
948 FileSpecList file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000949
Kate Stoneb9c1b512016-09-06 20:57:50 +0000950 if (!m_gnu_debuglink_file.empty()) {
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +0000951 FileSpec file_spec(m_gnu_debuglink_file);
Kate Stoneb9c1b512016-09-06 20:57:50 +0000952 file_spec_list.Append(file_spec);
953 }
954 return file_spec_list;
Michael Sartaina7499c92013-07-01 19:45:50 +0000955}
956
Kate Stoneb9c1b512016-09-06 20:57:50 +0000957uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
958 size_t num_modules = ParseDependentModules();
959 uint32_t num_specs = 0;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000960
Kate Stoneb9c1b512016-09-06 20:57:50 +0000961 for (unsigned i = 0; i < num_modules; ++i) {
962 if (files.AppendIfUnique(m_filespec_ap->GetFileSpecAtIndex(i)))
963 num_specs++;
964 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000965
Kate Stoneb9c1b512016-09-06 20:57:50 +0000966 return num_specs;
Stephen Wilsonf325ba92010-07-13 23:07:23 +0000967}
968
Kate Stoneb9c1b512016-09-06 20:57:50 +0000969Address ObjectFileELF::GetImageInfoAddress(Target *target) {
970 if (!ParseDynamicSymbols())
Stephen Wilson2ab0a582011-01-15 00:08:44 +0000971 return Address();
Kate Stoneb9c1b512016-09-06 20:57:50 +0000972
973 SectionList *section_list = GetSectionList();
974 if (!section_list)
975 return Address();
976
977 // Find the SHT_DYNAMIC (.dynamic) section.
978 SectionSP dynsym_section_sp(
979 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
980 if (!dynsym_section_sp)
981 return Address();
982 assert(dynsym_section_sp->GetObjectFile() == this);
983
984 user_id_t dynsym_id = dynsym_section_sp->GetID();
985 const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
986 if (!dynsym_hdr)
987 return Address();
988
989 for (size_t i = 0; i < m_dynamic_symbols.size(); ++i) {
990 ELFDynamic &symbol = m_dynamic_symbols[i];
991
992 if (symbol.d_tag == DT_DEBUG) {
Adrian Prantl05097242018-04-30 16:49:04 +0000993 // Compute the offset as the number of previous entries plus the size of
994 // d_tag.
Kate Stoneb9c1b512016-09-06 20:57:50 +0000995 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
996 return Address(dynsym_section_sp, offset);
997 }
998 // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
999 // exists in non-PIE.
1000 else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
1001 symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
1002 target) {
1003 addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
1004 addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
1005 if (dyn_base == LLDB_INVALID_ADDRESS)
1006 return Address();
1007
Zachary Turner97206d52017-05-12 04:51:55 +00001008 Status error;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001009 if (symbol.d_tag == DT_MIPS_RLD_MAP) {
1010 // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
1011 Address addr;
1012 if (target->ReadPointerFromMemory(dyn_base + offset, false, error,
1013 addr))
1014 return addr;
1015 }
1016 if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
1017 // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
1018 // relative to the address of the tag.
1019 uint64_t rel_offset;
1020 rel_offset = target->ReadUnsignedIntegerFromMemory(
1021 dyn_base + offset, false, GetAddressByteSize(), UINT64_MAX, error);
1022 if (error.Success() && rel_offset != UINT64_MAX) {
1023 Address addr;
1024 addr_t debug_ptr_address =
1025 dyn_base + (offset - GetAddressByteSize()) + rel_offset;
1026 addr.SetOffset(debug_ptr_address);
1027 return addr;
1028 }
1029 }
1030 }
1031 }
1032
1033 return Address();
Stephen Wilson2ab0a582011-01-15 00:08:44 +00001034}
1035
Kate Stoneb9c1b512016-09-06 20:57:50 +00001036lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
1037 if (m_entry_point_address.IsValid())
Stephen Wilsond126c8c2011-03-08 04:12:15 +00001038 return m_entry_point_address;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001039
1040 if (!ParseHeader() || !IsExecutable())
1041 return m_entry_point_address;
1042
1043 SectionList *section_list = GetSectionList();
1044 addr_t offset = m_header.e_entry;
1045
1046 if (!section_list)
1047 m_entry_point_address.SetOffset(offset);
1048 else
1049 m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
1050 return m_entry_point_address;
Jim Ingham672e6f52011-03-07 23:44:08 +00001051}
1052
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001053//----------------------------------------------------------------------
1054// ParseDependentModules
1055//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001056size_t ObjectFileELF::ParseDependentModules() {
1057 if (m_filespec_ap.get())
Stephen Wilsonf325ba92010-07-13 23:07:23 +00001058 return m_filespec_ap->GetSize();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001059
1060 m_filespec_ap.reset(new FileSpecList());
1061
1062 if (!ParseSectionHeaders())
1063 return 0;
1064
1065 SectionList *section_list = GetSectionList();
1066 if (!section_list)
1067 return 0;
1068
1069 // Find the SHT_DYNAMIC section.
1070 Section *dynsym =
1071 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
1072 .get();
1073 if (!dynsym)
1074 return 0;
1075 assert(dynsym->GetObjectFile() == this);
1076
1077 const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
1078 if (!header)
1079 return 0;
1080 // sh_link: section header index of string table used by entries in the
1081 // section.
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001082 Section *dynstr = section_list->FindSectionByID(header->sh_link).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001083 if (!dynstr)
1084 return 0;
1085
1086 DataExtractor dynsym_data;
1087 DataExtractor dynstr_data;
1088 if (ReadSectionData(dynsym, dynsym_data) &&
1089 ReadSectionData(dynstr, dynstr_data)) {
1090 ELFDynamic symbol;
1091 const lldb::offset_t section_size = dynsym_data.GetByteSize();
1092 lldb::offset_t offset = 0;
1093
1094 // The only type of entries we are concerned with are tagged DT_NEEDED,
1095 // yielding the name of a required library.
1096 while (offset < section_size) {
1097 if (!symbol.Parse(dynsym_data, &offset))
1098 break;
1099
1100 if (symbol.d_tag != DT_NEEDED)
1101 continue;
1102
1103 uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
1104 const char *lib_name = dynstr_data.PeekCStr(str_index);
Jonas Devlieghere8f3be7a2018-11-01 21:05:36 +00001105 FileSpec file_spec(lib_name);
1106 FileSystem::Instance().Resolve(file_spec);
1107 m_filespec_ap->Append(file_spec);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001108 }
1109 }
1110
1111 return m_filespec_ap->GetSize();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001112}
1113
1114//----------------------------------------------------------------------
Todd Fiala4339f3a2014-03-25 19:29:09 +00001115// GetProgramHeaderInfo
1116//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001117size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001118 DataExtractor &object_data,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001119 const ELFHeader &header) {
1120 // We have already parsed the program headers
1121 if (!program_headers.empty())
Todd Fiala4339f3a2014-03-25 19:29:09 +00001122 return program_headers.size();
1123
Kate Stoneb9c1b512016-09-06 20:57:50 +00001124 // If there are no program headers to read we are done.
1125 if (header.e_phnum == 0)
1126 return 0;
1127
1128 program_headers.resize(header.e_phnum);
1129 if (program_headers.size() != header.e_phnum)
1130 return 0;
1131
1132 const size_t ph_size = header.e_phnum * header.e_phentsize;
1133 const elf_off ph_offset = header.e_phoff;
1134 DataExtractor data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001135 if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001136 return 0;
1137
1138 uint32_t idx;
1139 lldb::offset_t offset;
1140 for (idx = 0, offset = 0; idx < header.e_phnum; ++idx) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001141 if (!program_headers[idx].Parse(data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001142 break;
1143 }
1144
1145 if (idx < program_headers.size())
1146 program_headers.resize(idx);
1147
1148 return program_headers.size();
Todd Fiala4339f3a2014-03-25 19:29:09 +00001149}
1150
1151//----------------------------------------------------------------------
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001152// ParseProgramHeaders
1153//----------------------------------------------------------------------
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00001154bool ObjectFileELF::ParseProgramHeaders() {
1155 return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00001156}
1157
Zachary Turner97206d52017-05-12 04:51:55 +00001158lldb_private::Status
Kate Stoneb9c1b512016-09-06 20:57:50 +00001159ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
1160 lldb_private::ArchSpec &arch_spec,
1161 lldb_private::UUID &uuid) {
1162 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
Zachary Turner97206d52017-05-12 04:51:55 +00001163 Status error;
Todd Fialab91de782014-06-27 16:52:49 +00001164
Kate Stoneb9c1b512016-09-06 20:57:50 +00001165 lldb::offset_t offset = 0;
Michael Sartainc836ae72013-05-23 20:57:03 +00001166
Kate Stoneb9c1b512016-09-06 20:57:50 +00001167 while (true) {
1168 // Parse the note header. If this fails, bail out.
1169 const lldb::offset_t note_offset = offset;
1170 ELFNote note = ELFNote();
1171 if (!note.Parse(data, &offset)) {
1172 // We're done.
1173 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001174 }
Todd Fialab91de782014-06-27 16:52:49 +00001175
Kate Stoneb9c1b512016-09-06 20:57:50 +00001176 if (log)
1177 log->Printf("ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1178 __FUNCTION__, note.n_name.c_str(), note.n_type);
1179
1180 // Process FreeBSD ELF notes.
1181 if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1182 (note.n_type == LLDB_NT_FREEBSD_ABI_TAG) &&
1183 (note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)) {
1184 // Pull out the min version info.
1185 uint32_t version_info;
1186 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1187 error.SetErrorString("failed to read FreeBSD ABI note payload");
1188 return error;
1189 }
1190
1191 // Convert the version info into a major/minor number.
1192 const uint32_t version_major = version_info / 100000;
1193 const uint32_t version_minor = (version_info / 1000) % 100;
1194
1195 char os_name[32];
1196 snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1197 version_major, version_minor);
1198
1199 // Set the elf OS version to FreeBSD. Also clear the vendor.
1200 arch_spec.GetTriple().setOSName(os_name);
1201 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1202
1203 if (log)
1204 log->Printf("ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1205 ".%" PRIu32,
1206 __FUNCTION__, version_major, version_minor,
1207 static_cast<uint32_t>(version_info % 1000));
1208 }
1209 // Process GNU ELF notes.
1210 else if (note.n_name == LLDB_NT_OWNER_GNU) {
1211 switch (note.n_type) {
1212 case LLDB_NT_GNU_ABI_TAG:
1213 if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1214 // Pull out the min OS version supporting the ABI.
1215 uint32_t version_info[4];
1216 if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1217 nullptr) {
1218 error.SetErrorString("failed to read GNU ABI note payload");
1219 return error;
1220 }
1221
1222 // Set the OS per the OS field.
1223 switch (version_info[0]) {
1224 case LLDB_NT_GNU_ABI_OS_LINUX:
1225 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1226 arch_spec.GetTriple().setVendor(
1227 llvm::Triple::VendorType::UnknownVendor);
1228 if (log)
1229 log->Printf(
1230 "ObjectFileELF::%s detected Linux, min version %" PRIu32
1231 ".%" PRIu32 ".%" PRIu32,
1232 __FUNCTION__, version_info[1], version_info[2],
1233 version_info[3]);
1234 // FIXME we have the minimal version number, we could be propagating
1235 // that. version_info[1] = OS Major, version_info[2] = OS Minor,
1236 // version_info[3] = Revision.
1237 break;
1238 case LLDB_NT_GNU_ABI_OS_HURD:
1239 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1240 arch_spec.GetTriple().setVendor(
1241 llvm::Triple::VendorType::UnknownVendor);
1242 if (log)
1243 log->Printf("ObjectFileELF::%s detected Hurd (unsupported), min "
1244 "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1245 __FUNCTION__, version_info[1], version_info[2],
1246 version_info[3]);
1247 break;
1248 case LLDB_NT_GNU_ABI_OS_SOLARIS:
1249 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1250 arch_spec.GetTriple().setVendor(
1251 llvm::Triple::VendorType::UnknownVendor);
1252 if (log)
1253 log->Printf(
1254 "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1255 ".%" PRIu32 ".%" PRIu32,
1256 __FUNCTION__, version_info[1], version_info[2],
1257 version_info[3]);
1258 break;
1259 default:
1260 if (log)
1261 log->Printf(
1262 "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1263 ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1264 __FUNCTION__, version_info[0], version_info[1],
1265 version_info[2], version_info[3]);
1266 break;
1267 }
1268 }
1269 break;
1270
1271 case LLDB_NT_GNU_BUILD_ID_TAG:
1272 // Only bother processing this if we don't already have the uuid set.
1273 if (!uuid.IsValid()) {
1274 // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
Pavel Labath77c397f2018-06-29 11:20:29 +00001275 // build-id of a different length. Accept it as long as it's at least
1276 // 4 bytes as it will be better than our own crc32.
1277 if (note.n_descsz >= 4) {
1278 if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
1279 // Save the build id as the UUID for the module.
1280 uuid = UUID::fromData(buf, note.n_descsz);
1281 } else {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001282 error.SetErrorString("failed to read GNU_BUILD_ID note payload");
1283 return error;
1284 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001285 }
1286 }
1287 break;
1288 }
Nitesh Jain706c5202017-03-31 11:06:25 +00001289 if (arch_spec.IsMIPS() &&
1290 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
1291 // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
1292 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001293 }
1294 // Process NetBSD ELF notes.
1295 else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
1296 (note.n_type == LLDB_NT_NETBSD_ABI_TAG) &&
1297 (note.n_descsz == LLDB_NT_NETBSD_ABI_SIZE)) {
1298 // Pull out the min version info.
1299 uint32_t version_info;
1300 if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1301 error.SetErrorString("failed to read NetBSD ABI note payload");
1302 return error;
1303 }
1304
1305 // Set the elf OS version to NetBSD. Also clear the vendor.
1306 arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
1307 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1308
1309 if (log)
1310 log->Printf(
1311 "ObjectFileELF::%s detected NetBSD, min version constant %" PRIu32,
1312 __FUNCTION__, version_info);
1313 }
Kamil Rytarowski12801f12017-03-26 15:34:57 +00001314 // Process OpenBSD ELF notes.
1315 else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
1316 // Set the elf OS version to OpenBSD. Also clear the vendor.
1317 arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
1318 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1319 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001320 // Process CSR kalimba notes
1321 else if ((note.n_type == LLDB_NT_GNU_ABI_TAG) &&
1322 (note.n_name == LLDB_NT_OWNER_CSR)) {
1323 arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1324 arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::CSR);
1325
1326 // TODO At some point the description string could be processed.
Adrian Prantl05097242018-04-30 16:49:04 +00001327 // It could provide a steer towards the kalimba variant which this ELF
1328 // targets.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001329 if (note.n_descsz) {
1330 const char *cstr =
1331 data.GetCStr(&offset, llvm::alignTo(note.n_descsz, 4));
1332 (void)cstr;
1333 }
1334 } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1335 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1336 arch_spec.GetTriple().setEnvironment(
1337 llvm::Triple::EnvironmentType::Android);
1338 } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1339 // This is sometimes found in core files and usually contains extended
1340 // register info
1341 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1342 } else if (note.n_name == LLDB_NT_OWNER_CORE) {
Adrian Prantl05097242018-04-30 16:49:04 +00001343 // Parse the NT_FILE to look for stuff in paths to shared libraries As
1344 // the contents look like this in a 64 bit ELF core file: count =
1345 // 0x000000000000000a (10) page_size = 0x0000000000001000 (4096) Index
1346 // start end file_ofs path =====
1347 // ------------------ ------------------ ------------------
1348 // ------------------------------------- [ 0] 0x0000000000400000
1349 // 0x0000000000401000 0x0000000000000000 /tmp/a.out [ 1]
1350 // 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out [
1351 // 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
Kate Stoneb9c1b512016-09-06 20:57:50 +00001352 // [ 3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000
Adrian Prantl05097242018-04-30 16:49:04 +00001353 // /lib/x86_64-linux-gnu/libc-2.19.so [ 4] 0x00007fa79cba8000
1354 // 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-
1355 // gnu/libc-2.19.so [ 5] 0x00007fa79cda7000 0x00007fa79cdab000
1356 // 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so [ 6]
1357 // 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64
1358 // -linux-gnu/libc-2.19.so [ 7] 0x00007fa79cdb2000 0x00007fa79cdd5000
1359 // 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so [ 8]
1360 // 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64
1361 // -linux-gnu/ld-2.19.so [ 9] 0x00007fa79cfd5000 0x00007fa79cfd6000
1362 // 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so In the 32 bit ELFs
1363 // the count, page_size, start, end, file_ofs are uint32_t For reference:
1364 // see readelf source code (in binutils).
Kate Stoneb9c1b512016-09-06 20:57:50 +00001365 if (note.n_type == NT_FILE) {
1366 uint64_t count = data.GetAddress(&offset);
1367 const char *cstr;
1368 data.GetAddress(&offset); // Skip page size
1369 offset += count * 3 *
1370 data.GetAddressByteSize(); // Skip all start/end/file_ofs
1371 for (size_t i = 0; i < count; ++i) {
1372 cstr = data.GetCStr(&offset);
1373 if (cstr == nullptr) {
1374 error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
1375 "at an offset after the end "
1376 "(GetCStr returned nullptr)",
1377 __FUNCTION__);
1378 return error;
1379 }
1380 llvm::StringRef path(cstr);
Richard Chamberlaina0c82e12016-10-13 12:11:00 +00001381 if (path.contains("/lib/x86_64-linux-gnu") || path.contains("/lib/i386-linux-gnu")) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001382 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1383 break;
1384 }
1385 }
Nitesh Jain706c5202017-03-31 11:06:25 +00001386 if (arch_spec.IsMIPS() &&
1387 arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS)
Adrian Prantl05097242018-04-30 16:49:04 +00001388 // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
1389 // cases (e.g. compile with -nostdlib) Hence set OS to Linux
Leonard Mosescu9ba51572018-08-07 18:00:30 +00001390 arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001391 }
1392 }
1393
Adrian Prantl05097242018-04-30 16:49:04 +00001394 // Calculate the offset of the next note just in case "offset" has been
1395 // used to poke at the contents of the note data
Kate Stoneb9c1b512016-09-06 20:57:50 +00001396 offset = note_offset + note.GetByteSize();
1397 }
1398
1399 return error;
Michael Sartainc836ae72013-05-23 20:57:03 +00001400}
Michael Sartaina7499c92013-07-01 19:45:50 +00001401
Kate Stoneb9c1b512016-09-06 20:57:50 +00001402void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
1403 ArchSpec &arch_spec) {
1404 lldb::offset_t Offset = 0;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001405
Kate Stoneb9c1b512016-09-06 20:57:50 +00001406 uint8_t FormatVersion = data.GetU8(&Offset);
1407 if (FormatVersion != llvm::ARMBuildAttrs::Format_Version)
1408 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001409
Kate Stoneb9c1b512016-09-06 20:57:50 +00001410 Offset = Offset + sizeof(uint32_t); // Section Length
1411 llvm::StringRef VendorName = data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001412
Kate Stoneb9c1b512016-09-06 20:57:50 +00001413 if (VendorName != "aeabi")
1414 return;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001415
Kate Stoneb9c1b512016-09-06 20:57:50 +00001416 if (arch_spec.GetTriple().getEnvironment() ==
1417 llvm::Triple::UnknownEnvironment)
1418 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001419
Kate Stoneb9c1b512016-09-06 20:57:50 +00001420 while (Offset < length) {
1421 uint8_t Tag = data.GetU8(&Offset);
1422 uint32_t Size = data.GetU32(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001423
Kate Stoneb9c1b512016-09-06 20:57:50 +00001424 if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1425 continue;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001426
Kate Stoneb9c1b512016-09-06 20:57:50 +00001427 while (Offset < length) {
1428 uint64_t Tag = data.GetULEB128(&Offset);
1429 switch (Tag) {
1430 default:
1431 if (Tag < 32)
1432 data.GetULEB128(&Offset);
1433 else if (Tag % 2 == 0)
1434 data.GetULEB128(&Offset);
1435 else
1436 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001437
Kate Stoneb9c1b512016-09-06 20:57:50 +00001438 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001439
Kate Stoneb9c1b512016-09-06 20:57:50 +00001440 case llvm::ARMBuildAttrs::CPU_raw_name:
1441 case llvm::ARMBuildAttrs::CPU_name:
1442 data.GetCStr(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001443
Kate Stoneb9c1b512016-09-06 20:57:50 +00001444 break;
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001445
Kate Stoneb9c1b512016-09-06 20:57:50 +00001446 case llvm::ARMBuildAttrs::ABI_VFP_args: {
1447 uint64_t VFPArgs = data.GetULEB128(&Offset);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001448
Kate Stoneb9c1b512016-09-06 20:57:50 +00001449 if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1450 if (arch_spec.GetTriple().getEnvironment() ==
1451 llvm::Triple::UnknownEnvironment ||
1452 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1453 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001454
Kate Stoneb9c1b512016-09-06 20:57:50 +00001455 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1456 } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1457 if (arch_spec.GetTriple().getEnvironment() ==
1458 llvm::Triple::UnknownEnvironment ||
1459 arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1460 arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001461
Kate Stoneb9c1b512016-09-06 20:57:50 +00001462 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001463 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001464
1465 break;
1466 }
1467 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001468 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001469 }
Saleem Abdulrasoold2d15042016-04-23 16:00:15 +00001470}
Todd Fialab91de782014-06-27 16:52:49 +00001471
Michael Sartaina7499c92013-07-01 19:45:50 +00001472//----------------------------------------------------------------------
1473// GetSectionHeaderInfo
1474//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001475size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001476 DataExtractor &object_data,
Kate Stoneb9c1b512016-09-06 20:57:50 +00001477 const elf::ELFHeader &header,
1478 lldb_private::UUID &uuid,
1479 std::string &gnu_debuglink_file,
1480 uint32_t &gnu_debuglink_crc,
1481 ArchSpec &arch_spec) {
1482 // Don't reparse the section headers if we already did that.
1483 if (!section_headers.empty())
1484 return section_headers.size();
Todd Fiala6477ea82014-07-11 15:13:33 +00001485
Kate Stoneb9c1b512016-09-06 20:57:50 +00001486 // Only initialize the arch_spec to okay defaults if they're not already set.
1487 // We'll refine this with note data as we parse the notes.
1488 if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1489 llvm::Triple::OSType ostype;
1490 llvm::Triple::OSType spec_ostype;
1491 const uint32_t sub_type = subTypeFromElfHeader(header);
1492 arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1493 header.e_ident[EI_OSABI]);
Leonard Mosescu9ba51572018-08-07 18:00:30 +00001494
Adrian Prantl05097242018-04-30 16:49:04 +00001495 // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
1496 // determined based on EI_OSABI flag and the info extracted from ELF notes
1497 // (see RefineModuleDetailsFromNote). However in some cases that still
1498 // might be not enough: for example a shared library might not have any
1499 // notes at all and have EI_OSABI flag set to System V, as result the OS
1500 // will be set to UnknownOS.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001501 GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1502 spec_ostype = arch_spec.GetTriple().getOS();
1503 assert(spec_ostype == ostype);
Hafiz Abid Qadeerb1554312017-01-20 10:24:03 +00001504 UNUSED_IF_ASSERT_DISABLED(spec_ostype);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001505 }
1506
1507 if (arch_spec.GetMachine() == llvm::Triple::mips ||
1508 arch_spec.GetMachine() == llvm::Triple::mipsel ||
1509 arch_spec.GetMachine() == llvm::Triple::mips64 ||
1510 arch_spec.GetMachine() == llvm::Triple::mips64el) {
1511 switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1512 case llvm::ELF::EF_MIPS_MICROMIPS:
1513 arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
1514 break;
1515 case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1516 arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
1517 break;
1518 case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1519 arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
1520 break;
1521 default:
1522 break;
Todd Fialab91de782014-06-27 16:52:49 +00001523 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001524 }
Todd Fialab91de782014-06-27 16:52:49 +00001525
Kate Stoneb9c1b512016-09-06 20:57:50 +00001526 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1527 arch_spec.GetMachine() == llvm::Triple::thumb) {
1528 if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1529 arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1530 else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1531 arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1532 }
Jaydeep Patil501a7812015-07-16 03:51:55 +00001533
Kate Stoneb9c1b512016-09-06 20:57:50 +00001534 // If there are no section headers we are done.
1535 if (header.e_shnum == 0)
Michael Sartaina7499c92013-07-01 19:45:50 +00001536 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001537
1538 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1539
1540 section_headers.resize(header.e_shnum);
1541 if (section_headers.size() != header.e_shnum)
1542 return 0;
1543
1544 const size_t sh_size = header.e_shnum * header.e_shentsize;
1545 const elf_off sh_offset = header.e_shoff;
1546 DataExtractor sh_data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001547 if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001548 return 0;
1549
1550 uint32_t idx;
1551 lldb::offset_t offset;
1552 for (idx = 0, offset = 0; idx < header.e_shnum; ++idx) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001553 if (!section_headers[idx].Parse(sh_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001554 break;
1555 }
1556 if (idx < section_headers.size())
1557 section_headers.resize(idx);
1558
1559 const unsigned strtab_idx = header.e_shstrndx;
1560 if (strtab_idx && strtab_idx < section_headers.size()) {
1561 const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1562 const size_t byte_size = sheader.sh_size;
1563 const Elf64_Off offset = sheader.sh_offset;
1564 lldb_private::DataExtractor shstr_data;
1565
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001566 if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001567 for (SectionHeaderCollIter I = section_headers.begin();
1568 I != section_headers.end(); ++I) {
1569 static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1570 const ELFSectionHeaderInfo &sheader = *I;
1571 const uint64_t section_size =
1572 sheader.sh_type == SHT_NOBITS ? 0 : sheader.sh_size;
1573 ConstString name(shstr_data.PeekCStr(I->sh_name));
1574
1575 I->section_name = name;
1576
1577 if (arch_spec.IsMIPS()) {
1578 uint32_t arch_flags = arch_spec.GetFlags();
1579 DataExtractor data;
1580 if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1581
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001582 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1583 section_size) == section_size)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001584 // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1585 lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1586 arch_flags |= data.GetU32(&offset);
1587
1588 // The floating point ABI is at offset 7
1589 offset = 7;
1590 switch (data.GetU8(&offset)) {
1591 case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1592 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
1593 break;
1594 case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1595 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
1596 break;
1597 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1598 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
1599 break;
1600 case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1601 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
1602 break;
1603 case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1604 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
1605 break;
1606 case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1607 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
1608 break;
1609 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1610 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
1611 break;
1612 case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1613 arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
1614 break;
1615 }
1616 }
1617 }
1618 // Settings appropriate ArchSpec ABI Flags
1619 switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1620 case llvm::ELF::EF_MIPS_ABI_O32:
1621 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
1622 break;
1623 case EF_MIPS_ABI_O64:
1624 arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
1625 break;
1626 case EF_MIPS_ABI_EABI32:
1627 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
1628 break;
1629 case EF_MIPS_ABI_EABI64:
1630 arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
1631 break;
1632 default:
1633 // ABI Mask doesn't cover N32 and N64 ABI.
1634 if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1635 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
Mehdi Aminid16a6e32017-06-23 18:20:13 +00001636 else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001637 arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
1638 break;
1639 }
1640 arch_spec.SetFlags(arch_flags);
1641 }
1642
1643 if (arch_spec.GetMachine() == llvm::Triple::arm ||
1644 arch_spec.GetMachine() == llvm::Triple::thumb) {
1645 DataExtractor data;
1646
1647 if (sheader.sh_type == SHT_ARM_ATTRIBUTES && section_size != 0 &&
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001648 data.SetData(object_data, sheader.sh_offset, section_size) == section_size)
Kate Stoneb9c1b512016-09-06 20:57:50 +00001649 ParseARMAttributes(data, section_size, arch_spec);
1650 }
1651
1652 if (name == g_sect_name_gnu_debuglink) {
1653 DataExtractor data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001654 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1655 section_size) == section_size)) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001656 lldb::offset_t gnu_debuglink_offset = 0;
1657 gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1658 gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1659 data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1660 }
1661 }
1662
1663 // Process ELF note section entries.
1664 bool is_note_header = (sheader.sh_type == SHT_NOTE);
1665
1666 // The section header ".note.android.ident" is stored as a
1667 // PROGBITS type header but it is actually a note header.
1668 static ConstString g_sect_name_android_ident(".note.android.ident");
1669 if (!is_note_header && name == g_sect_name_android_ident)
1670 is_note_header = true;
1671
1672 if (is_note_header) {
1673 // Allow notes to refine module info.
1674 DataExtractor data;
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001675 if (section_size && (data.SetData(object_data, sheader.sh_offset,
1676 section_size) == section_size)) {
Zachary Turner97206d52017-05-12 04:51:55 +00001677 Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001678 if (error.Fail()) {
1679 if (log)
1680 log->Printf("ObjectFileELF::%s ELF note processing failed: %s",
1681 __FUNCTION__, error.AsCString());
1682 }
1683 }
1684 }
1685 }
1686
1687 // Make any unknown triple components to be unspecified unknowns.
1688 if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1689 arch_spec.GetTriple().setVendorName(llvm::StringRef());
1690 if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1691 arch_spec.GetTriple().setOSName(llvm::StringRef());
1692
1693 return section_headers.size();
1694 }
1695 }
1696
1697 section_headers.clear();
1698 return 0;
Michael Sartaina7499c92013-07-01 19:45:50 +00001699}
1700
Pavel Labath4d35d6b2017-05-02 10:17:30 +00001701llvm::StringRef
Kate Stoneb9c1b512016-09-06 20:57:50 +00001702ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1703 size_t pos = symbol_name.find('@');
Pavel Labath4d35d6b2017-05-02 10:17:30 +00001704 return symbol_name.substr(0, pos);
Pavel Labathc6ae7ea2015-03-04 10:25:22 +00001705}
1706
Michael Sartaina7499c92013-07-01 19:45:50 +00001707//----------------------------------------------------------------------
1708// ParseSectionHeaders
1709//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00001710size_t ObjectFileELF::ParseSectionHeaders() {
Pavel Labathdf1a0d12017-06-20 08:11:47 +00001711 return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid,
1712 m_gnu_debuglink_file, m_gnu_debuglink_crc,
1713 m_arch_spec);
Michael Sartaina7499c92013-07-01 19:45:50 +00001714}
1715
Michael Sartaina7499c92013-07-01 19:45:50 +00001716const ObjectFileELF::ELFSectionHeaderInfo *
Kate Stoneb9c1b512016-09-06 20:57:50 +00001717ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001718 if (!ParseSectionHeaders())
Michael Sartaina7499c92013-07-01 19:45:50 +00001719 return NULL;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001720
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001721 if (id < m_section_headers.size())
Kate Stoneb9c1b512016-09-06 20:57:50 +00001722 return &m_section_headers[id];
1723
1724 return NULL;
Michael Sartaina7499c92013-07-01 19:45:50 +00001725}
1726
Kate Stoneb9c1b512016-09-06 20:57:50 +00001727lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
1728 if (!name || !name[0] || !ParseSectionHeaders())
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001729 return 0;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001730 for (size_t i = 1; i < m_section_headers.size(); ++i)
1731 if (m_section_headers[i].section_name == ConstString(name))
1732 return i;
1733 return 0;
Tamas Berghammer85fadd92015-05-08 09:40:05 +00001734}
1735
Pavel Labath62a82542018-12-15 13:45:38 +00001736static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
Pavel Labathef8683a2018-12-12 15:46:18 +00001737 return llvm::StringSwitch<SectionType>(Name)
1738 .Case(".ARM.exidx", eSectionTypeARMexidx)
1739 .Case(".ARM.extab", eSectionTypeARMextab)
1740 .Cases(".bss", ".tbss", eSectionTypeZeroFill)
1741 .Cases(".data", ".tdata", eSectionTypeData)
1742 .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
1743 .Case(".debug_abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo)
1744 .Case(".debug_addr", eSectionTypeDWARFDebugAddr)
1745 .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
1746 .Case(".debug_cu_index", eSectionTypeDWARFDebugCuIndex)
1747 .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
1748 .Case(".debug_info", eSectionTypeDWARFDebugInfo)
1749 .Case(".debug_info.dwo", eSectionTypeDWARFDebugInfoDwo)
1750 .Cases(".debug_line", ".debug_line.dwo", eSectionTypeDWARFDebugLine)
1751 .Cases(".debug_line_str", ".debug_line_str.dwo",
1752 eSectionTypeDWARFDebugLineStr)
1753 .Cases(".debug_loc", ".debug_loc.dwo", eSectionTypeDWARFDebugLoc)
1754 .Cases(".debug_loclists", ".debug_loclists.dwo",
1755 eSectionTypeDWARFDebugLocLists)
1756 .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
1757 .Cases(".debug_macro", ".debug_macro.dwo", eSectionTypeDWARFDebugMacro)
1758 .Case(".debug_names", eSectionTypeDWARFDebugNames)
1759 .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
1760 .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
1761 .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
1762 .Case(".debug_rnglists", eSectionTypeDWARFDebugRngLists)
1763 .Case(".debug_str", eSectionTypeDWARFDebugStr)
1764 .Case(".debug_str.dwo", eSectionTypeDWARFDebugStrDwo)
1765 .Case(".debug_str_offsets", eSectionTypeDWARFDebugStrOffsets)
1766 .Case(".debug_str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo)
1767 .Case(".debug_types", eSectionTypeDWARFDebugTypes)
1768 .Case(".eh_frame", eSectionTypeEHFrame)
1769 .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
1770 .Case(".gosymtab", eSectionTypeGoSymtab)
1771 .Case(".text", eSectionTypeCode)
1772 .Default(eSectionTypeOther);
1773}
1774
Pavel Labath62a82542018-12-15 13:45:38 +00001775SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const {
1776 switch (H.sh_type) {
1777 case SHT_PROGBITS:
1778 if (H.sh_flags & SHF_EXECINSTR)
1779 return eSectionTypeCode;
1780 break;
1781 case SHT_SYMTAB:
1782 return eSectionTypeELFSymbolTable;
1783 case SHT_DYNSYM:
1784 return eSectionTypeELFDynamicSymbols;
1785 case SHT_RELA:
1786 case SHT_REL:
1787 return eSectionTypeELFRelocationEntries;
1788 case SHT_DYNAMIC:
1789 return eSectionTypeELFDynamicLinkInfo;
1790 }
1791 SectionType Type = GetSectionTypeFromName(H.section_name.GetStringRef());
1792 if (Type == eSectionTypeOther) {
1793 // the kalimba toolchain assumes that ELF section names are free-form.
1794 // It does support linkscripts which (can) give rise to various
1795 // arbitrarily named sections being "Code" or "Data".
1796 Type = kalimbaSectionType(m_header, H);
1797 }
1798 return Type;
1799}
1800
1801static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {
1802 switch (Type) {
1803 case eSectionTypeData:
1804 case eSectionTypeZeroFill:
1805 return arch.GetDataByteSize();
1806 case eSectionTypeCode:
1807 return arch.GetCodeByteSize();
1808 default:
1809 return 1;
1810 }
1811}
1812
1813static Permissions GetPermissions(const ELFSectionHeader &H) {
1814 Permissions Perm = Permissions(0);
1815 if (H.sh_flags & SHF_ALLOC)
1816 Perm |= ePermissionsReadable;
1817 if (H.sh_flags & SHF_WRITE)
1818 Perm |= ePermissionsWritable;
1819 if (H.sh_flags & SHF_EXECINSTR)
1820 Perm |= ePermissionsExecutable;
1821 return Perm;
1822}
1823
1824namespace {
1825// (Unlinked) ELF object files usually have 0 for every section address, meaning
1826// we need to compute synthetic addresses in order for "file addresses" from
1827// different sections to not overlap. This class handles that logic.
1828class VMAddressProvider {
1829 bool m_synthesizing;
1830 addr_t m_next;
1831
1832public:
1833 VMAddressProvider(ObjectFile::Type Type)
1834 : m_synthesizing(Type == ObjectFile::Type::eTypeObjectFile), m_next(0) {}
1835
1836 std::pair<addr_t, addr_t> GetAddressAndSize(const ELFSectionHeader &H) {
1837 addr_t address = H.sh_addr;
1838 addr_t size = H.sh_flags & SHF_ALLOC ? H.sh_size : 0;
1839 if (m_synthesizing && (H.sh_flags & SHF_ALLOC)) {
1840 m_next = llvm::alignTo(m_next, std::max<addr_t>(H.sh_addralign, 1));
1841 address = m_next;
1842 m_next += size;
1843 }
1844 return {address, size};
1845 }
1846};
1847}
1848
Kate Stoneb9c1b512016-09-06 20:57:50 +00001849void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
1850 if (!m_sections_ap.get() && ParseSectionHeaders()) {
1851 m_sections_ap.reset(new SectionList());
Andrew MacPherson17220c12014-03-05 10:12:43 +00001852
Pavel Labath62a82542018-12-15 13:45:38 +00001853 VMAddressProvider address_provider(CalculateType());
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001854 for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
Kate Stoneb9c1b512016-09-06 20:57:50 +00001855 I != m_section_headers.end(); ++I) {
1856 const ELFSectionHeaderInfo &header = *I;
1857
Davide Italiano1e6a01f2018-05-12 01:25:48 +00001858 ConstString &name = I->section_name;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001859 const uint64_t file_size =
1860 header.sh_type == SHT_NOBITS ? 0 : header.sh_size;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001861
Pavel Labath62a82542018-12-15 13:45:38 +00001862 addr_t vm_addr, vm_size;
1863 std::tie(vm_addr, vm_size) = address_provider.GetAddressAndSize(header);
Davide Italiano1e6a01f2018-05-12 01:25:48 +00001864
Pavel Labath62a82542018-12-15 13:45:38 +00001865 SectionType sect_type = GetSectionType(header);
Pavel Labathedb01272018-04-30 13:23:47 +00001866
Kate Stoneb9c1b512016-09-06 20:57:50 +00001867 const uint32_t target_bytes_size =
Pavel Labath62a82542018-12-15 13:45:38 +00001868 GetTargetByteSize(sect_type, m_arch_spec);
1869
Kate Stoneb9c1b512016-09-06 20:57:50 +00001870 elf::elf_xword log2align =
1871 (header.sh_addralign == 0) ? 0 : llvm::Log2_64(header.sh_addralign);
Ed Masted13f6912017-10-02 14:35:07 +00001872
Kate Stoneb9c1b512016-09-06 20:57:50 +00001873 SectionSP section_sp(new Section(
1874 GetModule(), // Module to which this section belongs.
1875 this, // ObjectFile to which this section belongs and should read
1876 // section data from.
1877 SectionIndex(I), // Section ID.
Davide Italiano1e6a01f2018-05-12 01:25:48 +00001878 name, // Section name.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001879 sect_type, // Section type.
Pavel Labath62a82542018-12-15 13:45:38 +00001880 vm_addr, // VM address.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001881 vm_size, // VM size in bytes of this section.
1882 header.sh_offset, // Offset of this section in the file.
1883 file_size, // Size of the section as found in the file.
1884 log2align, // Alignment of the section
1885 header.sh_flags, // Flags for this section.
1886 target_bytes_size)); // Number of host bytes per target byte
1887
Pavel Labath62a82542018-12-15 13:45:38 +00001888 section_sp->SetPermissions(GetPermissions(header));
1889 section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
Kate Stoneb9c1b512016-09-06 20:57:50 +00001890 m_sections_ap->AddSection(section_sp);
Andrew MacPherson17220c12014-03-05 10:12:43 +00001891 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00001892 }
1893
Pavel Labath3ef4eeb2018-03-09 12:30:09 +00001894 // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the
1895 // unified section list.
1896 if (GetType() != eTypeDebugInfo)
1897 unified_section_list = *m_sections_ap;
Greg Clayton3046e662013-07-10 01:23:25 +00001898}
1899
Kate Stoneb9c1b512016-09-06 20:57:50 +00001900// Find the arm/aarch64 mapping symbol character in the given symbol name.
Adrian Prantl05097242018-04-30 16:49:04 +00001901// Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
1902// recognize cases when the mapping symbol prefixed by an arbitrary string
1903// because if a symbol prefix added to each symbol in the object file with
Kate Stoneb9c1b512016-09-06 20:57:50 +00001904// objcopy then the mapping symbols are also prefixed.
1905static char FindArmAarch64MappingSymbol(const char *symbol_name) {
1906 if (!symbol_name)
1907 return '\0';
1908
1909 const char *dollar_pos = ::strchr(symbol_name, '$');
1910 if (!dollar_pos || dollar_pos[1] == '\0')
1911 return '\0';
1912
1913 if (dollar_pos[2] == '\0' || dollar_pos[2] == '.')
1914 return dollar_pos[1];
1915 return '\0';
1916}
1917
1918#define STO_MIPS_ISA (3 << 6)
1919#define STO_MICROMIPS (2 << 6)
1920#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
1921
1922// private
1923unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
1924 SectionList *section_list,
1925 const size_t num_symbols,
1926 const DataExtractor &symtab_data,
1927 const DataExtractor &strtab_data) {
1928 ELFSymbol symbol;
1929 lldb::offset_t offset = 0;
1930
1931 static ConstString text_section_name(".text");
1932 static ConstString init_section_name(".init");
1933 static ConstString fini_section_name(".fini");
1934 static ConstString ctors_section_name(".ctors");
1935 static ConstString dtors_section_name(".dtors");
1936
1937 static ConstString data_section_name(".data");
1938 static ConstString rodata_section_name(".rodata");
1939 static ConstString rodata1_section_name(".rodata1");
1940 static ConstString data2_section_name(".data1");
1941 static ConstString bss_section_name(".bss");
1942 static ConstString opd_section_name(".opd"); // For ppc64
1943
1944 // On Android the oatdata and the oatexec symbols in the oat and odex files
Adrian Prantl05097242018-04-30 16:49:04 +00001945 // covers the full .text section what causes issues with displaying unusable
1946 // symbol name to the user and very slow unwinding speed because the
1947 // instruction emulation based unwind plans try to emulate all instructions
1948 // in these symbols. Don't add these symbols to the symbol list as they have
1949 // no use for the debugger and they are causing a lot of trouble. Filtering
1950 // can't be restricted to Android because this special object file don't
1951 // contain the note section specifying the environment to Android but the
1952 // custom extension and file name makes it highly unlikely that this will
1953 // collide with anything else.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001954 ConstString file_extension = m_file.GetFileNameExtension();
Jonas Devliegheread8d48f2018-06-13 16:23:21 +00001955 bool skip_oatdata_oatexec = file_extension == ConstString(".oat") ||
1956 file_extension == ConstString(".odex");
Kate Stoneb9c1b512016-09-06 20:57:50 +00001957
Pavel Labathf760f5a2019-01-03 10:37:19 +00001958 ArchSpec arch = GetArchitecture();
Kate Stoneb9c1b512016-09-06 20:57:50 +00001959 ModuleSP module_sp(GetModule());
1960 SectionList *module_section_list =
1961 module_sp ? module_sp->GetSectionList() : nullptr;
1962
1963 // Local cache to avoid doing a FindSectionByName for each symbol. The "const
Adrian Prantl05097242018-04-30 16:49:04 +00001964 // char*" key must came from a ConstString object so they can be compared by
1965 // pointer
Kate Stoneb9c1b512016-09-06 20:57:50 +00001966 std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
1967
1968 unsigned i;
1969 for (i = 0; i < num_symbols; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00001970 if (!symbol.Parse(symtab_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00001971 break;
1972
1973 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1974 if (!symbol_name)
1975 symbol_name = "";
1976
1977 // No need to add non-section symbols that have no names
1978 if (symbol.getType() != STT_SECTION &&
1979 (symbol_name == nullptr || symbol_name[0] == '\0'))
1980 continue;
1981
1982 // Skipping oatdata and oatexec sections if it is requested. See details
Adrian Prantl05097242018-04-30 16:49:04 +00001983 // above the definition of skip_oatdata_oatexec for the reasons.
Kate Stoneb9c1b512016-09-06 20:57:50 +00001984 if (skip_oatdata_oatexec && (::strcmp(symbol_name, "oatdata") == 0 ||
1985 ::strcmp(symbol_name, "oatexec") == 0))
1986 continue;
1987
1988 SectionSP symbol_section_sp;
1989 SymbolType symbol_type = eSymbolTypeInvalid;
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001990 Elf64_Half shndx = symbol.st_shndx;
Kate Stoneb9c1b512016-09-06 20:57:50 +00001991
Pavel Labath0d38e4f2018-12-18 15:56:45 +00001992 switch (shndx) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00001993 case SHN_ABS:
1994 symbol_type = eSymbolTypeAbsolute;
1995 break;
1996 case SHN_UNDEF:
1997 symbol_type = eSymbolTypeUndefined;
1998 break;
1999 default:
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002000 symbol_section_sp = section_list->FindSectionByID(shndx);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002001 break;
2002 }
2003
2004 // If a symbol is undefined do not process it further even if it has a STT
2005 // type
2006 if (symbol_type != eSymbolTypeUndefined) {
2007 switch (symbol.getType()) {
2008 default:
2009 case STT_NOTYPE:
2010 // The symbol's type is not specified.
2011 break;
2012
2013 case STT_OBJECT:
Adrian Prantl05097242018-04-30 16:49:04 +00002014 // The symbol is associated with a data object, such as a variable, an
2015 // array, etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002016 symbol_type = eSymbolTypeData;
2017 break;
2018
2019 case STT_FUNC:
2020 // The symbol is associated with a function or other executable code.
2021 symbol_type = eSymbolTypeCode;
2022 break;
2023
2024 case STT_SECTION:
2025 // The symbol is associated with a section. Symbol table entries of
Adrian Prantl05097242018-04-30 16:49:04 +00002026 // this type exist primarily for relocation and normally have STB_LOCAL
2027 // binding.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002028 break;
2029
2030 case STT_FILE:
Adrian Prantl05097242018-04-30 16:49:04 +00002031 // Conventionally, the symbol's name gives the name of the source file
2032 // associated with the object file. A file symbol has STB_LOCAL
Kate Stoneb9c1b512016-09-06 20:57:50 +00002033 // binding, its section index is SHN_ABS, and it precedes the other
2034 // STB_LOCAL symbols for the file, if it is present.
2035 symbol_type = eSymbolTypeSourceFile;
2036 break;
2037
2038 case STT_GNU_IFUNC:
2039 // The symbol is associated with an indirect function. The actual
2040 // function will be resolved if it is referenced.
2041 symbol_type = eSymbolTypeResolver;
2042 break;
2043 }
2044 }
2045
2046 if (symbol_type == eSymbolTypeInvalid && symbol.getType() != STT_SECTION) {
2047 if (symbol_section_sp) {
2048 const ConstString &sect_name = symbol_section_sp->GetName();
2049 if (sect_name == text_section_name || sect_name == init_section_name ||
2050 sect_name == fini_section_name || sect_name == ctors_section_name ||
2051 sect_name == dtors_section_name) {
2052 symbol_type = eSymbolTypeCode;
2053 } else if (sect_name == data_section_name ||
2054 sect_name == data2_section_name ||
2055 sect_name == rodata_section_name ||
2056 sect_name == rodata1_section_name ||
2057 sect_name == bss_section_name) {
2058 symbol_type = eSymbolTypeData;
2059 }
2060 }
2061 }
2062
2063 int64_t symbol_value_offset = 0;
2064 uint32_t additional_flags = 0;
2065
2066 if (arch.IsValid()) {
2067 if (arch.GetMachine() == llvm::Triple::arm) {
2068 if (symbol.getBinding() == STB_LOCAL) {
2069 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2070 if (symbol_type == eSymbolTypeCode) {
2071 switch (mapping_symbol) {
2072 case 'a':
2073 // $a[.<any>]* - marks an ARM instruction sequence
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002074 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002075 break;
2076 case 'b':
2077 case 't':
2078 // $b[.<any>]* - marks a THUMB BL instruction sequence
2079 // $t[.<any>]* - marks a THUMB instruction sequence
2080 m_address_class_map[symbol.st_value] =
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002081 AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002082 break;
2083 case 'd':
2084 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002085 m_address_class_map[symbol.st_value] = AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002086 break;
2087 }
2088 }
2089 if (mapping_symbol)
2090 continue;
2091 }
2092 } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2093 if (symbol.getBinding() == STB_LOCAL) {
2094 char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2095 if (symbol_type == eSymbolTypeCode) {
2096 switch (mapping_symbol) {
2097 case 'x':
2098 // $x[.<any>]* - marks an A64 instruction sequence
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002099 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002100 break;
2101 case 'd':
2102 // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002103 m_address_class_map[symbol.st_value] = AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002104 break;
2105 }
2106 }
2107 if (mapping_symbol)
2108 continue;
2109 }
2110 }
2111
2112 if (arch.GetMachine() == llvm::Triple::arm) {
2113 if (symbol_type == eSymbolTypeCode) {
2114 if (symbol.st_value & 1) {
Adrian Prantl05097242018-04-30 16:49:04 +00002115 // Subtracting 1 from the address effectively unsets the low order
2116 // bit, which results in the address actually pointing to the
2117 // beginning of the symbol. This delta will be used below in
2118 // conjunction with symbol.st_value to produce the final
2119 // symbol_value that we store in the symtab.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002120 symbol_value_offset = -1;
2121 m_address_class_map[symbol.st_value ^ 1] =
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002122 AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002123 } else {
2124 // This address is ARM
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002125 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002126 }
2127 }
2128 }
2129
2130 /*
2131 * MIPS:
2132 * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2133 * MIPS).
2134 * This allows processor to switch between microMIPS and MIPS without any
2135 * need
2136 * for special mode-control register. However, apart from .debug_line,
2137 * none of
2138 * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2139 * st_other
2140 * flag to check whether the symbol is microMIPS and then set the address
2141 * class
2142 * accordingly.
2143 */
2144 const llvm::Triple::ArchType llvm_arch = arch.GetMachine();
2145 if (llvm_arch == llvm::Triple::mips ||
2146 llvm_arch == llvm::Triple::mipsel ||
2147 llvm_arch == llvm::Triple::mips64 ||
2148 llvm_arch == llvm::Triple::mips64el) {
2149 if (IS_MICROMIPS(symbol.st_other))
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002150 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002151 else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2152 symbol.st_value = symbol.st_value & (~1ull);
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002153 m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002154 } else {
2155 if (symbol_type == eSymbolTypeCode)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002156 m_address_class_map[symbol.st_value] = AddressClass::eCode;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002157 else if (symbol_type == eSymbolTypeData)
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002158 m_address_class_map[symbol.st_value] = AddressClass::eData;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002159 else
Tatyana Krasnukha04803b32018-06-26 13:06:54 +00002160 m_address_class_map[symbol.st_value] = AddressClass::eUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002161 }
2162 }
2163 }
2164
2165 // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
Adrian Prantl05097242018-04-30 16:49:04 +00002166 // symbols. See above for more details.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002167 uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2168
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002169 if (symbol_section_sp == nullptr && shndx == SHN_ABS &&
Kate Stoneb9c1b512016-09-06 20:57:50 +00002170 symbol.st_size != 0) {
2171 // We don't have a section for a symbol with non-zero size. Create a new
Adrian Prantl05097242018-04-30 16:49:04 +00002172 // section for it so the address range covered by the symbol is also
2173 // covered by the module (represented through the section list). It is
2174 // needed so module lookup for the addresses covered by this symbol will
2175 // be successfull. This case happens for absolute symbols.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002176 ConstString fake_section_name(std::string(".absolute.") + symbol_name);
2177 symbol_section_sp =
2178 std::make_shared<Section>(module_sp, this, SHN_ABS, fake_section_name,
2179 eSectionTypeAbsoluteAddress, symbol_value,
2180 symbol.st_size, 0, 0, 0, SHF_ALLOC);
2181
2182 module_section_list->AddSection(symbol_section_sp);
2183 section_list->AddSection(symbol_section_sp);
2184 }
2185
2186 if (symbol_section_sp &&
2187 CalculateType() != ObjectFile::Type::eTypeObjectFile)
2188 symbol_value -= symbol_section_sp->GetFileAddress();
2189
2190 if (symbol_section_sp && module_section_list &&
2191 module_section_list != section_list) {
2192 const ConstString &sect_name = symbol_section_sp->GetName();
2193 auto section_it = section_name_to_section.find(sect_name.GetCString());
2194 if (section_it == section_name_to_section.end())
2195 section_it =
2196 section_name_to_section
2197 .emplace(sect_name.GetCString(),
2198 module_section_list->FindSectionByName(sect_name))
2199 .first;
Pavel Labathefddda3d2017-05-02 12:40:31 +00002200 if (section_it->second)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002201 symbol_section_sp = section_it->second;
2202 }
2203
2204 bool is_global = symbol.getBinding() == STB_GLOBAL;
2205 uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2206 bool is_mangled = (symbol_name[0] == '_' && symbol_name[1] == 'Z');
2207
2208 llvm::StringRef symbol_ref(symbol_name);
2209
2210 // Symbol names may contain @VERSION suffixes. Find those and strip them
2211 // temporarily.
2212 size_t version_pos = symbol_ref.find('@');
2213 bool has_suffix = version_pos != llvm::StringRef::npos;
2214 llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2215 Mangled mangled(ConstString(symbol_bare), is_mangled);
2216
2217 // Now append the suffix back to mangled and unmangled names. Only do it if
Adrian Prantl05097242018-04-30 16:49:04 +00002218 // the demangling was successful (string is not empty).
Kate Stoneb9c1b512016-09-06 20:57:50 +00002219 if (has_suffix) {
2220 llvm::StringRef suffix = symbol_ref.substr(version_pos);
2221
2222 llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2223 if (!mangled_name.empty())
2224 mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2225
2226 ConstString demangled =
2227 mangled.GetDemangledName(lldb::eLanguageTypeUnknown);
2228 llvm::StringRef demangled_name = demangled.GetStringRef();
2229 if (!demangled_name.empty())
2230 mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2231 }
2232
2233 // In ELF all symbol should have a valid size but it is not true for some
Adrian Prantl05097242018-04-30 16:49:04 +00002234 // function symbols coming from hand written assembly. As none of the
2235 // function symbol should have 0 size we try to calculate the size for
2236 // these symbols in the symtab with saying that their original size is not
2237 // valid.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002238 bool symbol_size_valid =
2239 symbol.st_size != 0 || symbol.getType() != STT_FUNC;
2240
2241 Symbol dc_symbol(
2242 i + start_id, // ID is the original symbol table index.
2243 mangled,
2244 symbol_type, // Type of this symbol
2245 is_global, // Is this globally visible?
2246 false, // Is this symbol debug info?
2247 false, // Is this symbol a trampoline?
2248 false, // Is this symbol artificial?
2249 AddressRange(symbol_section_sp, // Section in which this symbol is
2250 // defined or null.
2251 symbol_value, // Offset in section or symbol value.
2252 symbol.st_size), // Size in bytes of this symbol.
2253 symbol_size_valid, // Symbol size is valid
2254 has_suffix, // Contains linker annotations?
2255 flags); // Symbol flags.
2256 symtab->AddSymbol(dc_symbol);
2257 }
2258 return i;
2259}
2260
2261unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
2262 user_id_t start_id,
2263 lldb_private::Section *symtab) {
2264 if (symtab->GetObjectFile() != this) {
2265 // If the symbol table section is owned by a different object file, have it
Adrian Prantl05097242018-04-30 16:49:04 +00002266 // do the parsing.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002267 ObjectFileELF *obj_file_elf =
2268 static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2269 return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2270 }
2271
2272 // Get section list for this object file.
2273 SectionList *section_list = m_sections_ap.get();
2274 if (!section_list)
2275 return 0;
2276
2277 user_id_t symtab_id = symtab->GetID();
2278 const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2279 assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2280 symtab_hdr->sh_type == SHT_DYNSYM);
2281
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002282 // sh_link: section header index of associated string table.
2283 user_id_t strtab_id = symtab_hdr->sh_link;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002284 Section *strtab = section_list->FindSectionByID(strtab_id).get();
2285
2286 if (symtab && strtab) {
2287 assert(symtab->GetObjectFile() == this);
2288 assert(strtab->GetObjectFile() == this);
2289
2290 DataExtractor symtab_data;
2291 DataExtractor strtab_data;
2292 if (ReadSectionData(symtab, symtab_data) &&
2293 ReadSectionData(strtab, strtab_data)) {
2294 size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2295
2296 return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2297 symtab_data, strtab_data);
2298 }
2299 }
2300
2301 return 0;
2302}
2303
2304size_t ObjectFileELF::ParseDynamicSymbols() {
2305 if (m_dynamic_symbols.size())
2306 return m_dynamic_symbols.size();
2307
2308 SectionList *section_list = GetSectionList();
2309 if (!section_list)
2310 return 0;
2311
2312 // Find the SHT_DYNAMIC section.
2313 Section *dynsym =
2314 section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
2315 .get();
2316 if (!dynsym)
2317 return 0;
2318 assert(dynsym->GetObjectFile() == this);
2319
2320 ELFDynamic symbol;
2321 DataExtractor dynsym_data;
2322 if (ReadSectionData(dynsym, dynsym_data)) {
2323 const lldb::offset_t section_size = dynsym_data.GetByteSize();
2324 lldb::offset_t cursor = 0;
2325
2326 while (cursor < section_size) {
2327 if (!symbol.Parse(dynsym_data, &cursor))
2328 break;
2329
2330 m_dynamic_symbols.push_back(symbol);
2331 }
2332 }
2333
2334 return m_dynamic_symbols.size();
2335}
2336
2337const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
2338 if (!ParseDynamicSymbols())
2339 return NULL;
2340
2341 DynamicSymbolCollIter I = m_dynamic_symbols.begin();
2342 DynamicSymbolCollIter E = m_dynamic_symbols.end();
2343 for (; I != E; ++I) {
2344 ELFDynamic *symbol = &*I;
2345
2346 if (symbol->d_tag == tag)
2347 return symbol;
2348 }
2349
2350 return NULL;
2351}
2352
2353unsigned ObjectFileELF::PLTRelocationType() {
2354 // DT_PLTREL
2355 // This member specifies the type of relocation entry to which the
2356 // procedure linkage table refers. The d_val member holds DT_REL or
2357 // DT_RELA, as appropriate. All relocations in a procedure linkage table
2358 // must use the same relocation.
2359 const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2360
2361 if (symbol)
2362 return symbol->d_val;
2363
2364 return 0;
2365}
2366
Adrian Prantl05097242018-04-30 16:49:04 +00002367// Returns the size of the normal plt entries and the offset of the first
2368// normal plt entry. The 0th entry in the plt table is usually a resolution
2369// entry which have different size in some architectures then the rest of the
2370// plt entries.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002371static std::pair<uint64_t, uint64_t>
2372GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
2373 const ELFSectionHeader *plt_hdr) {
2374 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2375
Adrian Prantl05097242018-04-30 16:49:04 +00002376 // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
2377 // 16 bytes. So round the entsize up by the alignment if addralign is set.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002378 elf_xword plt_entsize =
2379 plt_hdr->sh_addralign
2380 ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2381 : plt_hdr->sh_entsize;
2382
2383 // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2384 // PLT entries relocation code in general requires multiple instruction and
2385 // should be greater than 4 bytes in most cases. Try to guess correct size
2386 // just in case.
2387 if (plt_entsize <= 4) {
2388 // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
Adrian Prantl05097242018-04-30 16:49:04 +00002389 // size of the plt entries based on the number of entries and the size of
2390 // the plt section with the assumption that the size of the 0th entry is at
2391 // least as big as the size of the normal entries and it isn't much bigger
2392 // then that.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002393 if (plt_hdr->sh_addralign)
2394 plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2395 (num_relocations + 1) * plt_hdr->sh_addralign;
2396 else
2397 plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2398 }
2399
2400 elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2401
2402 return std::make_pair(plt_entsize, plt_offset);
2403}
2404
2405static unsigned ParsePLTRelocations(
2406 Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2407 const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2408 const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2409 const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2410 DataExtractor &symtab_data, DataExtractor &strtab_data) {
2411 ELFRelocation rel(rel_type);
2412 ELFSymbol symbol;
2413 lldb::offset_t offset = 0;
2414
2415 uint64_t plt_offset, plt_entsize;
2416 std::tie(plt_entsize, plt_offset) =
2417 GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2418 const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2419
2420 typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2421 reloc_info_fn reloc_type;
2422 reloc_info_fn reloc_symbol;
2423
2424 if (hdr->Is32Bit()) {
2425 reloc_type = ELFRelocation::RelocType32;
2426 reloc_symbol = ELFRelocation::RelocSymbol32;
2427 } else {
2428 reloc_type = ELFRelocation::RelocType64;
2429 reloc_symbol = ELFRelocation::RelocSymbol64;
2430 }
2431
2432 unsigned slot_type = hdr->GetRelocationJumpSlotType();
2433 unsigned i;
2434 for (i = 0; i < num_relocations; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002435 if (!rel.Parse(rel_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002436 break;
2437
2438 if (reloc_type(rel) != slot_type)
2439 continue;
2440
2441 lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2442 if (!symbol.Parse(symtab_data, &symbol_offset))
2443 break;
2444
2445 const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2446 bool is_mangled =
2447 symbol_name ? (symbol_name[0] == '_' && symbol_name[1] == 'Z') : false;
2448 uint64_t plt_index = plt_offset + i * plt_entsize;
2449
2450 Symbol jump_symbol(
2451 i + start_id, // Symbol table index
2452 symbol_name, // symbol name.
2453 is_mangled, // is the symbol name mangled?
2454 eSymbolTypeTrampoline, // Type of this symbol
2455 false, // Is this globally visible?
2456 false, // Is this symbol debug info?
2457 true, // Is this symbol a trampoline?
2458 true, // Is this symbol artificial?
2459 plt_section_sp, // Section in which this symbol is defined or null.
2460 plt_index, // Offset in section or symbol value.
2461 plt_entsize, // Size in bytes of this symbol.
2462 true, // Size is valid
2463 false, // Contains linker annotations?
2464 0); // Symbol flags.
2465
2466 symbol_table->AddSymbol(jump_symbol);
2467 }
2468
2469 return i;
2470}
2471
2472unsigned
2473ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
2474 const ELFSectionHeaderInfo *rel_hdr,
2475 user_id_t rel_id) {
2476 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2477
2478 // The link field points to the associated symbol table.
2479 user_id_t symtab_id = rel_hdr->sh_link;
2480
2481 // If the link field doesn't point to the appropriate symbol name table then
2482 // try to find it by name as some compiler don't fill in the link fields.
2483 if (!symtab_id)
2484 symtab_id = GetSectionIndexByName(".dynsym");
2485
2486 // Get PLT section. We cannot use rel_hdr->sh_info, since current linkers
2487 // point that to the .got.plt or .got section instead of .plt.
2488 user_id_t plt_id = GetSectionIndexByName(".plt");
2489
2490 if (!symtab_id || !plt_id)
2491 return 0;
2492
Kate Stoneb9c1b512016-09-06 20:57:50 +00002493 const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2494 if (!plt_hdr)
2495 return 0;
2496
2497 const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2498 if (!sym_hdr)
2499 return 0;
2500
2501 SectionList *section_list = m_sections_ap.get();
2502 if (!section_list)
2503 return 0;
2504
2505 Section *rel_section = section_list->FindSectionByID(rel_id).get();
2506 if (!rel_section)
2507 return 0;
2508
2509 SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2510 if (!plt_section_sp)
2511 return 0;
2512
2513 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2514 if (!symtab)
2515 return 0;
2516
2517 // sh_link points to associated string table.
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002518 Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002519 if (!strtab)
2520 return 0;
2521
2522 DataExtractor rel_data;
2523 if (!ReadSectionData(rel_section, rel_data))
2524 return 0;
2525
2526 DataExtractor symtab_data;
2527 if (!ReadSectionData(symtab, symtab_data))
2528 return 0;
2529
2530 DataExtractor strtab_data;
2531 if (!ReadSectionData(strtab, strtab_data))
2532 return 0;
2533
2534 unsigned rel_type = PLTRelocationType();
2535 if (!rel_type)
2536 return 0;
2537
2538 return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2539 rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2540 rel_data, symtab_data, strtab_data);
2541}
2542
Ed Masted13f6912017-10-02 14:35:07 +00002543unsigned ObjectFileELF::ApplyRelocations(
Kate Stoneb9c1b512016-09-06 20:57:50 +00002544 Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2545 const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
2546 DataExtractor &rel_data, DataExtractor &symtab_data,
2547 DataExtractor &debug_data, Section *rel_section) {
2548 ELFRelocation rel(rel_hdr->sh_type);
2549 lldb::addr_t offset = 0;
2550 const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
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 for (unsigned i = 0; i < num_relocations; ++i) {
Jonas Devliegherea6682a42018-12-15 00:15:33 +00002564 if (!rel.Parse(rel_data, &offset))
Kate Stoneb9c1b512016-09-06 20:57:50 +00002565 break;
2566
2567 Symbol *symbol = NULL;
2568
2569 if (hdr->Is32Bit()) {
2570 switch (reloc_type(rel)) {
2571 case R_386_32:
2572 case R_386_PC32:
2573 default:
Zachary Turnera6d54642017-12-02 00:15:29 +00002574 // FIXME: This asserts with this input:
2575 //
2576 // foo.cpp
2577 // int main(int argc, char **argv) { return 0; }
2578 //
2579 // clang++.exe --target=i686-unknown-linux-gnu -g -c foo.cpp -o foo.o
2580 //
2581 // and running this on the foo.o module.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002582 assert(false && "unexpected relocation type");
2583 }
2584 } else {
2585 switch (reloc_type(rel)) {
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002586 case R_AARCH64_ABS64:
Kate Stoneb9c1b512016-09-06 20:57:50 +00002587 case R_X86_64_64: {
2588 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2589 if (symbol) {
2590 addr_t value = symbol->GetAddressRef().GetFileAddress();
2591 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2592 uint64_t *dst = reinterpret_cast<uint64_t *>(
2593 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2594 ELFRelocation::RelocOffset64(rel));
Davide Italianob37f1ec2018-11-06 17:11:34 +00002595 uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
2596 memcpy(dst, &val_offset, sizeof(uint64_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002597 }
2598 break;
2599 }
2600 case R_X86_64_32:
Stephane Sezer9e2fe8b2018-08-17 00:35:47 +00002601 case R_X86_64_32S:
2602 case R_AARCH64_ABS32: {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002603 symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2604 if (symbol) {
2605 addr_t value = symbol->GetAddressRef().GetFileAddress();
2606 value += ELFRelocation::RelocAddend32(rel);
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002607 if ((reloc_type(rel) == R_X86_64_32 && (value > UINT32_MAX)) ||
Stephane Sezer0c679b72018-08-06 22:21:28 +00002608 (reloc_type(rel) == R_X86_64_32S &&
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002609 ((int64_t)value > INT32_MAX && (int64_t)value < INT32_MIN)) ||
2610 (reloc_type(rel) == R_AARCH64_ABS32 &&
2611 ((int64_t)value > INT32_MAX && (int64_t)value < INT32_MIN))) {
Stephane Sezer9e2fe8b2018-08-17 00:35:47 +00002612 Log *log =
2613 lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES);
2614 log->Printf("Failed to apply debug info relocations");
Nathan Lanza6868d2d2018-11-05 22:18:00 +00002615 break;
Stephane Sezer9e2fe8b2018-08-17 00:35:47 +00002616 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00002617 uint32_t truncated_addr = (value & 0xFFFFFFFF);
2618 DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2619 uint32_t *dst = reinterpret_cast<uint32_t *>(
2620 data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2621 ELFRelocation::RelocOffset32(rel));
Davide Italianob37f1ec2018-11-06 17:11:34 +00002622 memcpy(dst, &truncated_addr, sizeof(uint32_t));
Kate Stoneb9c1b512016-09-06 20:57:50 +00002623 }
2624 break;
2625 }
2626 case R_X86_64_PC32:
2627 default:
2628 assert(false && "unexpected relocation type");
2629 }
2630 }
2631 }
2632
2633 return 0;
2634}
2635
2636unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
Ed Masted13f6912017-10-02 14:35:07 +00002637 user_id_t rel_id,
2638 lldb_private::Symtab *thetab) {
Kate Stoneb9c1b512016-09-06 20:57:50 +00002639 assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2640
2641 // Parse in the section list if needed.
2642 SectionList *section_list = GetSectionList();
2643 if (!section_list)
2644 return 0;
2645
Pavel Labath0d38e4f2018-12-18 15:56:45 +00002646 user_id_t symtab_id = rel_hdr->sh_link;
2647 user_id_t debug_id = rel_hdr->sh_info;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002648
2649 const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2650 if (!symtab_hdr)
2651 return 0;
2652
2653 const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
2654 if (!debug_hdr)
2655 return 0;
2656
2657 Section *rel = section_list->FindSectionByID(rel_id).get();
2658 if (!rel)
2659 return 0;
2660
2661 Section *symtab = section_list->FindSectionByID(symtab_id).get();
2662 if (!symtab)
2663 return 0;
2664
2665 Section *debug = section_list->FindSectionByID(debug_id).get();
2666 if (!debug)
2667 return 0;
2668
2669 DataExtractor rel_data;
2670 DataExtractor symtab_data;
2671 DataExtractor debug_data;
2672
Ed Masted13f6912017-10-02 14:35:07 +00002673 if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&
2674 GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&
2675 GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {
2676 ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
2677 rel_data, symtab_data, debug_data, debug);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002678 }
2679
2680 return 0;
2681}
2682
2683Symtab *ObjectFileELF::GetSymtab() {
2684 ModuleSP module_sp(GetModule());
2685 if (!module_sp)
2686 return NULL;
2687
2688 // We always want to use the main object file so we (hopefully) only have one
Adrian Prantl05097242018-04-30 16:49:04 +00002689 // cached copy of our symtab, dynamic sections, etc.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002690 ObjectFile *module_obj_file = module_sp->GetObjectFile();
2691 if (module_obj_file && module_obj_file != this)
2692 return module_obj_file->GetSymtab();
2693
2694 if (m_symtab_ap.get() == NULL) {
2695 SectionList *section_list = module_sp->GetSectionList();
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002696 if (!section_list)
Kate Stoneb9c1b512016-09-06 20:57:50 +00002697 return NULL;
Ashok Thirumurthi35729bb2013-09-24 15:34:13 +00002698
Kate Stoneb9c1b512016-09-06 20:57:50 +00002699 uint64_t symbol_id = 0;
2700 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002701
Kate Stoneb9c1b512016-09-06 20:57:50 +00002702 // Sharable objects and dynamic executables usually have 2 distinct symbol
2703 // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
Adrian Prantl05097242018-04-30 16:49:04 +00002704 // smaller version of the symtab that only contains global symbols. The
2705 // information found in the dynsym is therefore also found in the symtab,
2706 // while the reverse is not necessarily true.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002707 Section *symtab =
2708 section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
2709 if (!symtab) {
2710 // The symtab section is non-allocable and can be stripped, so if it
Adrian Prantl05097242018-04-30 16:49:04 +00002711 // doesn't exist then use the dynsym section which should always be
2712 // there.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002713 symtab =
2714 section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
2715 .get();
2716 }
2717 if (symtab) {
2718 m_symtab_ap.reset(new Symtab(symtab->GetObjectFile()));
2719 symbol_id += ParseSymbolTable(m_symtab_ap.get(), symbol_id, symtab);
2720 }
2721
2722 // DT_JMPREL
2723 // If present, this entry's d_ptr member holds the address of
2724 // relocation
2725 // entries associated solely with the procedure linkage table.
2726 // Separating
2727 // these relocation entries lets the dynamic linker ignore them during
2728 // process initialization, if lazy binding is enabled. If this entry is
2729 // present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
2730 // also be present.
2731 const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
2732 if (symbol) {
2733 // Synthesize trampoline symbols to help navigate the PLT.
2734 addr_t addr = symbol->d_ptr;
2735 Section *reloc_section =
2736 section_list->FindSectionContainingFileAddress(addr).get();
2737 if (reloc_section) {
2738 user_id_t reloc_id = reloc_section->GetID();
2739 const ELFSectionHeaderInfo *reloc_header =
2740 GetSectionHeaderByIndex(reloc_id);
2741 assert(reloc_header);
2742
2743 if (m_symtab_ap == nullptr)
2744 m_symtab_ap.reset(new Symtab(reloc_section->GetObjectFile()));
2745
2746 ParseTrampolineSymbols(m_symtab_ap.get(), symbol_id, reloc_header,
2747 reloc_id);
2748 }
2749 }
2750
2751 DWARFCallFrameInfo *eh_frame = GetUnwindTable().GetEHFrameInfo();
2752 if (eh_frame) {
2753 if (m_symtab_ap == nullptr)
2754 m_symtab_ap.reset(new Symtab(this));
2755 ParseUnwindSymbols(m_symtab_ap.get(), eh_frame);
2756 }
2757
2758 // If we still don't have any symtab then create an empty instance to avoid
Adrian Prantl05097242018-04-30 16:49:04 +00002759 // do the section lookup next time.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002760 if (m_symtab_ap == nullptr)
2761 m_symtab_ap.reset(new Symtab(this));
Davide Italiano407c6912018-11-02 21:59:14 +00002762
2763 m_symtab_ap->CalculateSymbolSizes();
Kate Stoneb9c1b512016-09-06 20:57:50 +00002764 }
2765
Ed Masted13f6912017-10-02 14:35:07 +00002766 return m_symtab_ap.get();
2767}
2768
2769void ObjectFileELF::RelocateSection(lldb_private::Section *section)
2770{
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002771 static const char *debug_prefix = ".debug";
Ed Masted13f6912017-10-02 14:35:07 +00002772
Adrian Prantl05097242018-04-30 16:49:04 +00002773 // Set relocated bit so we stop getting called, regardless of whether we
2774 // actually relocate.
Ed Masted13f6912017-10-02 14:35:07 +00002775 section->SetIsRelocated(true);
2776
2777 // We only relocate in ELF relocatable files
2778 if (CalculateType() != eTypeObjectFile)
2779 return;
2780
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002781 const char *section_name = section->GetName().GetCString();
Ed Masted13f6912017-10-02 14:35:07 +00002782 // Can't relocate that which can't be named
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002783 if (section_name == nullptr)
Ed Masted13f6912017-10-02 14:35:07 +00002784 return;
2785
2786 // We don't relocate non-debug sections at the moment
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002787 if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
Ed Masted13f6912017-10-02 14:35:07 +00002788 return;
2789
2790 // Relocation section names to look for
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002791 std::string needle = std::string(".rel") + section_name;
2792 std::string needlea = std::string(".rela") + section_name;
Ed Masted13f6912017-10-02 14:35:07 +00002793
Kate Stoneb9c1b512016-09-06 20:57:50 +00002794 for (SectionHeaderCollIter I = m_section_headers.begin();
2795 I != m_section_headers.end(); ++I) {
2796 if (I->sh_type == SHT_RELA || I->sh_type == SHT_REL) {
Ed Masted13f6912017-10-02 14:35:07 +00002797 const char *hay_name = I->section_name.GetCString();
2798 if (hay_name == nullptr)
2799 continue;
2800 if (needle == hay_name || needlea == hay_name) {
2801 const ELFSectionHeader &reloc_header = *I;
2802 user_id_t reloc_id = SectionIndex(I);
2803 RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
2804 break;
Kate Stoneb9c1b512016-09-06 20:57:50 +00002805 }
2806 }
2807 }
Tamas Berghammer6b63b142016-02-18 11:12:18 +00002808}
Tamas Berghammer5bfd4d02016-02-10 12:10:58 +00002809
Kate Stoneb9c1b512016-09-06 20:57:50 +00002810void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
2811 DWARFCallFrameInfo *eh_frame) {
2812 SectionList *section_list = GetSectionList();
2813 if (!section_list)
2814 return;
2815
2816 // First we save the new symbols into a separate list and add them to the
Adrian Prantl05097242018-04-30 16:49:04 +00002817 // symbol table after we colleced all symbols we want to add. This is
Davide Italiano1e6a01f2018-05-12 01:25:48 +00002818 // neccessary because adding a new symbol invalidates the internal index of
Adrian Prantl05097242018-04-30 16:49:04 +00002819 // the symtab what causing the next lookup to be slow because it have to
2820 // recalculate the index first.
Kate Stoneb9c1b512016-09-06 20:57:50 +00002821 std::vector<Symbol> new_symbols;
2822
2823 eh_frame->ForEachFDEEntries([this, symbol_table, section_list, &new_symbols](
2824 lldb::addr_t file_addr, uint32_t size, dw_offset_t) {
2825 Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
2826 if (symbol) {
2827 if (!symbol->GetByteSizeIsValid()) {
2828 symbol->SetByteSize(size);
2829 symbol->SetSizeIsSynthesized(true);
2830 }
2831 } else {
2832 SectionSP section_sp =
2833 section_list->FindSectionContainingFileAddress(file_addr);
2834 if (section_sp) {
2835 addr_t offset = file_addr - section_sp->GetFileAddress();
2836 const char *symbol_name = GetNextSyntheticSymbolName().GetCString();
2837 uint64_t symbol_id = symbol_table->GetNumSymbols();
2838 Symbol eh_symbol(
2839 symbol_id, // Symbol table index.
2840 symbol_name, // Symbol name.
2841 false, // Is the symbol name mangled?
2842 eSymbolTypeCode, // Type of this symbol.
2843 true, // Is this globally visible?
2844 false, // Is this symbol debug info?
2845 false, // Is this symbol a trampoline?
2846 true, // Is this symbol artificial?
2847 section_sp, // Section in which this symbol is defined or null.
2848 offset, // Offset in section or symbol value.
2849 0, // Size: Don't specify the size as an FDE can
2850 false, // Size is valid: cover multiple symbols.
2851 false, // Contains linker annotations?
2852 0); // Symbol flags.
2853 new_symbols.push_back(eh_symbol);
2854 }
2855 }
2856 return true;
2857 });
2858
2859 for (const Symbol &s : new_symbols)
2860 symbol_table->AddSymbol(s);
2861}
2862
2863bool ObjectFileELF::IsStripped() {
2864 // TODO: determine this for ELF
2865 return false;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002866}
2867
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002868//===----------------------------------------------------------------------===//
2869// Dump
2870//
2871// Dump the specifics of the runtime file container (such as any headers
2872// segments, sections, etc).
2873//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002874void ObjectFileELF::Dump(Stream *s) {
2875 ModuleSP module_sp(GetModule());
2876 if (!module_sp) {
2877 return;
2878 }
Adrian McCarthy543725c2016-04-04 21:21:49 +00002879
Kate Stoneb9c1b512016-09-06 20:57:50 +00002880 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
2881 s->Printf("%p: ", static_cast<void *>(this));
2882 s->Indent();
2883 s->PutCString("ObjectFileELF");
Adrian McCarthy543725c2016-04-04 21:21:49 +00002884
Pavel Labathf760f5a2019-01-03 10:37:19 +00002885 ArchSpec header_arch = GetArchitecture();
Adrian McCarthy543725c2016-04-04 21:21:49 +00002886
Kate Stoneb9c1b512016-09-06 20:57:50 +00002887 *s << ", file = '" << m_file
2888 << "', arch = " << header_arch.GetArchitectureName() << "\n";
Adrian McCarthy543725c2016-04-04 21:21:49 +00002889
Kate Stoneb9c1b512016-09-06 20:57:50 +00002890 DumpELFHeader(s, m_header);
2891 s->EOL();
2892 DumpELFProgramHeaders(s);
2893 s->EOL();
2894 DumpELFSectionHeaders(s);
2895 s->EOL();
2896 SectionList *section_list = GetSectionList();
2897 if (section_list)
2898 section_list->Dump(s, NULL, true, UINT32_MAX);
2899 Symtab *symtab = GetSymtab();
2900 if (symtab)
2901 symtab->Dump(s, NULL, eSortOrderNone);
2902 s->EOL();
2903 DumpDependentModules(s);
2904 s->EOL();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002905}
2906
2907//----------------------------------------------------------------------
2908// DumpELFHeader
2909//
2910// Dump the ELF header to the specified output stream
2911//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002912void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
2913 s->PutCString("ELF Header\n");
2914 s->Printf("e_ident[EI_MAG0 ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
2915 s->Printf("e_ident[EI_MAG1 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
2916 header.e_ident[EI_MAG1]);
2917 s->Printf("e_ident[EI_MAG2 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
2918 header.e_ident[EI_MAG2]);
2919 s->Printf("e_ident[EI_MAG3 ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
2920 header.e_ident[EI_MAG3]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002921
Kate Stoneb9c1b512016-09-06 20:57:50 +00002922 s->Printf("e_ident[EI_CLASS ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
2923 s->Printf("e_ident[EI_DATA ] = 0x%2.2x ", header.e_ident[EI_DATA]);
2924 DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
2925 s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
2926 s->Printf("e_ident[EI_PAD ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002927
Kate Stoneb9c1b512016-09-06 20:57:50 +00002928 s->Printf("e_type = 0x%4.4x ", header.e_type);
2929 DumpELFHeader_e_type(s, header.e_type);
2930 s->Printf("\ne_machine = 0x%4.4x\n", header.e_machine);
2931 s->Printf("e_version = 0x%8.8x\n", header.e_version);
2932 s->Printf("e_entry = 0x%8.8" PRIx64 "\n", header.e_entry);
2933 s->Printf("e_phoff = 0x%8.8" PRIx64 "\n", header.e_phoff);
2934 s->Printf("e_shoff = 0x%8.8" PRIx64 "\n", header.e_shoff);
2935 s->Printf("e_flags = 0x%8.8x\n", header.e_flags);
2936 s->Printf("e_ehsize = 0x%4.4x\n", header.e_ehsize);
2937 s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
Pavel Labath23ccc292017-01-31 23:09:46 +00002938 s->Printf("e_phnum = 0x%8.8x\n", header.e_phnum);
Kate Stoneb9c1b512016-09-06 20:57:50 +00002939 s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
Pavel Labath23ccc292017-01-31 23:09:46 +00002940 s->Printf("e_shnum = 0x%8.8x\n", header.e_shnum);
2941 s->Printf("e_shstrndx = 0x%8.8x\n", header.e_shstrndx);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002942}
2943
2944//----------------------------------------------------------------------
2945// DumpELFHeader_e_type
2946//
2947// Dump an token value for the ELF header member e_type
2948//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002949void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
2950 switch (e_type) {
2951 case ET_NONE:
2952 *s << "ET_NONE";
2953 break;
2954 case ET_REL:
2955 *s << "ET_REL";
2956 break;
2957 case ET_EXEC:
2958 *s << "ET_EXEC";
2959 break;
2960 case ET_DYN:
2961 *s << "ET_DYN";
2962 break;
2963 case ET_CORE:
2964 *s << "ET_CORE";
2965 break;
2966 default:
2967 break;
2968 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002969}
2970
2971//----------------------------------------------------------------------
2972// DumpELFHeader_e_ident_EI_DATA
2973//
2974// Dump an token value for the ELF header member e_ident[EI_DATA]
2975//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002976void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
2977 unsigned char ei_data) {
2978 switch (ei_data) {
2979 case ELFDATANONE:
2980 *s << "ELFDATANONE";
2981 break;
2982 case ELFDATA2LSB:
2983 *s << "ELFDATA2LSB - Little Endian";
2984 break;
2985 case ELFDATA2MSB:
2986 *s << "ELFDATA2MSB - Big Endian";
2987 break;
2988 default:
2989 break;
2990 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002991}
2992
Chris Lattner30fdc8d2010-06-08 16:52:24 +00002993//----------------------------------------------------------------------
2994// DumpELFProgramHeader
2995//
2996// Dump a single ELF program header to the specified output stream
2997//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00002998void ObjectFileELF::DumpELFProgramHeader(Stream *s,
2999 const ELFProgramHeader &ph) {
3000 DumpELFProgramHeader_p_type(s, ph.p_type);
3001 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3002 ph.p_vaddr, ph.p_paddr);
3003 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3004 ph.p_flags);
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003005
Kate Stoneb9c1b512016-09-06 20:57:50 +00003006 DumpELFProgramHeader_p_flags(s, ph.p_flags);
3007 s->Printf(") %8.8" PRIx64, ph.p_align);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003008}
3009
3010//----------------------------------------------------------------------
3011// DumpELFProgramHeader_p_type
3012//
Adrian Prantl05097242018-04-30 16:49:04 +00003013// Dump an token value for the ELF program header member p_type which describes
3014// the type of the program header
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003015// ----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003016void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
3017 const int kStrWidth = 15;
3018 switch (p_type) {
3019 CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3020 CASE_AND_STREAM(s, PT_LOAD, kStrWidth);
3021 CASE_AND_STREAM(s, PT_DYNAMIC, kStrWidth);
3022 CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3023 CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3024 CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3025 CASE_AND_STREAM(s, PT_PHDR, kStrWidth);
3026 CASE_AND_STREAM(s, PT_TLS, kStrWidth);
Filipe Cabecinhas477d86d2013-05-23 23:01:14 +00003027 CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003028 default:
3029 s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3030 break;
3031 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003032}
3033
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003034//----------------------------------------------------------------------
3035// DumpELFProgramHeader_p_flags
3036//
3037// Dump an token value for the ELF program header member p_flags
3038//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003039void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
3040 *s << ((p_flags & PF_X) ? "PF_X" : " ")
3041 << (((p_flags & PF_X) && (p_flags & PF_W)) ? '+' : ' ')
3042 << ((p_flags & PF_W) ? "PF_W" : " ")
3043 << (((p_flags & PF_W) && (p_flags & PF_R)) ? '+' : ' ')
3044 << ((p_flags & PF_R) ? "PF_R" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003045}
3046
3047//----------------------------------------------------------------------
3048// DumpELFProgramHeaders
3049//
3050// Dump all of the ELF program header to the specified output stream
3051//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003052void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
3053 if (!ParseProgramHeaders())
3054 return;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003055
Kate Stoneb9c1b512016-09-06 20:57:50 +00003056 s->PutCString("Program Headers\n");
3057 s->PutCString("IDX p_type p_offset p_vaddr p_paddr "
3058 "p_filesz p_memsz p_flags p_align\n");
3059 s->PutCString("==== --------------- -------- -------- -------- "
3060 "-------- -------- ------------------------- --------\n");
Ed Maste3a8ab6e2015-02-23 15:33:11 +00003061
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003062 for (const auto &H : llvm::enumerate(m_program_headers)) {
3063 s->Format("[{0,2}] ", H.index());
3064 ObjectFileELF::DumpELFProgramHeader(s, H.value());
Kate Stoneb9c1b512016-09-06 20:57:50 +00003065 s->EOL();
3066 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003067}
3068
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003069//----------------------------------------------------------------------
3070// DumpELFSectionHeader
3071//
3072// Dump a single ELF section header to the specified output stream
3073//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003074void ObjectFileELF::DumpELFSectionHeader(Stream *s,
3075 const ELFSectionHeaderInfo &sh) {
3076 s->Printf("%8.8x ", sh.sh_name);
3077 DumpELFSectionHeader_sh_type(s, sh.sh_type);
3078 s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3079 DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
3080 s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3081 sh.sh_offset, sh.sh_size);
3082 s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3083 s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003084}
3085
3086//----------------------------------------------------------------------
3087// DumpELFSectionHeader_sh_type
3088//
3089// Dump an token value for the ELF section header member sh_type which
3090// describes the type of the section
3091//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003092void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
3093 const int kStrWidth = 12;
3094 switch (sh_type) {
3095 CASE_AND_STREAM(s, SHT_NULL, kStrWidth);
3096 CASE_AND_STREAM(s, SHT_PROGBITS, kStrWidth);
3097 CASE_AND_STREAM(s, SHT_SYMTAB, kStrWidth);
3098 CASE_AND_STREAM(s, SHT_STRTAB, kStrWidth);
3099 CASE_AND_STREAM(s, SHT_RELA, kStrWidth);
3100 CASE_AND_STREAM(s, SHT_HASH, kStrWidth);
3101 CASE_AND_STREAM(s, SHT_DYNAMIC, kStrWidth);
3102 CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3103 CASE_AND_STREAM(s, SHT_NOBITS, kStrWidth);
3104 CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3105 CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3106 CASE_AND_STREAM(s, SHT_DYNSYM, kStrWidth);
3107 CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3108 CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3109 CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3110 CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3111 default:
3112 s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3113 break;
3114 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003115}
3116
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003117//----------------------------------------------------------------------
3118// DumpELFSectionHeader_sh_flags
3119//
3120// Dump an token value for the ELF section header member sh_flags
3121//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003122void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
3123 elf_xword sh_flags) {
3124 *s << ((sh_flags & SHF_WRITE) ? "WRITE" : " ")
3125 << (((sh_flags & SHF_WRITE) && (sh_flags & SHF_ALLOC)) ? '+' : ' ')
3126 << ((sh_flags & SHF_ALLOC) ? "ALLOC" : " ")
3127 << (((sh_flags & SHF_ALLOC) && (sh_flags & SHF_EXECINSTR)) ? '+' : ' ')
3128 << ((sh_flags & SHF_EXECINSTR) ? "EXECINSTR" : " ");
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003129}
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003130
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003131//----------------------------------------------------------------------
3132// DumpELFSectionHeaders
3133//
3134// Dump all of the ELF section header to the specified output stream
3135//----------------------------------------------------------------------
Kate Stoneb9c1b512016-09-06 20:57:50 +00003136void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
3137 if (!ParseSectionHeaders())
3138 return;
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003139
Kate Stoneb9c1b512016-09-06 20:57:50 +00003140 s->PutCString("Section Headers\n");
3141 s->PutCString("IDX name type flags "
3142 "addr offset size link info addralgn "
3143 "entsize Name\n");
3144 s->PutCString("==== -------- ------------ -------------------------------- "
3145 "-------- -------- -------- -------- -------- -------- "
3146 "-------- ====================\n");
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003147
Kate Stoneb9c1b512016-09-06 20:57:50 +00003148 uint32_t idx = 0;
3149 for (SectionHeaderCollConstIter I = m_section_headers.begin();
3150 I != m_section_headers.end(); ++I, ++idx) {
3151 s->Printf("[%2u] ", idx);
3152 ObjectFileELF::DumpELFSectionHeader(s, *I);
3153 const char *section_name = I->section_name.AsCString("");
3154 if (section_name)
3155 *s << ' ' << section_name << "\n";
3156 }
Stephen Wilsonf325ba92010-07-13 23:07:23 +00003157}
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003158
Kate Stoneb9c1b512016-09-06 20:57:50 +00003159void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
3160 size_t num_modules = ParseDependentModules();
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003161
Kate Stoneb9c1b512016-09-06 20:57:50 +00003162 if (num_modules > 0) {
3163 s->PutCString("Dependent Modules:\n");
3164 for (unsigned i = 0; i < num_modules; ++i) {
3165 const FileSpec &spec = m_filespec_ap->GetFileSpecAtIndex(i);
3166 s->Printf(" %s\n", spec.GetFilename().GetCString());
3167 }
3168 }
3169}
3170
Pavel Labathf760f5a2019-01-03 10:37:19 +00003171ArchSpec ObjectFileELF::GetArchitecture() {
Kate Stoneb9c1b512016-09-06 20:57:50 +00003172 if (!ParseHeader())
Pavel Labathf760f5a2019-01-03 10:37:19 +00003173 return ArchSpec();
Kate Stoneb9c1b512016-09-06 20:57:50 +00003174
3175 if (m_section_headers.empty()) {
3176 // Allow elf notes to be parsed which may affect the detected architecture.
3177 ParseSectionHeaders();
3178 }
3179
3180 if (CalculateType() == eTypeCoreFile &&
3181 m_arch_spec.TripleOSIsUnspecifiedUnknown()) {
3182 // Core files don't have section headers yet they have PT_NOTE program
Adrian Prantl05097242018-04-30 16:49:04 +00003183 // headers that might shed more light on the architecture
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003184 for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
3185 if (H.p_type != PT_NOTE || H.p_offset == 0 || H.p_filesz == 0)
3186 continue;
3187 DataExtractor data;
3188 if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {
3189 UUID uuid;
3190 RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
Kate Stoneb9c1b512016-09-06 20:57:50 +00003191 }
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003192 }
Kate Stoneb9c1b512016-09-06 20:57:50 +00003193 }
Pavel Labathf760f5a2019-01-03 10:37:19 +00003194 return m_arch_spec;
Chris Lattner30fdc8d2010-06-08 16:52:24 +00003195}
3196
Kate Stoneb9c1b512016-09-06 20:57:50 +00003197ObjectFile::Type ObjectFileELF::CalculateType() {
3198 switch (m_header.e_type) {
3199 case llvm::ELF::ET_NONE:
3200 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003201 return eTypeUnknown;
Kate Stoneb9c1b512016-09-06 20:57:50 +00003202
3203 case llvm::ELF::ET_REL:
3204 // 1 - Relocatable file
3205 return eTypeObjectFile;
3206
3207 case llvm::ELF::ET_EXEC:
3208 // 2 - Executable file
3209 return eTypeExecutable;
3210
3211 case llvm::ELF::ET_DYN:
3212 // 3 - Shared object file
3213 return eTypeSharedLibrary;
3214
3215 case ET_CORE:
3216 // 4 - Core file
3217 return eTypeCoreFile;
3218
3219 default:
3220 break;
3221 }
3222 return eTypeUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003223}
3224
Kate Stoneb9c1b512016-09-06 20:57:50 +00003225ObjectFile::Strata ObjectFileELF::CalculateStrata() {
3226 switch (m_header.e_type) {
3227 case llvm::ELF::ET_NONE:
3228 // 0 - No file type
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003229 return eStrataUnknown;
Greg Clayton9e00b6a652011-07-09 00:41:34 +00003230
Kate Stoneb9c1b512016-09-06 20:57:50 +00003231 case llvm::ELF::ET_REL:
3232 // 1 - Relocatable file
3233 return eStrataUnknown;
3234
3235 case llvm::ELF::ET_EXEC:
3236 // 2 - Executable file
3237 // TODO: is there any way to detect that an executable is a kernel
Adrian Prantl05097242018-04-30 16:49:04 +00003238 // related executable by inspecting the program headers, section headers,
3239 // symbols, or any other flag bits???
Kate Stoneb9c1b512016-09-06 20:57:50 +00003240 return eStrataUser;
3241
3242 case llvm::ELF::ET_DYN:
3243 // 3 - Shared object file
3244 // TODO: is there any way to detect that an shared library is a kernel
Adrian Prantl05097242018-04-30 16:49:04 +00003245 // related executable by inspecting the program headers, section headers,
3246 // symbols, or any other flag bits???
Kate Stoneb9c1b512016-09-06 20:57:50 +00003247 return eStrataUnknown;
3248
3249 case ET_CORE:
3250 // 4 - Core file
3251 // TODO: is there any way to detect that an core file is a kernel
Adrian Prantl05097242018-04-30 16:49:04 +00003252 // related executable by inspecting the program headers, section headers,
3253 // symbols, or any other flag bits???
Kate Stoneb9c1b512016-09-06 20:57:50 +00003254 return eStrataUnknown;
3255
3256 default:
3257 break;
3258 }
3259 return eStrataUnknown;
3260}
Pavel Labathe2867bc2017-12-15 14:23:58 +00003261
3262size_t ObjectFileELF::ReadSectionData(Section *section,
3263 lldb::offset_t section_offset, void *dst,
3264 size_t dst_len) {
3265 // If some other objectfile owns this data, pass this to them.
3266 if (section->GetObjectFile() != this)
3267 return section->GetObjectFile()->ReadSectionData(section, section_offset,
3268 dst, dst_len);
3269
3270 if (!section->Test(SHF_COMPRESSED))
3271 return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
3272
3273 // For compressed sections we need to read to full data to be able to
3274 // decompress.
3275 DataExtractor data;
3276 ReadSectionData(section, data);
3277 return data.CopyData(section_offset, dst_len, dst);
3278}
3279
3280size_t ObjectFileELF::ReadSectionData(Section *section,
3281 DataExtractor &section_data) {
3282 // If some other objectfile owns this data, pass this to them.
3283 if (section->GetObjectFile() != this)
3284 return section->GetObjectFile()->ReadSectionData(section, section_data);
3285
Pavel Labathe2867bc2017-12-15 14:23:58 +00003286 size_t result = ObjectFile::ReadSectionData(section, section_data);
3287 if (result == 0 || !section->Test(SHF_COMPRESSED))
3288 return result;
3289
3290 auto Decompressor = llvm::object::Decompressor::create(
3291 section->GetName().GetStringRef(),
3292 {reinterpret_cast<const char *>(section_data.GetDataStart()),
Pavel Labath4c2eb8b2017-12-15 14:39:12 +00003293 size_t(section_data.GetByteSize())},
Pavel Labathe2867bc2017-12-15 14:23:58 +00003294 GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8);
3295 if (!Decompressor) {
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003296 GetModule()->ReportWarning(
3297 "Unable to initialize decompressor for section '%s': %s",
3298 section->GetName().GetCString(),
3299 llvm::toString(Decompressor.takeError()).c_str());
3300 section_data.Clear();
3301 return 0;
Pavel Labathe2867bc2017-12-15 14:23:58 +00003302 }
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003303
Pavel Labathe2867bc2017-12-15 14:23:58 +00003304 auto buffer_sp =
3305 std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003306 if (auto error = Decompressor->decompress(
Pavel Labathe2867bc2017-12-15 14:23:58 +00003307 {reinterpret_cast<char *>(buffer_sp->GetBytes()),
Pavel Labath4c2eb8b2017-12-15 14:39:12 +00003308 size_t(buffer_sp->GetByteSize())})) {
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003309 GetModule()->ReportWarning(
3310 "Decompression of section '%s' failed: %s",
3311 section->GetName().GetCString(),
3312 llvm::toString(std::move(error)).c_str());
3313 section_data.Clear();
3314 return 0;
Pavel Labathe2867bc2017-12-15 14:23:58 +00003315 }
Leonard Mosescu9ba51572018-08-07 18:00:30 +00003316
Pavel Labathe2867bc2017-12-15 14:23:58 +00003317 section_data.SetData(buffer_sp);
3318 return buffer_sp->GetByteSize();
3319}
Pavel Labath16064d32018-03-20 11:56:24 +00003320
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003321llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
3322 ParseProgramHeaders();
3323 return m_program_headers;
3324}
3325
3326DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) {
3327 return DataExtractor(m_data, H.p_offset, H.p_filesz);
3328}
3329
Pavel Labath16064d32018-03-20 11:56:24 +00003330bool ObjectFileELF::AnySegmentHasPhysicalAddress() {
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003331 for (const ELFProgramHeader &H : ProgramHeaders()) {
3332 if (H.p_paddr != 0)
Pavel Labath16064d32018-03-20 11:56:24 +00003333 return true;
3334 }
3335 return false;
3336}
3337
3338std::vector<ObjectFile::LoadableData>
3339ObjectFileELF::GetLoadableData(Target &target) {
Adrian Prantl05097242018-04-30 16:49:04 +00003340 // Create a list of loadable data from loadable segments, using physical
3341 // addresses if they aren't all null
Pavel Labath16064d32018-03-20 11:56:24 +00003342 std::vector<LoadableData> loadables;
Pavel Labath16064d32018-03-20 11:56:24 +00003343 bool should_use_paddr = AnySegmentHasPhysicalAddress();
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003344 for (const ELFProgramHeader &H : ProgramHeaders()) {
Pavel Labath16064d32018-03-20 11:56:24 +00003345 LoadableData loadable;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003346 if (H.p_type != llvm::ELF::PT_LOAD)
Pavel Labath16064d32018-03-20 11:56:24 +00003347 continue;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003348 loadable.Dest = should_use_paddr ? H.p_paddr : H.p_vaddr;
Pavel Labath16064d32018-03-20 11:56:24 +00003349 if (loadable.Dest == LLDB_INVALID_ADDRESS)
3350 continue;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003351 if (H.p_filesz == 0)
Pavel Labath16064d32018-03-20 11:56:24 +00003352 continue;
Pavel Labath5ea7ecd2018-12-12 14:20:28 +00003353 auto segment_data = GetSegmentData(H);
Pavel Labath16064d32018-03-20 11:56:24 +00003354 loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
3355 segment_data.GetByteSize());
3356 loadables.push_back(loadable);
3357 }
3358 return loadables;
3359}