Coverage Report

Created: 2022-01-22 13:19

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/ObjectFile/ELF/ObjectFileELF.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- ObjectFileELF.cpp -------------------------------------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
9
#include "ObjectFileELF.h"
10
11
#include <algorithm>
12
#include <cassert>
13
#include <unordered_map>
14
15
#include "lldb/Core/FileSpecList.h"
16
#include "lldb/Core/Module.h"
17
#include "lldb/Core/ModuleSpec.h"
18
#include "lldb/Core/PluginManager.h"
19
#include "lldb/Core/Progress.h"
20
#include "lldb/Core/Section.h"
21
#include "lldb/Host/FileSystem.h"
22
#include "lldb/Host/LZMA.h"
23
#include "lldb/Symbol/DWARFCallFrameInfo.h"
24
#include "lldb/Symbol/SymbolContext.h"
25
#include "lldb/Target/SectionLoadList.h"
26
#include "lldb/Target/Target.h"
27
#include "lldb/Utility/ArchSpec.h"
28
#include "lldb/Utility/DataBufferHeap.h"
29
#include "lldb/Utility/Log.h"
30
#include "lldb/Utility/RangeMap.h"
31
#include "lldb/Utility/Status.h"
32
#include "lldb/Utility/Stream.h"
33
#include "lldb/Utility/Timer.h"
34
#include "llvm/ADT/IntervalMap.h"
35
#include "llvm/ADT/PointerUnion.h"
36
#include "llvm/ADT/StringRef.h"
37
#include "llvm/BinaryFormat/ELF.h"
38
#include "llvm/Object/Decompressor.h"
39
#include "llvm/Support/ARMBuildAttributes.h"
40
#include "llvm/Support/CRC.h"
41
#include "llvm/Support/FormatVariadic.h"
42
#include "llvm/Support/MathExtras.h"
43
#include "llvm/Support/MemoryBuffer.h"
44
#include "llvm/Support/MipsABIFlags.h"
45
46
#define CASE_AND_STREAM(s, def, width)                                         \
47
67
  case def:                                                                    \
48
67
    s->Printf("%-*s", width, #def);                                            \
49
67
    break;
50
51
using namespace lldb;
52
using namespace lldb_private;
53
using namespace elf;
54
using namespace llvm::ELF;
55
56
LLDB_PLUGIN_DEFINE(ObjectFileELF)
57
58
// ELF note owner definitions
59
static const char *const LLDB_NT_OWNER_FREEBSD = "FreeBSD";
60
static const char *const LLDB_NT_OWNER_GNU = "GNU";
61
static const char *const LLDB_NT_OWNER_NETBSD = "NetBSD";
62
static const char *const LLDB_NT_OWNER_NETBSDCORE = "NetBSD-CORE";
63
static const char *const LLDB_NT_OWNER_OPENBSD = "OpenBSD";
64
static const char *const LLDB_NT_OWNER_ANDROID = "Android";
65
static const char *const LLDB_NT_OWNER_CORE = "CORE";
66
static const char *const LLDB_NT_OWNER_LINUX = "LINUX";
67
68
// ELF note type definitions
69
static const elf_word LLDB_NT_FREEBSD_ABI_TAG = 0x01;
70
static const elf_word LLDB_NT_FREEBSD_ABI_SIZE = 4;
71
72
static const elf_word LLDB_NT_GNU_ABI_TAG = 0x01;
73
static const elf_word LLDB_NT_GNU_ABI_SIZE = 16;
74
75
static const elf_word LLDB_NT_GNU_BUILD_ID_TAG = 0x03;
76
77
static const elf_word LLDB_NT_NETBSD_IDENT_TAG = 1;
78
static const elf_word LLDB_NT_NETBSD_IDENT_DESCSZ = 4;
79
static const elf_word LLDB_NT_NETBSD_IDENT_NAMESZ = 7;
80
static const elf_word LLDB_NT_NETBSD_PROCINFO = 1;
81
82
// GNU ABI note OS constants
83
static const elf_word LLDB_NT_GNU_ABI_OS_LINUX = 0x00;
84
static const elf_word LLDB_NT_GNU_ABI_OS_HURD = 0x01;
85
static const elf_word LLDB_NT_GNU_ABI_OS_SOLARIS = 0x02;
86
87
namespace {
88
89
//===----------------------------------------------------------------------===//
90
/// \class ELFRelocation
91
/// Generic wrapper for ELFRel and ELFRela.
92
///
93
/// This helper class allows us to parse both ELFRel and ELFRela relocation
94
/// entries in a generic manner.
95
class ELFRelocation {
96
public:
97
  /// Constructs an ELFRelocation entry with a personality as given by @p
98
  /// type.
99
  ///
100
  /// \param type Either DT_REL or DT_RELA.  Any other value is invalid.
101
  ELFRelocation(unsigned type);
102
103
  ~ELFRelocation();
104
105
  bool Parse(const lldb_private::DataExtractor &data, lldb::offset_t *offset);
106
107
  static unsigned RelocType32(const ELFRelocation &rel);
108
109
  static unsigned RelocType64(const ELFRelocation &rel);
110
111
  static unsigned RelocSymbol32(const ELFRelocation &rel);
112
113
  static unsigned RelocSymbol64(const ELFRelocation &rel);
114
115
  static unsigned RelocOffset32(const ELFRelocation &rel);
116
117
  static unsigned RelocOffset64(const ELFRelocation &rel);
118
119
  static unsigned RelocAddend32(const ELFRelocation &rel);
120
121
  static unsigned RelocAddend64(const ELFRelocation &rel);
122
123
private:
124
  typedef llvm::PointerUnion<ELFRel *, ELFRela *> RelocUnion;
125
126
  RelocUnion reloc;
127
};
128
} // end anonymous namespace
129
130
116
ELFRelocation::ELFRelocation(unsigned type) {
131
116
  if (type == DT_REL || type == SHT_REL)
132
0
    reloc = new ELFRel();
133
116
  else if (type == DT_RELA || 
type == SHT_RELA94
)
134
116
    reloc = new ELFRela();
135
0
  else {
136
0
    assert(false && "unexpected relocation type");
137
0
    reloc = static_cast<ELFRel *>(nullptr);
138
0
  }
139
116
}
140
141
116
ELFRelocation::~ELFRelocation() {
142
116
  if (reloc.is<ELFRel *>())
143
0
    delete reloc.get<ELFRel *>();
144
116
  else
145
116
    delete reloc.get<ELFRela *>();
146
116
}
147
148
bool ELFRelocation::Parse(const lldb_private::DataExtractor &data,
149
1.88k
                          lldb::offset_t *offset) {
150
1.88k
  if (reloc.is<ELFRel *>())
151
0
    return reloc.get<ELFRel *>()->Parse(data, offset);
152
1.88k
  else
153
1.88k
    return reloc.get<ELFRela *>()->Parse(data, offset);
154
1.88k
}
155
156
0
unsigned ELFRelocation::RelocType32(const ELFRelocation &rel) {
157
0
  if (rel.reloc.is<ELFRel *>())
158
0
    return ELFRel::RelocType32(*rel.reloc.get<ELFRel *>());
159
0
  else
160
0
    return ELFRela::RelocType32(*rel.reloc.get<ELFRela *>());
161
0
}
162
163
6.00k
unsigned ELFRelocation::RelocType64(const ELFRelocation &rel) {
164
6.00k
  if (rel.reloc.is<ELFRel *>())
165
0
    return ELFRel::RelocType64(*rel.reloc.get<ELFRel *>());
166
6.00k
  else
167
6.00k
    return ELFRela::RelocType64(*rel.reloc.get<ELFRela *>());
168
6.00k
}
169
170
0
unsigned ELFRelocation::RelocSymbol32(const ELFRelocation &rel) {
171
0
  if (rel.reloc.is<ELFRel *>())
172
0
    return ELFRel::RelocSymbol32(*rel.reloc.get<ELFRel *>());
173
0
  else
174
0
    return ELFRela::RelocSymbol32(*rel.reloc.get<ELFRela *>());
175
0
}
176
177
1.88k
unsigned ELFRelocation::RelocSymbol64(const ELFRelocation &rel) {
178
1.88k
  if (rel.reloc.is<ELFRel *>())
179
0
    return ELFRel::RelocSymbol64(*rel.reloc.get<ELFRel *>());
180
1.88k
  else
181
1.88k
    return ELFRela::RelocSymbol64(*rel.reloc.get<ELFRela *>());
182
1.88k
}
183
184
1.37k
unsigned ELFRelocation::RelocOffset32(const ELFRelocation &rel) {
185
1.37k
  if (rel.reloc.is<ELFRel *>())
186
0
    return rel.reloc.get<ELFRel *>()->r_offset;
187
1.37k
  else
188
1.37k
    return rel.reloc.get<ELFRela *>()->r_offset;
189
1.37k
}
190
191
411
unsigned ELFRelocation::RelocOffset64(const ELFRelocation &rel) {
192
411
  if (rel.reloc.is<ELFRel *>())
193
0
    return rel.reloc.get<ELFRel *>()->r_offset;
194
411
  else
195
411
    return rel.reloc.get<ELFRela *>()->r_offset;
196
411
}
197
198
1.37k
unsigned ELFRelocation::RelocAddend32(const ELFRelocation &rel) {
199
1.37k
  if (rel.reloc.is<ELFRel *>())
200
0
    return 0;
201
1.37k
  else
202
1.37k
    return rel.reloc.get<ELFRela *>()->r_addend;
203
1.37k
}
204
205
411
unsigned ELFRelocation::RelocAddend64(const ELFRelocation &rel) {
206
411
  if (rel.reloc.is<ELFRel *>())
207
0
    return 0;
208
411
  else
209
411
    return rel.reloc.get<ELFRela *>()->r_addend;
210
411
}
211
212
220
static user_id_t SegmentID(size_t PHdrIndex) {
213
220
  return ~user_id_t(PHdrIndex);
214
220
}
215
216
1.52k
bool ELFNote::Parse(const DataExtractor &data, lldb::offset_t *offset) {
217
  // Read all fields.
218
1.52k
  if (data.GetU32(offset, &n_namesz, 3) == nullptr)
219
299
    return false;
220
221
  // The name field is required to be nul-terminated, and n_namesz includes the
222
  // terminating nul in observed implementations (contrary to the ELF-64 spec).
223
  // A special case is needed for cores generated by some older Linux versions,
224
  // which write a note named "CORE" without a nul terminator and n_namesz = 4.
225
1.22k
  if (n_namesz == 4) {
226
205
    char buf[4];
227
205
    if (data.ExtractBytes(*offset, 4, data.GetByteOrder(), buf) != 4)
228
0
      return false;
229
205
    if (strncmp(buf, "CORE", 4) == 0) {
230
0
      n_name = "CORE";
231
0
      *offset += 4;
232
0
      return true;
233
0
    }
234
205
  }
235
236
1.22k
  const char *cstr = data.GetCStr(offset, llvm::alignTo(n_namesz, 4));
237
1.22k
  if (cstr == nullptr) {
238
0
    Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_SYMBOLS));
239
0
    LLDB_LOGF(log, "Failed to parse note name lacking nul terminator");
240
241
0
    return false;
242
0
  }
243
1.22k
  n_name = cstr;
244
1.22k
  return true;
245
1.22k
}
246
247
0
static uint32_t mipsVariantFromElfFlags (const elf::ELFHeader &header) {
248
0
  const uint32_t mips_arch = header.e_flags & llvm::ELF::EF_MIPS_ARCH;
249
0
  uint32_t endian = header.e_ident[EI_DATA];
250
0
  uint32_t arch_variant = ArchSpec::eMIPSSubType_unknown;
251
0
  uint32_t fileclass = header.e_ident[EI_CLASS];
252
253
  // If there aren't any elf flags available (e.g core elf file) then return
254
  // default
255
  // 32 or 64 bit arch (without any architecture revision) based on object file's class.
256
0
  if (header.e_type == ET_CORE) {
257
0
    switch (fileclass) {
258
0
    case llvm::ELF::ELFCLASS32:
259
0
      return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
260
0
                                     : ArchSpec::eMIPSSubType_mips32;
261
0
    case llvm::ELF::ELFCLASS64:
262
0
      return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
263
0
                                     : ArchSpec::eMIPSSubType_mips64;
264
0
    default:
265
0
      return arch_variant;
266
0
    }
267
0
  }
268
269
0
  switch (mips_arch) {
270
0
  case llvm::ELF::EF_MIPS_ARCH_1:
271
0
  case llvm::ELF::EF_MIPS_ARCH_2:
272
0
  case llvm::ELF::EF_MIPS_ARCH_32:
273
0
    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32el
274
0
                                   : ArchSpec::eMIPSSubType_mips32;
275
0
  case llvm::ELF::EF_MIPS_ARCH_32R2:
276
0
    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r2el
277
0
                                   : ArchSpec::eMIPSSubType_mips32r2;
278
0
  case llvm::ELF::EF_MIPS_ARCH_32R6:
279
0
    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips32r6el
280
0
                                   : ArchSpec::eMIPSSubType_mips32r6;
281
0
  case llvm::ELF::EF_MIPS_ARCH_3:
282
0
  case llvm::ELF::EF_MIPS_ARCH_4:
283
0
  case llvm::ELF::EF_MIPS_ARCH_5:
284
0
  case llvm::ELF::EF_MIPS_ARCH_64:
285
0
    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64el
286
0
                                   : ArchSpec::eMIPSSubType_mips64;
287
0
  case llvm::ELF::EF_MIPS_ARCH_64R2:
288
0
    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r2el
289
0
                                   : ArchSpec::eMIPSSubType_mips64r2;
290
0
  case llvm::ELF::EF_MIPS_ARCH_64R6:
291
0
    return (endian == ELFDATA2LSB) ? ArchSpec::eMIPSSubType_mips64r6el
292
0
                                   : ArchSpec::eMIPSSubType_mips64r6;
293
0
  default:
294
0
    break;
295
0
  }
296
297
0
  return arch_variant;
298
0
}
299
300
6
static uint32_t riscvVariantFromElfFlags(const elf::ELFHeader &header) {
301
6
  uint32_t fileclass = header.e_ident[EI_CLASS];
302
6
  switch (fileclass) {
303
3
  case llvm::ELF::ELFCLASS32:
304
3
    return ArchSpec::eRISCVSubType_riscv32;
305
3
  case llvm::ELF::ELFCLASS64:
306
3
    return ArchSpec::eRISCVSubType_riscv64;
307
0
  default:
308
0
    return ArchSpec::eRISCVSubType_unknown;
309
6
  }
310
6
}
311
312
1.22k
static uint32_t subTypeFromElfHeader(const elf::ELFHeader &header) {
313
1.22k
  if (header.e_machine == llvm::ELF::EM_MIPS)
314
0
    return mipsVariantFromElfFlags(header);
315
1.22k
  else if (header.e_machine == llvm::ELF::EM_RISCV)
316
6
    return riscvVariantFromElfFlags(header);
317
318
1.22k
  return LLDB_INVALID_CPUTYPE;
319
1.22k
}
320
321
char ObjectFileELF::ID;
322
323
// Arbitrary constant used as UUID prefix for core files.
324
const uint32_t ObjectFileELF::g_core_uuid_magic(0xE210C);
325
326
// Static methods.
327
3.46k
void ObjectFileELF::Initialize() {
328
3.46k
  PluginManager::RegisterPlugin(GetPluginNameStatic(),
329
3.46k
                                GetPluginDescriptionStatic(), CreateInstance,
330
3.46k
                                CreateMemoryInstance, GetModuleSpecifications);
331
3.46k
}
332
333
3.45k
void ObjectFileELF::Terminate() {
334
3.45k
  PluginManager::UnregisterPlugin(CreateInstance);
335
3.45k
}
336
337
ObjectFile *ObjectFileELF::CreateInstance(const lldb::ModuleSP &module_sp,
338
                                          DataBufferSP &data_sp,
339
                                          lldb::offset_t data_offset,
340
                                          const lldb_private::FileSpec *file,
341
                                          lldb::offset_t file_offset,
342
139k
                                          lldb::offset_t length) {
343
139k
  if (!data_sp) {
344
0
    data_sp = MapFileData(*file, length, file_offset);
345
0
    if (!data_sp)
346
0
      return nullptr;
347
0
    data_offset = 0;
348
0
  }
349
350
139k
  assert(data_sp);
351
352
139k
  if (data_sp->GetByteSize() <= (llvm::ELF::EI_NIDENT + data_offset))
353
0
    return nullptr;
354
355
139k
  const uint8_t *magic = data_sp->GetBytes() + data_offset;
356
139k
  if (!ELFHeader::MagicBytesMatch(magic))
357
139k
    return nullptr;
358
359
  // Update the data to contain the entire file if it doesn't already
360
310
  if (data_sp->GetByteSize() < length) {
361
256
    data_sp = MapFileData(*file, length, file_offset);
362
256
    if (!data_sp)
363
0
      return nullptr;
364
256
    data_offset = 0;
365
256
    magic = data_sp->GetBytes();
366
256
  }
367
368
310
  unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
369
310
  if (address_size == 4 || 
address_size == 8256
) {
370
310
    std::unique_ptr<ObjectFileELF> objfile_up(new ObjectFileELF(
371
310
        module_sp, data_sp, data_offset, file, file_offset, length));
372
310
    ArchSpec spec = objfile_up->GetArchitecture();
373
310
    if (spec && objfile_up->SetModulesArchitecture(spec))
374
310
      return objfile_up.release();
375
310
  }
376
377
0
  return nullptr;
378
310
}
379
380
ObjectFile *ObjectFileELF::CreateMemoryInstance(
381
    const lldb::ModuleSP &module_sp, DataBufferSP &data_sp,
382
18
    const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
383
18
  if (data_sp && data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT)) {
384
18
    const uint8_t *magic = data_sp->GetBytes();
385
18
    if (ELFHeader::MagicBytesMatch(magic)) {
386
14
      unsigned address_size = ELFHeader::AddressSizeInBytes(magic);
387
14
      if (address_size == 4 || 
address_size == 811
) {
388
14
        std::unique_ptr<ObjectFileELF> objfile_up(
389
14
            new ObjectFileELF(module_sp, data_sp, process_sp, header_addr));
390
14
        ArchSpec spec = objfile_up->GetArchitecture();
391
14
        if (spec && objfile_up->SetModulesArchitecture(spec))
392
14
          return objfile_up.release();
393
14
      }
394
14
    }
395
18
  }
396
4
  return nullptr;
397
18
}
398
399
bool ObjectFileELF::MagicBytesMatch(DataBufferSP &data_sp,
400
                                    lldb::addr_t data_offset,
401
146k
                                    lldb::addr_t data_length) {
402
146k
  if (data_sp &&
403
146k
      data_sp->GetByteSize() > (llvm::ELF::EI_NIDENT + data_offset)) {
404
146k
    const uint8_t *magic = data_sp->GetBytes() + data_offset;
405
146k
    return ELFHeader::MagicBytesMatch(magic);
406
146k
  }
407
0
  return false;
408
146k
}
409
410
561
static uint32_t calc_crc32(uint32_t init, const DataExtractor &data) {
411
561
  return llvm::crc32(
412
561
      init, llvm::makeArrayRef(data.GetDataStart(), data.GetByteSize()));
413
561
}
414
415
uint32_t ObjectFileELF::CalculateELFNotesSegmentsCRC32(
416
54
    const ProgramHeaderColl &program_headers, DataExtractor &object_data) {
417
418
54
  uint32_t core_notes_crc = 0;
419
420
1.32k
  for (const ELFProgramHeader &H : program_headers) {
421
1.32k
    if (H.p_type == llvm::ELF::PT_NOTE) {
422
54
      const elf_off ph_offset = H.p_offset;
423
54
      const size_t ph_size = H.p_filesz;
424
425
54
      DataExtractor segment_data;
426
54
      if (segment_data.SetData(object_data, ph_offset, ph_size) != ph_size) {
427
        // The ELF program header contained incorrect data, probably corefile
428
        // is incomplete or corrupted.
429
0
        break;
430
0
      }
431
432
54
      core_notes_crc = calc_crc32(core_notes_crc, segment_data);
433
54
    }
434
1.32k
  }
435
436
54
  return core_notes_crc;
437
54
}
438
439
0
static const char *OSABIAsCString(unsigned char osabi_byte) {
440
0
#define _MAKE_OSABI_CASE(x)                                                    \
441
0
  case x:                                                                      \
442
0
    return #x
443
0
  switch (osabi_byte) {
444
0
    _MAKE_OSABI_CASE(ELFOSABI_NONE);
445
0
    _MAKE_OSABI_CASE(ELFOSABI_HPUX);
446
0
    _MAKE_OSABI_CASE(ELFOSABI_NETBSD);
447
0
    _MAKE_OSABI_CASE(ELFOSABI_GNU);
448
0
    _MAKE_OSABI_CASE(ELFOSABI_HURD);
449
0
    _MAKE_OSABI_CASE(ELFOSABI_SOLARIS);
450
0
    _MAKE_OSABI_CASE(ELFOSABI_AIX);
451
0
    _MAKE_OSABI_CASE(ELFOSABI_IRIX);
452
0
    _MAKE_OSABI_CASE(ELFOSABI_FREEBSD);
453
0
    _MAKE_OSABI_CASE(ELFOSABI_TRU64);
454
0
    _MAKE_OSABI_CASE(ELFOSABI_MODESTO);
455
0
    _MAKE_OSABI_CASE(ELFOSABI_OPENBSD);
456
0
    _MAKE_OSABI_CASE(ELFOSABI_OPENVMS);
457
0
    _MAKE_OSABI_CASE(ELFOSABI_NSK);
458
0
    _MAKE_OSABI_CASE(ELFOSABI_AROS);
459
0
    _MAKE_OSABI_CASE(ELFOSABI_FENIXOS);
460
0
    _MAKE_OSABI_CASE(ELFOSABI_C6000_ELFABI);
461
0
    _MAKE_OSABI_CASE(ELFOSABI_C6000_LINUX);
462
0
    _MAKE_OSABI_CASE(ELFOSABI_ARM);
463
0
    _MAKE_OSABI_CASE(ELFOSABI_STANDALONE);
464
0
  default:
465
0
    return "<unknown-osabi>";
466
0
  }
467
0
#undef _MAKE_OSABI_CASE
468
0
}
469
470
//
471
// WARNING : This function is being deprecated
472
// It's functionality has moved to ArchSpec::SetArchitecture This function is
473
// only being kept to validate the move.
474
//
475
// TODO : Remove this function
476
static bool GetOsFromOSABI(unsigned char osabi_byte,
477
1.22k
                           llvm::Triple::OSType &ostype) {
478
1.22k
  switch (osabi_byte) {
479
0
  case ELFOSABI_AIX:
480
0
    ostype = llvm::Triple::OSType::AIX;
481
0
    break;
482
24
  case ELFOSABI_FREEBSD:
483
24
    ostype = llvm::Triple::OSType::FreeBSD;
484
24
    break;
485
2
  case ELFOSABI_GNU:
486
2
    ostype = llvm::Triple::OSType::Linux;
487
2
    break;
488
0
  case ELFOSABI_NETBSD:
489
0
    ostype = llvm::Triple::OSType::NetBSD;
490
0
    break;
491
0
  case ELFOSABI_OPENBSD:
492
0
    ostype = llvm::Triple::OSType::OpenBSD;
493
0
    break;
494
0
  case ELFOSABI_SOLARIS:
495
0
    ostype = llvm::Triple::OSType::Solaris;
496
0
    break;
497
1.20k
  default:
498
1.20k
    ostype = llvm::Triple::OSType::UnknownOS;
499
1.22k
  }
500
1.22k
  return ostype != llvm::Triple::OSType::UnknownOS;
501
1.22k
}
502
503
size_t ObjectFileELF::GetModuleSpecifications(
504
    const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
505
    lldb::offset_t data_offset, lldb::offset_t file_offset,
506
146k
    lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
507
146k
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
508
509
146k
  const size_t initial_count = specs.GetSize();
510
511
146k
  if (ObjectFileELF::MagicBytesMatch(data_sp, 0, data_sp->GetByteSize())) {
512
458
    DataExtractor data;
513
458
    data.SetData(data_sp);
514
458
    elf::ELFHeader header;
515
458
    lldb::offset_t header_offset = data_offset;
516
458
    if (header.Parse(data, &header_offset)) {
517
458
      if (data_sp) {
518
458
        ModuleSpec spec(file);
519
520
458
        const uint32_t sub_type = subTypeFromElfHeader(header);
521
458
        spec.GetArchitecture().SetArchitecture(
522
458
            eArchTypeELF, header.e_machine, sub_type, header.e_ident[EI_OSABI]);
523
524
458
        if (spec.GetArchitecture().IsValid()) {
525
458
          llvm::Triple::OSType ostype;
526
458
          llvm::Triple::VendorType vendor;
527
458
          llvm::Triple::OSType spec_ostype =
528
458
              spec.GetArchitecture().GetTriple().getOS();
529
530
458
          LLDB_LOGF(log, "ObjectFileELF::%s file '%s' module OSABI: %s",
531
458
                    __FUNCTION__, file.GetPath().c_str(),
532
458
                    OSABIAsCString(header.e_ident[EI_OSABI]));
533
534
          // SetArchitecture should have set the vendor to unknown
535
458
          vendor = spec.GetArchitecture().GetTriple().getVendor();
536
458
          assert(vendor == llvm::Triple::UnknownVendor);
537
458
          UNUSED_IF_ASSERT_DISABLED(vendor);
538
539
          //
540
          // Validate it is ok to remove GetOsFromOSABI
541
458
          GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
542
458
          assert(spec_ostype == ostype);
543
458
          if (spec_ostype != llvm::Triple::OSType::UnknownOS) {
544
14
            LLDB_LOGF(log,
545
14
                      "ObjectFileELF::%s file '%s' set ELF module OS type "
546
14
                      "from ELF header OSABI.",
547
14
                      __FUNCTION__, file.GetPath().c_str());
548
14
          }
549
550
458
          if (data_sp->GetByteSize() < length)
551
378
            data_sp = MapFileData(file, -1, file_offset);
552
458
          if (data_sp)
553
458
            data.SetData(data_sp);
554
          // In case there is header extension in the section #0, the header we
555
          // parsed above could have sentinel values for e_phnum, e_shnum, and
556
          // e_shstrndx.  In this case we need to reparse the header with a
557
          // bigger data source to get the actual values.
558
458
          if (header.HasHeaderExtension()) {
559
1
            lldb::offset_t header_offset = data_offset;
560
1
            header.Parse(data, &header_offset);
561
1
          }
562
563
458
          uint32_t gnu_debuglink_crc = 0;
564
458
          std::string gnu_debuglink_file;
565
458
          SectionHeaderColl section_headers;
566
458
          lldb_private::UUID &uuid = spec.GetUUID();
567
568
458
          GetSectionHeaderInfo(section_headers, data, header, uuid,
569
458
                               gnu_debuglink_file, gnu_debuglink_crc,
570
458
                               spec.GetArchitecture());
571
572
458
          llvm::Triple &spec_triple = spec.GetArchitecture().GetTriple();
573
574
458
          LLDB_LOGF(log,
575
458
                    "ObjectFileELF::%s file '%s' module set to triple: %s "
576
458
                    "(architecture %s)",
577
458
                    __FUNCTION__, file.GetPath().c_str(),
578
458
                    spec_triple.getTriple().c_str(),
579
458
                    spec.GetArchitecture().GetArchitectureName());
580
581
458
          if (!uuid.IsValid()) {
582
387
            uint32_t core_notes_crc = 0;
583
584
387
            if (!gnu_debuglink_crc) {
585
386
              LLDB_SCOPED_TIMERF(
586
386
                  "Calculating module crc32 %s with size %" PRIu64 " KiB",
587
386
                  file.GetLastPathComponent().AsCString(),
588
386
                  (length - file_offset) / 1024);
589
590
              // For core files - which usually don't happen to have a
591
              // gnu_debuglink, and are pretty bulky - calculating whole
592
              // contents crc32 would be too much of luxury.  Thus we will need
593
              // to fallback to something simpler.
594
386
              if (header.e_type == llvm::ELF::ET_CORE) {
595
53
                ProgramHeaderColl program_headers;
596
53
                GetProgramHeaderInfo(program_headers, data, header);
597
598
53
                core_notes_crc =
599
53
                    CalculateELFNotesSegmentsCRC32(program_headers, data);
600
333
              } else {
601
333
                gnu_debuglink_crc = calc_crc32(0, data);
602
333
              }
603
386
            }
604
387
            using u32le = llvm::support::ulittle32_t;
605
387
            if (gnu_debuglink_crc) {
606
              // Use 4 bytes of crc from the .gnu_debuglink section.
607
334
              u32le data(gnu_debuglink_crc);
608
334
              uuid = UUID::fromData(&data, sizeof(data));
609
334
            } else 
if (53
core_notes_crc53
) {
610
              // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make
611
              // it look different form .gnu_debuglink crc followed by 4 bytes
612
              // of note segments crc.
613
53
              u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
614
53
              uuid = UUID::fromData(data, sizeof(data));
615
53
            }
616
387
          }
617
618
458
          specs.Append(spec);
619
458
        }
620
458
      }
621
458
    }
622
458
  }
623
624
0
  return specs.GetSize() - initial_count;
625
146k
}
626
627
// ObjectFile protocol
628
629
ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
630
                             DataBufferSP &data_sp, lldb::offset_t data_offset,
631
                             const FileSpec *file, lldb::offset_t file_offset,
632
                             lldb::offset_t length)
633
311
    : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset) {
634
311
  if (file)
635
311
    m_file = *file;
636
311
}
637
638
ObjectFileELF::ObjectFileELF(const lldb::ModuleSP &module_sp,
639
                             DataBufferSP &header_data_sp,
640
                             const lldb::ProcessSP &process_sp,
641
                             addr_t header_addr)
642
14
    : ObjectFile(module_sp, process_sp, header_addr, header_data_sp) {}
643
644
584
bool ObjectFileELF::IsExecutable() const {
645
584
  return ((m_header.e_type & ET_EXEC) != 0) || 
(m_header.e_entry != 0)89
;
646
584
}
647
648
bool ObjectFileELF::SetLoadAddress(Target &target, lldb::addr_t value,
649
61
                                   bool value_is_offset) {
650
61
  ModuleSP module_sp = GetModule();
651
61
  if (module_sp) {
652
61
    size_t num_loaded_sections = 0;
653
61
    SectionList *section_list = GetSectionList();
654
61
    if (section_list) {
655
61
      if (!value_is_offset) {
656
33
        addr_t base = GetBaseAddress().GetFileAddress();
657
33
        if (base == LLDB_INVALID_ADDRESS)
658
7
          return false;
659
26
        value -= base;
660
26
      }
661
662
54
      const size_t num_sections = section_list->GetSize();
663
54
      size_t sect_idx = 0;
664
665
514
      for (sect_idx = 0; sect_idx < num_sections; 
++sect_idx460
) {
666
        // Iterate through the object file sections to find all of the sections
667
        // that have SHF_ALLOC in their flag bits.
668
460
        SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
669
460
        if (section_sp->Test(SHF_ALLOC) ||
670
460
            
section_sp->GetType() == eSectionTypeContainer451
) {
671
83
          lldb::addr_t load_addr = section_sp->GetFileAddress();
672
          // We don't want to update the load address of a section with type
673
          // eSectionTypeAbsoluteAddress as they already have the absolute load
674
          // address already specified
675
83
          if (section_sp->GetType() != eSectionTypeAbsoluteAddress)
676
83
            load_addr += value;
677
678
          // On 32-bit systems the load address have to fit into 4 bytes. The
679
          // rest of the bytes are the overflow from the addition.
680
83
          if (GetAddressByteSize() == 4)
681
6
            load_addr &= 0xFFFFFFFF;
682
683
83
          if (target.GetSectionLoadList().SetSectionLoadAddress(section_sp,
684
83
                                                                load_addr))
685
71
            ++num_loaded_sections;
686
83
        }
687
460
      }
688
54
      return num_loaded_sections > 0;
689
61
    }
690
61
  }
691
0
  return false;
692
61
}
693
694
558
ByteOrder ObjectFileELF::GetByteOrder() const {
695
558
  if (m_header.e_ident[EI_DATA] == ELFDATA2MSB)
696
0
    return eByteOrderBig;
697
558
  if (m_header.e_ident[EI_DATA] == ELFDATA2LSB)
698
558
    return eByteOrderLittle;
699
0
  return eByteOrderInvalid;
700
558
}
701
702
691
uint32_t ObjectFileELF::GetAddressByteSize() const {
703
691
  return m_data.GetAddressByteSize();
704
691
}
705
706
40
AddressClass ObjectFileELF::GetAddressClass(addr_t file_addr) {
707
40
  Symtab *symtab = GetSymtab();
708
40
  if (!symtab)
709
0
    return AddressClass::eUnknown;
710
711
  // The address class is determined based on the symtab. Ask it from the
712
  // object file what contains the symtab information.
713
40
  ObjectFile *symtab_objfile = symtab->GetObjectFile();
714
40
  if (symtab_objfile != nullptr && symtab_objfile != this)
715
0
    return symtab_objfile->GetAddressClass(file_addr);
716
717
40
  auto res = ObjectFile::GetAddressClass(file_addr);
718
40
  if (res != AddressClass::eCode)
719
0
    return res;
720
721
40
  auto ub = m_address_class_map.upper_bound(file_addr);
722
40
  if (ub == m_address_class_map.begin()) {
723
    // No entry in the address class map before the address. Return default
724
    // address class for an address in a code section.
725
28
    return AddressClass::eCode;
726
28
  }
727
728
  // Move iterator to the address class entry preceding address
729
12
  --ub;
730
731
12
  return ub->second;
732
40
}
733
734
68.0k
size_t ObjectFileELF::SectionIndex(const SectionHeaderCollIter &I) {
735
68.0k
  return std::distance(m_section_headers.begin(), I);
736
68.0k
}
737
738
0
size_t ObjectFileELF::SectionIndex(const SectionHeaderCollConstIter &I) const {
739
0
  return std::distance(m_section_headers.begin(), I);
740
0
}
741
742
1.43k
bool ObjectFileELF::ParseHeader() {
743
1.43k
  lldb::offset_t offset = 0;
744
1.43k
  return m_header.Parse(m_data, &offset);
745
1.43k
}
746
747
318
UUID ObjectFileELF::GetUUID() {
748
  // Need to parse the section list to get the UUIDs, so make sure that's been
749
  // done.
750
318
  if (!ParseSectionHeaders() && 
GetType() != ObjectFile::eTypeCoreFile2
)
751
0
    return UUID();
752
753
318
  if (!m_uuid) {
754
176
    using u32le = llvm::support::ulittle32_t;
755
176
    if (GetType() == ObjectFile::eTypeCoreFile) {
756
1
      uint32_t core_notes_crc = 0;
757
758
1
      if (!ParseProgramHeaders())
759
0
        return UUID();
760
761
1
      core_notes_crc =
762
1
          CalculateELFNotesSegmentsCRC32(m_program_headers, m_data);
763
764
1
      if (core_notes_crc) {
765
        // Use 8 bytes - first 4 bytes for *magic* prefix, mainly to make it
766
        // look different form .gnu_debuglink crc - followed by 4 bytes of note
767
        // segments crc.
768
1
        u32le data[] = {u32le(g_core_uuid_magic), u32le(core_notes_crc)};
769
1
        m_uuid = UUID::fromData(data, sizeof(data));
770
1
      }
771
175
    } else {
772
175
      if (!m_gnu_debuglink_crc)
773
174
        m_gnu_debuglink_crc = calc_crc32(0, m_data);
774
175
      if (m_gnu_debuglink_crc) {
775
        // Use 4 bytes of crc from the .gnu_debuglink section.
776
175
        u32le data(m_gnu_debuglink_crc);
777
175
        m_uuid = UUID::fromData(&data, sizeof(data));
778
175
      }
779
175
    }
780
176
  }
781
782
318
  return m_uuid;
783
318
}
784
785
102
llvm::Optional<FileSpec> ObjectFileELF::GetDebugLink() {
786
102
  if (m_gnu_debuglink_file.empty())
787
100
    return llvm::None;
788
2
  return FileSpec(m_gnu_debuglink_file);
789
102
}
790
791
83
uint32_t ObjectFileELF::GetDependentModules(FileSpecList &files) {
792
83
  size_t num_modules = ParseDependentModules();
793
83
  uint32_t num_specs = 0;
794
795
130
  for (unsigned i = 0; i < num_modules; 
++i47
) {
796
47
    if (files.AppendIfUnique(m_filespec_up->GetFileSpecAtIndex(i)))
797
47
      num_specs++;
798
47
  }
799
800
83
  return num_specs;
801
83
}
802
803
46
Address ObjectFileELF::GetImageInfoAddress(Target *target) {
804
46
  if (!ParseDynamicSymbols())
805
34
    return Address();
806
807
12
  SectionList *section_list = GetSectionList();
808
12
  if (!section_list)
809
0
    return Address();
810
811
  // Find the SHT_DYNAMIC (.dynamic) section.
812
12
  SectionSP dynsym_section_sp(
813
12
      section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true));
814
12
  if (!dynsym_section_sp)
815
0
    return Address();
816
12
  assert(dynsym_section_sp->GetObjectFile() == this);
817
818
0
  user_id_t dynsym_id = dynsym_section_sp->GetID();
819
12
  const ELFSectionHeaderInfo *dynsym_hdr = GetSectionHeaderByIndex(dynsym_id);
820
12
  if (!dynsym_hdr)
821
0
    return Address();
822
823
66
  
for (size_t i = 0; 12
i < m_dynamic_symbols.size();
++i54
) {
824
66
    ELFDynamic &symbol = m_dynamic_symbols[i];
825
826
66
    if (symbol.d_tag == DT_DEBUG) {
827
      // Compute the offset as the number of previous entries plus the size of
828
      // d_tag.
829
12
      addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
830
12
      return Address(dynsym_section_sp, offset);
831
12
    }
832
    // MIPS executables uses DT_MIPS_RLD_MAP_REL to support PIE. DT_MIPS_RLD_MAP
833
    // exists in non-PIE.
834
54
    else if ((symbol.d_tag == DT_MIPS_RLD_MAP ||
835
54
              symbol.d_tag == DT_MIPS_RLD_MAP_REL) &&
836
54
             
target0
) {
837
0
      addr_t offset = i * dynsym_hdr->sh_entsize + GetAddressByteSize();
838
0
      addr_t dyn_base = dynsym_section_sp->GetLoadBaseAddress(target);
839
0
      if (dyn_base == LLDB_INVALID_ADDRESS)
840
0
        return Address();
841
842
0
      Status error;
843
0
      if (symbol.d_tag == DT_MIPS_RLD_MAP) {
844
        // DT_MIPS_RLD_MAP tag stores an absolute address of the debug pointer.
845
0
        Address addr;
846
0
        if (target->ReadPointerFromMemory(dyn_base + offset, error, addr, true))
847
0
          return addr;
848
0
      }
849
0
      if (symbol.d_tag == DT_MIPS_RLD_MAP_REL) {
850
        // DT_MIPS_RLD_MAP_REL tag stores the offset to the debug pointer,
851
        // relative to the address of the tag.
852
0
        uint64_t rel_offset;
853
0
        rel_offset = target->ReadUnsignedIntegerFromMemory(
854
0
            dyn_base + offset, GetAddressByteSize(), UINT64_MAX, error, true);
855
0
        if (error.Success() && rel_offset != UINT64_MAX) {
856
0
          Address addr;
857
0
          addr_t debug_ptr_address =
858
0
              dyn_base + (offset - GetAddressByteSize()) + rel_offset;
859
0
          addr.SetOffset(debug_ptr_address);
860
0
          return addr;
861
0
        }
862
0
      }
863
0
    }
864
66
  }
865
866
0
  return Address();
867
12
}
868
869
151
lldb_private::Address ObjectFileELF::GetEntryPointAddress() {
870
151
  if (m_entry_point_address.IsValid())
871
25
    return m_entry_point_address;
872
873
126
  if (!ParseHeader() || !IsExecutable())
874
0
    return m_entry_point_address;
875
876
126
  SectionList *section_list = GetSectionList();
877
126
  addr_t offset = m_header.e_entry;
878
879
126
  if (!section_list)
880
0
    m_entry_point_address.SetOffset(offset);
881
126
  else
882
126
    m_entry_point_address.ResolveAddressUsingFileSections(offset, section_list);
883
126
  return m_entry_point_address;
884
126
}
885
886
89
Address ObjectFileELF::GetBaseAddress() {
887
91
  for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
888
91
    const ELFProgramHeader &H = EnumPHdr.value();
889
91
    if (H.p_type != PT_LOAD)
890
24
      continue;
891
892
67
    return Address(
893
67
        GetSectionList()->FindSectionByID(SegmentID(EnumPHdr.index())), 0);
894
91
  }
895
22
  return LLDB_INVALID_ADDRESS;
896
89
}
897
898
// ParseDependentModules
899
89
size_t ObjectFileELF::ParseDependentModules() {
900
89
  if (m_filespec_up)
901
0
    return m_filespec_up->GetSize();
902
903
89
  m_filespec_up = std::make_unique<FileSpecList>();
904
905
89
  if (!ParseSectionHeaders())
906
0
    return 0;
907
908
89
  SectionList *section_list = GetSectionList();
909
89
  if (!section_list)
910
0
    return 0;
911
912
  // Find the SHT_DYNAMIC section.
913
89
  Section *dynsym =
914
89
      section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
915
89
          .get();
916
89
  if (!dynsym)
917
71
    return 0;
918
18
  assert(dynsym->GetObjectFile() == this);
919
920
0
  const ELFSectionHeaderInfo *header = GetSectionHeaderByIndex(dynsym->GetID());
921
18
  if (!header)
922
0
    return 0;
923
  // sh_link: section header index of string table used by entries in the
924
  // section.
925
18
  Section *dynstr = section_list->FindSectionByID(header->sh_link).get();
926
18
  if (!dynstr)
927
0
    return 0;
928
929
18
  DataExtractor dynsym_data;
930
18
  DataExtractor dynstr_data;
931
18
  if (ReadSectionData(dynsym, dynsym_data) &&
932
18
      ReadSectionData(dynstr, dynstr_data)) {
933
18
    ELFDynamic symbol;
934
18
    const lldb::offset_t section_size = dynsym_data.GetByteSize();
935
18
    lldb::offset_t offset = 0;
936
937
    // The only type of entries we are concerned with are tagged DT_NEEDED,
938
    // yielding the name of a required library.
939
404
    while (offset < section_size) {
940
386
      if (!symbol.Parse(dynsym_data, &offset))
941
0
        break;
942
943
386
      if (symbol.d_tag != DT_NEEDED)
944
339
        continue;
945
946
47
      uint32_t str_index = static_cast<uint32_t>(symbol.d_val);
947
47
      const char *lib_name = dynstr_data.PeekCStr(str_index);
948
47
      FileSpec file_spec(lib_name);
949
47
      FileSystem::Instance().Resolve(file_spec);
950
47
      m_filespec_up->Append(file_spec);
951
47
    }
952
18
  }
953
954
18
  return m_filespec_up->GetSize();
955
18
}
956
957
// GetProgramHeaderInfo
958
size_t ObjectFileELF::GetProgramHeaderInfo(ProgramHeaderColl &program_headers,
959
                                           DataExtractor &object_data,
960
494
                                           const ELFHeader &header) {
961
  // We have already parsed the program headers
962
494
  if (!program_headers.empty())
963
115
    return program_headers.size();
964
965
  // If there are no program headers to read we are done.
966
379
  if (header.e_phnum == 0)
967
181
    return 0;
968
969
198
  program_headers.resize(header.e_phnum);
970
198
  if (program_headers.size() != header.e_phnum)
971
0
    return 0;
972
973
198
  const size_t ph_size = header.e_phnum * header.e_phentsize;
974
198
  const elf_off ph_offset = header.e_phoff;
975
198
  DataExtractor data;
976
198
  if (data.SetData(object_data, ph_offset, ph_size) != ph_size)
977
0
    return 0;
978
979
198
  uint32_t idx;
980
198
  lldb::offset_t offset;
981
3.21k
  for (idx = 0, offset = 0; idx < header.e_phnum; 
++idx3.01k
) {
982
3.01k
    if (!program_headers[idx].Parse(data, &offset))
983
0
      break;
984
3.01k
  }
985
986
198
  if (idx < program_headers.size())
987
0
    program_headers.resize(idx);
988
989
198
  return program_headers.size();
990
198
}
991
992
// ParseProgramHeaders
993
441
bool ObjectFileELF::ParseProgramHeaders() {
994
441
  return GetProgramHeaderInfo(m_program_headers, m_data, m_header) != 0;
995
441
}
996
997
lldb_private::Status
998
ObjectFileELF::RefineModuleDetailsFromNote(lldb_private::DataExtractor &data,
999
                                           lldb_private::ArchSpec &arch_spec,
1000
299
                                           lldb_private::UUID &uuid) {
1001
299
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1002
299
  Status error;
1003
1004
299
  lldb::offset_t offset = 0;
1005
1006
976
  while (true) {
1007
    // Parse the note header.  If this fails, bail out.
1008
976
    const lldb::offset_t note_offset = offset;
1009
976
    ELFNote note = ELFNote();
1010
976
    if (!note.Parse(data, &offset)) {
1011
      // We're done.
1012
299
      return error;
1013
299
    }
1014
1015
677
    LLDB_LOGF(log, "ObjectFileELF::%s parsing note name='%s', type=%" PRIu32,
1016
677
              __FUNCTION__, note.n_name.c_str(), note.n_type);
1017
1018
    // Process FreeBSD ELF notes.
1019
677
    if ((note.n_name == LLDB_NT_OWNER_FREEBSD) &&
1020
677
        
(note.n_type == LLDB_NT_FREEBSD_ABI_TAG)12
&&
1021
677
        
(note.n_descsz == LLDB_NT_FREEBSD_ABI_SIZE)6
) {
1022
      // Pull out the min version info.
1023
6
      uint32_t version_info;
1024
6
      if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1025
0
        error.SetErrorString("failed to read FreeBSD ABI note payload");
1026
0
        return error;
1027
0
      }
1028
1029
      // Convert the version info into a major/minor number.
1030
6
      const uint32_t version_major = version_info / 100000;
1031
6
      const uint32_t version_minor = (version_info / 1000) % 100;
1032
1033
6
      char os_name[32];
1034
6
      snprintf(os_name, sizeof(os_name), "freebsd%" PRIu32 ".%" PRIu32,
1035
6
               version_major, version_minor);
1036
1037
      // Set the elf OS version to FreeBSD.  Also clear the vendor.
1038
6
      arch_spec.GetTriple().setOSName(os_name);
1039
6
      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1040
1041
6
      LLDB_LOGF(log,
1042
6
                "ObjectFileELF::%s detected FreeBSD %" PRIu32 ".%" PRIu32
1043
6
                ".%" PRIu32,
1044
6
                __FUNCTION__, version_major, version_minor,
1045
6
                static_cast<uint32_t>(version_info % 1000));
1046
6
    }
1047
    // Process GNU ELF notes.
1048
671
    else if (note.n_name == LLDB_NT_OWNER_GNU) {
1049
160
      switch (note.n_type) {
1050
12
      case LLDB_NT_GNU_ABI_TAG:
1051
12
        if (note.n_descsz == LLDB_NT_GNU_ABI_SIZE) {
1052
          // Pull out the min OS version supporting the ABI.
1053
12
          uint32_t version_info[4];
1054
12
          if (data.GetU32(&offset, &version_info[0], note.n_descsz / 4) ==
1055
12
              nullptr) {
1056
0
            error.SetErrorString("failed to read GNU ABI note payload");
1057
0
            return error;
1058
0
          }
1059
1060
          // Set the OS per the OS field.
1061
12
          switch (version_info[0]) {
1062
12
          case LLDB_NT_GNU_ABI_OS_LINUX:
1063
12
            arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1064
12
            arch_spec.GetTriple().setVendor(
1065
12
                llvm::Triple::VendorType::UnknownVendor);
1066
12
            LLDB_LOGF(log,
1067
12
                      "ObjectFileELF::%s detected Linux, min version %" PRIu32
1068
12
                      ".%" PRIu32 ".%" PRIu32,
1069
12
                      __FUNCTION__, version_info[1], version_info[2],
1070
12
                      version_info[3]);
1071
            // FIXME we have the minimal version number, we could be propagating
1072
            // that.  version_info[1] = OS Major, version_info[2] = OS Minor,
1073
            // version_info[3] = Revision.
1074
12
            break;
1075
0
          case LLDB_NT_GNU_ABI_OS_HURD:
1076
0
            arch_spec.GetTriple().setOS(llvm::Triple::OSType::UnknownOS);
1077
0
            arch_spec.GetTriple().setVendor(
1078
0
                llvm::Triple::VendorType::UnknownVendor);
1079
0
            LLDB_LOGF(log,
1080
0
                      "ObjectFileELF::%s detected Hurd (unsupported), min "
1081
0
                      "version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1082
0
                      __FUNCTION__, version_info[1], version_info[2],
1083
0
                      version_info[3]);
1084
0
            break;
1085
0
          case LLDB_NT_GNU_ABI_OS_SOLARIS:
1086
0
            arch_spec.GetTriple().setOS(llvm::Triple::OSType::Solaris);
1087
0
            arch_spec.GetTriple().setVendor(
1088
0
                llvm::Triple::VendorType::UnknownVendor);
1089
0
            LLDB_LOGF(log,
1090
0
                      "ObjectFileELF::%s detected Solaris, min version %" PRIu32
1091
0
                      ".%" PRIu32 ".%" PRIu32,
1092
0
                      __FUNCTION__, version_info[1], version_info[2],
1093
0
                      version_info[3]);
1094
0
            break;
1095
0
          default:
1096
0
            LLDB_LOGF(log,
1097
0
                      "ObjectFileELF::%s unrecognized OS in note, id %" PRIu32
1098
0
                      ", min version %" PRIu32 ".%" PRIu32 ".%" PRIu32,
1099
0
                      __FUNCTION__, version_info[0], version_info[1],
1100
0
                      version_info[2], version_info[3]);
1101
0
            break;
1102
12
          }
1103
12
        }
1104
12
        break;
1105
1106
129
      case LLDB_NT_GNU_BUILD_ID_TAG:
1107
        // Only bother processing this if we don't already have the uuid set.
1108
129
        if (!uuid.IsValid()) {
1109
          // 16 bytes is UUID|MD5, 20 bytes is SHA1. Other linkers may produce a
1110
          // build-id of a different length. Accept it as long as it's at least
1111
          // 4 bytes as it will be better than our own crc32.
1112
129
          if (note.n_descsz >= 4) {
1113
129
            if (const uint8_t *buf = data.PeekData(offset, note.n_descsz)) {
1114
              // Save the build id as the UUID for the module.
1115
129
              uuid = UUID::fromData(buf, note.n_descsz);
1116
129
            } else {
1117
0
              error.SetErrorString("failed to read GNU_BUILD_ID note payload");
1118
0
              return error;
1119
0
            }
1120
129
          }
1121
129
        }
1122
129
        break;
1123
160
      }
1124
160
      if (arch_spec.IsMIPS() &&
1125
160
          
arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS0
)
1126
        // The note.n_name == LLDB_NT_OWNER_GNU is valid for Linux platform
1127
0
        arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1128
160
    }
1129
    // Process NetBSD ELF executables and shared libraries
1130
511
    else if ((note.n_name == LLDB_NT_OWNER_NETBSD) &&
1131
511
             
(note.n_type == LLDB_NT_NETBSD_IDENT_TAG)47
&&
1132
511
             
(note.n_descsz == LLDB_NT_NETBSD_IDENT_DESCSZ)47
&&
1133
511
             
(note.n_namesz == LLDB_NT_NETBSD_IDENT_NAMESZ)47
) {
1134
      // Pull out the version info.
1135
47
      uint32_t version_info;
1136
47
      if (data.GetU32(&offset, &version_info, 1) == nullptr) {
1137
0
        error.SetErrorString("failed to read NetBSD ABI note payload");
1138
0
        return error;
1139
0
      }
1140
      // Convert the version info into a major/minor/patch number.
1141
      //     #define __NetBSD_Version__ MMmmrrpp00
1142
      //
1143
      //     M = major version
1144
      //     m = minor version; a minor number of 99 indicates current.
1145
      //     r = 0 (since NetBSD 3.0 not used)
1146
      //     p = patchlevel
1147
47
      const uint32_t version_major = version_info / 100000000;
1148
47
      const uint32_t version_minor = (version_info % 100000000) / 1000000;
1149
47
      const uint32_t version_patch = (version_info % 10000) / 100;
1150
      // Set the elf OS version to NetBSD.  Also clear the vendor.
1151
47
      arch_spec.GetTriple().setOSName(
1152
47
          llvm::formatv("netbsd{0}.{1}.{2}", version_major, version_minor,
1153
47
                        version_patch).str());
1154
47
      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1155
47
    }
1156
    // Process NetBSD ELF core(5) notes
1157
464
    else if ((note.n_name == LLDB_NT_OWNER_NETBSDCORE) &&
1158
464
             
(note.n_type == LLDB_NT_NETBSD_PROCINFO)28
) {
1159
      // Set the elf OS version to NetBSD.  Also clear the vendor.
1160
14
      arch_spec.GetTriple().setOS(llvm::Triple::OSType::NetBSD);
1161
14
      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1162
14
    }
1163
    // Process OpenBSD ELF notes.
1164
450
    else if (note.n_name == LLDB_NT_OWNER_OPENBSD) {
1165
      // Set the elf OS version to OpenBSD.  Also clear the vendor.
1166
0
      arch_spec.GetTriple().setOS(llvm::Triple::OSType::OpenBSD);
1167
0
      arch_spec.GetTriple().setVendor(llvm::Triple::VendorType::UnknownVendor);
1168
450
    } else if (note.n_name == LLDB_NT_OWNER_ANDROID) {
1169
0
      arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1170
0
      arch_spec.GetTriple().setEnvironment(
1171
0
          llvm::Triple::EnvironmentType::Android);
1172
450
    } else if (note.n_name == LLDB_NT_OWNER_LINUX) {
1173
      // This is sometimes found in core files and usually contains extended
1174
      // register info
1175
100
      arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1176
350
    } else if (note.n_name == LLDB_NT_OWNER_CORE) {
1177
      // Parse the NT_FILE to look for stuff in paths to shared libraries As
1178
      // the contents look like this in a 64 bit ELF core file: count     =
1179
      // 0x000000000000000a (10) page_size = 0x0000000000001000 (4096) Index
1180
      // start              end                file_ofs           path =====
1181
      // 0x0000000000401000 0x0000000000000000 /tmp/a.out [  1]
1182
      // 0x0000000000600000 0x0000000000601000 0x0000000000000000 /tmp/a.out [
1183
      // 2] 0x0000000000601000 0x0000000000602000 0x0000000000000001 /tmp/a.out
1184
      // [  3] 0x00007fa79c9ed000 0x00007fa79cba8000 0x0000000000000000
1185
      // /lib/x86_64-linux-gnu/libc-2.19.so [  4] 0x00007fa79cba8000
1186
      // 0x00007fa79cda7000 0x00000000000001bb /lib/x86_64-linux-
1187
      // gnu/libc-2.19.so [  5] 0x00007fa79cda7000 0x00007fa79cdab000
1188
      // 0x00000000000001ba /lib/x86_64-linux-gnu/libc-2.19.so [  6]
1189
      // 0x00007fa79cdab000 0x00007fa79cdad000 0x00000000000001be /lib/x86_64
1190
      // -linux-gnu/libc-2.19.so [  7] 0x00007fa79cdb2000 0x00007fa79cdd5000
1191
      // 0x0000000000000000 /lib/x86_64-linux-gnu/ld-2.19.so [  8]
1192
      // 0x00007fa79cfd4000 0x00007fa79cfd5000 0x0000000000000022 /lib/x86_64
1193
      // -linux-gnu/ld-2.19.so [  9] 0x00007fa79cfd5000 0x00007fa79cfd6000
1194
      // 0x0000000000000023 /lib/x86_64-linux-gnu/ld-2.19.so In the 32 bit ELFs
1195
      // the count, page_size, start, end, file_ofs are uint32_t For reference:
1196
      // see readelf source code (in binutils).
1197
220
      if (note.n_type == NT_FILE) {
1198
27
        uint64_t count = data.GetAddress(&offset);
1199
27
        const char *cstr;
1200
27
        data.GetAddress(&offset); // Skip page size
1201
27
        offset += count * 3 *
1202
27
                  data.GetAddressByteSize(); // Skip all start/end/file_ofs
1203
356
        for (size_t i = 0; i < count; 
++i329
) {
1204
330
          cstr = data.GetCStr(&offset);
1205
330
          if (cstr == nullptr) {
1206
0
            error.SetErrorStringWithFormat("ObjectFileELF::%s trying to read "
1207
0
                                           "at an offset after the end "
1208
0
                                           "(GetCStr returned nullptr)",
1209
0
                                           __FUNCTION__);
1210
0
            return error;
1211
0
          }
1212
330
          llvm::StringRef path(cstr);
1213
330
          if (path.contains("/lib/x86_64-linux-gnu") || 
path.contains("/lib/i386-linux-gnu")329
) {
1214
1
            arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1215
1
            break;
1216
1
          }
1217
330
        }
1218
27
        if (arch_spec.IsMIPS() &&
1219
27
            
arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS0
)
1220
          // In case of MIPSR6, the LLDB_NT_OWNER_GNU note is missing for some
1221
          // cases (e.g. compile with -nostdlib) Hence set OS to Linux
1222
0
          arch_spec.GetTriple().setOS(llvm::Triple::OSType::Linux);
1223
27
      }
1224
220
    }
1225
1226
    // Calculate the offset of the next note just in case "offset" has been
1227
    // used to poke at the contents of the note data
1228
677
    offset = note_offset + note.GetByteSize();
1229
677
  }
1230
1231
0
  return error;
1232
299
}
1233
1234
void ObjectFileELF::ParseARMAttributes(DataExtractor &data, uint64_t length,
1235
4
                                       ArchSpec &arch_spec) {
1236
4
  lldb::offset_t Offset = 0;
1237
1238
4
  uint8_t FormatVersion = data.GetU8(&Offset);
1239
4
  if (FormatVersion != llvm::ELFAttrs::Format_Version)
1240
0
    return;
1241
1242
4
  Offset = Offset + sizeof(uint32_t); // Section Length
1243
4
  llvm::StringRef VendorName = data.GetCStr(&Offset);
1244
1245
4
  if (VendorName != "aeabi")
1246
0
    return;
1247
1248
4
  if (arch_spec.GetTriple().getEnvironment() ==
1249
4
      llvm::Triple::UnknownEnvironment)
1250
4
    arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1251
1252
8
  while (Offset < length) {
1253
4
    uint8_t Tag = data.GetU8(&Offset);
1254
4
    uint32_t Size = data.GetU32(&Offset);
1255
1256
4
    if (Tag != llvm::ARMBuildAttrs::File || Size == 0)
1257
0
      continue;
1258
1259
12
    
while (4
Offset < length) {
1260
8
      uint64_t Tag = data.GetULEB128(&Offset);
1261
8
      switch (Tag) {
1262
8
      default:
1263
8
        if (Tag < 32)
1264
8
          data.GetULEB128(&Offset);
1265
0
        else if (Tag % 2 == 0)
1266
0
          data.GetULEB128(&Offset);
1267
0
        else
1268
0
          data.GetCStr(&Offset);
1269
1270
8
        break;
1271
1272
0
      case llvm::ARMBuildAttrs::CPU_raw_name:
1273
0
      case llvm::ARMBuildAttrs::CPU_name:
1274
0
        data.GetCStr(&Offset);
1275
1276
0
        break;
1277
1278
0
      case llvm::ARMBuildAttrs::ABI_VFP_args: {
1279
0
        uint64_t VFPArgs = data.GetULEB128(&Offset);
1280
1281
0
        if (VFPArgs == llvm::ARMBuildAttrs::BaseAAPCS) {
1282
0
          if (arch_spec.GetTriple().getEnvironment() ==
1283
0
                  llvm::Triple::UnknownEnvironment ||
1284
0
              arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABIHF)
1285
0
            arch_spec.GetTriple().setEnvironment(llvm::Triple::EABI);
1286
1287
0
          arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1288
0
        } else if (VFPArgs == llvm::ARMBuildAttrs::HardFPAAPCS) {
1289
0
          if (arch_spec.GetTriple().getEnvironment() ==
1290
0
                  llvm::Triple::UnknownEnvironment ||
1291
0
              arch_spec.GetTriple().getEnvironment() == llvm::Triple::EABI)
1292
0
            arch_spec.GetTriple().setEnvironment(llvm::Triple::EABIHF);
1293
1294
0
          arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1295
0
        }
1296
1297
0
        break;
1298
0
      }
1299
8
      }
1300
8
    }
1301
4
  }
1302
4
}
1303
1304
// GetSectionHeaderInfo
1305
size_t ObjectFileELF::GetSectionHeaderInfo(SectionHeaderColl &section_headers,
1306
                                           DataExtractor &object_data,
1307
                                           const elf::ELFHeader &header,
1308
                                           lldb_private::UUID &uuid,
1309
                                           std::string &gnu_debuglink_file,
1310
                                           uint32_t &gnu_debuglink_crc,
1311
2.25k
                                           ArchSpec &arch_spec) {
1312
  // Don't reparse the section headers if we already did that.
1313
2.25k
  if (!section_headers.empty())
1314
1.11k
    return section_headers.size();
1315
1316
  // Only initialize the arch_spec to okay defaults if they're not already set.
1317
  // We'll refine this with note data as we parse the notes.
1318
1.14k
  if (arch_spec.GetTriple().getOS() == llvm::Triple::OSType::UnknownOS) {
1319
769
    llvm::Triple::OSType ostype;
1320
769
    llvm::Triple::OSType spec_ostype;
1321
769
    const uint32_t sub_type = subTypeFromElfHeader(header);
1322
769
    arch_spec.SetArchitecture(eArchTypeELF, header.e_machine, sub_type,
1323
769
                              header.e_ident[EI_OSABI]);
1324
1325
    // Validate if it is ok to remove GetOsFromOSABI. Note, that now the OS is
1326
    // determined based on EI_OSABI flag and the info extracted from ELF notes
1327
    // (see RefineModuleDetailsFromNote). However in some cases that still
1328
    // might be not enough: for example a shared library might not have any
1329
    // notes at all and have EI_OSABI flag set to System V, as result the OS
1330
    // will be set to UnknownOS.
1331
769
    GetOsFromOSABI(header.e_ident[EI_OSABI], ostype);
1332
769
    spec_ostype = arch_spec.GetTriple().getOS();
1333
769
    assert(spec_ostype == ostype);
1334
769
    UNUSED_IF_ASSERT_DISABLED(spec_ostype);
1335
769
  }
1336
1337
1.14k
  if (arch_spec.GetMachine() == llvm::Triple::mips ||
1338
1.14k
      arch_spec.GetMachine() == llvm::Triple::mipsel ||
1339
1.14k
      arch_spec.GetMachine() == llvm::Triple::mips64 ||
1340
1.14k
      arch_spec.GetMachine() == llvm::Triple::mips64el) {
1341
0
    switch (header.e_flags & llvm::ELF::EF_MIPS_ARCH_ASE) {
1342
0
    case llvm::ELF::EF_MIPS_MICROMIPS:
1343
0
      arch_spec.SetFlags(ArchSpec::eMIPSAse_micromips);
1344
0
      break;
1345
0
    case llvm::ELF::EF_MIPS_ARCH_ASE_M16:
1346
0
      arch_spec.SetFlags(ArchSpec::eMIPSAse_mips16);
1347
0
      break;
1348
0
    case llvm::ELF::EF_MIPS_ARCH_ASE_MDMX:
1349
0
      arch_spec.SetFlags(ArchSpec::eMIPSAse_mdmx);
1350
0
      break;
1351
0
    default:
1352
0
      break;
1353
0
    }
1354
0
  }
1355
1356
1.14k
  if (arch_spec.GetMachine() == llvm::Triple::arm ||
1357
1.14k
      
arch_spec.GetMachine() == llvm::Triple::thumb1.07k
) {
1358
77
    if (header.e_flags & llvm::ELF::EF_ARM_SOFT_FLOAT)
1359
47
      arch_spec.SetFlags(ArchSpec::eARM_abi_soft_float);
1360
30
    else if (header.e_flags & llvm::ELF::EF_ARM_VFP_FLOAT)
1361
0
      arch_spec.SetFlags(ArchSpec::eARM_abi_hard_float);
1362
77
  }
1363
1364
  // If there are no section headers we are done.
1365
1.14k
  if (header.e_shnum == 0)
1366
468
    return 0;
1367
1368
681
  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES));
1369
1370
681
  section_headers.resize(header.e_shnum);
1371
681
  if (section_headers.size() != header.e_shnum)
1372
0
    return 0;
1373
1374
681
  const size_t sh_size = header.e_shnum * header.e_shentsize;
1375
681
  const elf_off sh_offset = header.e_shoff;
1376
681
  DataExtractor sh_data;
1377
681
  if (sh_data.SetData(object_data, sh_offset, sh_size) != sh_size)
1378
0
    return 0;
1379
1380
681
  uint32_t idx;
1381
681
  lldb::offset_t offset;
1382
139k
  for (idx = 0, offset = 0; idx < header.e_shnum; 
++idx138k
) {
1383
138k
    if (!section_headers[idx].Parse(sh_data, &offset))
1384
0
      break;
1385
138k
  }
1386
681
  if (idx < section_headers.size())
1387
0
    section_headers.resize(idx);
1388
1389
681
  const unsigned strtab_idx = header.e_shstrndx;
1390
681
  if (strtab_idx && strtab_idx < section_headers.size()) {
1391
681
    const ELFSectionHeaderInfo &sheader = section_headers[strtab_idx];
1392
681
    const size_t byte_size = sheader.sh_size;
1393
681
    const Elf64_Off offset = sheader.sh_offset;
1394
681
    lldb_private::DataExtractor shstr_data;
1395
1396
681
    if (shstr_data.SetData(object_data, offset, byte_size) == byte_size) {
1397
681
      for (SectionHeaderCollIter I = section_headers.begin();
1398
139k
           I != section_headers.end(); 
++I138k
) {
1399
138k
        static ConstString g_sect_name_gnu_debuglink(".gnu_debuglink");
1400
138k
        const ELFSectionHeaderInfo &sheader = *I;
1401
138k
        const uint64_t section_size =
1402
138k
            sheader.sh_type == SHT_NOBITS ? 
082
:
sheader.sh_size138k
;
1403
138k
        ConstString name(shstr_data.PeekCStr(I->sh_name));
1404
1405
138k
        I->section_name = name;
1406
1407
138k
        if (arch_spec.IsMIPS()) {
1408
0
          uint32_t arch_flags = arch_spec.GetFlags();
1409
0
          DataExtractor data;
1410
0
          if (sheader.sh_type == SHT_MIPS_ABIFLAGS) {
1411
1412
0
            if (section_size && (data.SetData(object_data, sheader.sh_offset,
1413
0
                                              section_size) == section_size)) {
1414
              // MIPS ASE Mask is at offset 12 in MIPS.abiflags section
1415
0
              lldb::offset_t offset = 12; // MIPS ABI Flags Version: 0
1416
0
              arch_flags |= data.GetU32(&offset);
1417
1418
              // The floating point ABI is at offset 7
1419
0
              offset = 7;
1420
0
              switch (data.GetU8(&offset)) {
1421
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_ANY:
1422
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_ANY;
1423
0
                break;
1424
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_DOUBLE:
1425
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_DOUBLE;
1426
0
                break;
1427
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_SINGLE:
1428
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SINGLE;
1429
0
                break;
1430
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_SOFT:
1431
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_SOFT;
1432
0
                break;
1433
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_OLD_64:
1434
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_OLD_64;
1435
0
                break;
1436
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_XX:
1437
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_XX;
1438
0
                break;
1439
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_64:
1440
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64;
1441
0
                break;
1442
0
              case llvm::Mips::Val_GNU_MIPS_ABI_FP_64A:
1443
0
                arch_flags |= lldb_private::ArchSpec::eMIPS_ABI_FP_64A;
1444
0
                break;
1445
0
              }
1446
0
            }
1447
0
          }
1448
          // Settings appropriate ArchSpec ABI Flags
1449
0
          switch (header.e_flags & llvm::ELF::EF_MIPS_ABI) {
1450
0
          case llvm::ELF::EF_MIPS_ABI_O32:
1451
0
            arch_flags |= lldb_private::ArchSpec::eMIPSABI_O32;
1452
0
            break;
1453
0
          case EF_MIPS_ABI_O64:
1454
0
            arch_flags |= lldb_private::ArchSpec::eMIPSABI_O64;
1455
0
            break;
1456
0
          case EF_MIPS_ABI_EABI32:
1457
0
            arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI32;
1458
0
            break;
1459
0
          case EF_MIPS_ABI_EABI64:
1460
0
            arch_flags |= lldb_private::ArchSpec::eMIPSABI_EABI64;
1461
0
            break;
1462
0
          default:
1463
            // ABI Mask doesn't cover N32 and N64 ABI.
1464
0
            if (header.e_ident[EI_CLASS] == llvm::ELF::ELFCLASS64)
1465
0
              arch_flags |= lldb_private::ArchSpec::eMIPSABI_N64;
1466
0
            else if (header.e_flags & llvm::ELF::EF_MIPS_ABI2)
1467
0
              arch_flags |= lldb_private::ArchSpec::eMIPSABI_N32;
1468
0
            break;
1469
0
          }
1470
0
          arch_spec.SetFlags(arch_flags);
1471
0
        }
1472
1473
138k
        if (arch_spec.GetMachine() == llvm::Triple::arm ||
1474
138k
            
arch_spec.GetMachine() == llvm::Triple::thumb138k
) {
1475
324
          DataExtractor data;
1476
1477
324
          if (sheader.sh_type == SHT_ARM_ATTRIBUTES && 
section_size != 04
&&
1478
324
              
data.SetData(object_data, sheader.sh_offset, section_size) == section_size4
)
1479
4
            ParseARMAttributes(data, section_size, arch_spec);
1480
324
        }
1481
1482
138k
        if (name == g_sect_name_gnu_debuglink) {
1483
4
          DataExtractor data;
1484
4
          if (section_size && (data.SetData(object_data, sheader.sh_offset,
1485
4
                                            section_size) == section_size)) {
1486
4
            lldb::offset_t gnu_debuglink_offset = 0;
1487
4
            gnu_debuglink_file = data.GetCStr(&gnu_debuglink_offset);
1488
4
            gnu_debuglink_offset = llvm::alignTo(gnu_debuglink_offset, 4);
1489
4
            data.GetU32(&gnu_debuglink_offset, &gnu_debuglink_crc, 1);
1490
4
          }
1491
4
        }
1492
1493
        // Process ELF note section entries.
1494
138k
        bool is_note_header = (sheader.sh_type == SHT_NOTE);
1495
1496
        // The section header ".note.android.ident" is stored as a
1497
        // PROGBITS type header but it is actually a note header.
1498
138k
        static ConstString g_sect_name_android_ident(".note.android.ident");
1499
138k
        if (!is_note_header && 
name == g_sect_name_android_ident138k
)
1500
0
          is_note_header = true;
1501
1502
138k
        if (is_note_header) {
1503
          // Allow notes to refine module info.
1504
258
          DataExtractor data;
1505
258
          if (section_size && (data.SetData(object_data, sheader.sh_offset,
1506
258
                                            section_size) == section_size)) {
1507
258
            Status error = RefineModuleDetailsFromNote(data, arch_spec, uuid);
1508
258
            if (error.Fail()) {
1509
0
              LLDB_LOGF(log, "ObjectFileELF::%s ELF note processing failed: %s",
1510
0
                        __FUNCTION__, error.AsCString());
1511
0
            }
1512
258
          }
1513
258
        }
1514
138k
      }
1515
1516
      // Make any unknown triple components to be unspecified unknowns.
1517
681
      if (arch_spec.GetTriple().getVendor() == llvm::Triple::UnknownVendor)
1518
681
        arch_spec.GetTriple().setVendorName(llvm::StringRef());
1519
681
      if (arch_spec.GetTriple().getOS() == llvm::Triple::UnknownOS)
1520
612
        arch_spec.GetTriple().setOSName(llvm::StringRef());
1521
1522
681
      return section_headers.size();
1523
681
    }
1524
681
  }
1525
1526
0
  section_headers.clear();
1527
0
  return 0;
1528
681
}
1529
1530
llvm::StringRef
1531
11
ObjectFileELF::StripLinkerSymbolAnnotations(llvm::StringRef symbol_name) const {
1532
11
  size_t pos = symbol_name.find('@');
1533
11
  return symbol_name.substr(0, pos);
1534
11
}
1535
1536
// ParseSectionHeaders
1537
1.80k
size_t ObjectFileELF::ParseSectionHeaders() {
1538
1.80k
  return GetSectionHeaderInfo(m_section_headers, m_data, m_header, m_uuid,
1539
1.80k
                              m_gnu_debuglink_file, m_gnu_debuglink_crc,
1540
1.80k
                              m_arch_spec);
1541
1.80k
}
1542
1543
const ObjectFileELF::ELFSectionHeaderInfo *
1544
430
ObjectFileELF::GetSectionHeaderByIndex(lldb::user_id_t id) {
1545
430
  if (!ParseSectionHeaders())
1546
0
    return nullptr;
1547
1548
430
  if (id < m_section_headers.size())
1549
428
    return &m_section_headers[id];
1550
1551
2
  return nullptr;
1552
430
}
1553
1554
22
lldb::user_id_t ObjectFileELF::GetSectionIndexByName(const char *name) {
1555
22
  if (!name || !name[0] || !ParseSectionHeaders())
1556
0
    return 0;
1557
206
  
for (size_t i = 1; 22
i < m_section_headers.size();
++i184
)
1558
206
    if (m_section_headers[i].section_name == ConstString(name))
1559
22
      return i;
1560
0
  return 0;
1561
22
}
1562
1563
67.2k
static SectionType GetSectionTypeFromName(llvm::StringRef Name) {
1564
67.2k
  if (Name.consume_front(".debug_") || 
Name.consume_front(".zdebug_")66.6k
) {
1565
669
    return llvm::StringSwitch<SectionType>(Name)
1566
669
        .Case("abbrev", eSectionTypeDWARFDebugAbbrev)
1567
669
        .Case("abbrev.dwo", eSectionTypeDWARFDebugAbbrevDwo)
1568
669
        .Case("addr", eSectionTypeDWARFDebugAddr)
1569
669
        .Case("aranges", eSectionTypeDWARFDebugAranges)
1570
669
        .Case("cu_index", eSectionTypeDWARFDebugCuIndex)
1571
669
        .Case("frame", eSectionTypeDWARFDebugFrame)
1572
669
        .Case("info", eSectionTypeDWARFDebugInfo)
1573
669
        .Case("info.dwo", eSectionTypeDWARFDebugInfoDwo)
1574
669
        .Cases("line", "line.dwo", eSectionTypeDWARFDebugLine)
1575
669
        .Cases("line_str", "line_str.dwo", eSectionTypeDWARFDebugLineStr)
1576
669
        .Case("loc", eSectionTypeDWARFDebugLoc)
1577
669
        .Case("loc.dwo", eSectionTypeDWARFDebugLocDwo)
1578
669
        .Case("loclists", eSectionTypeDWARFDebugLocLists)
1579
669
        .Case("loclists.dwo", eSectionTypeDWARFDebugLocListsDwo)
1580
669
        .Case("macinfo", eSectionTypeDWARFDebugMacInfo)
1581
669
        .Cases("macro", "macro.dwo", eSectionTypeDWARFDebugMacro)
1582
669
        .Case("names", eSectionTypeDWARFDebugNames)
1583
669
        .Case("pubnames", eSectionTypeDWARFDebugPubNames)
1584
669
        .Case("pubtypes", eSectionTypeDWARFDebugPubTypes)
1585
669
        .Case("ranges", eSectionTypeDWARFDebugRanges)
1586
669
        .Case("rnglists", eSectionTypeDWARFDebugRngLists)
1587
669
        .Case("rnglists.dwo", eSectionTypeDWARFDebugRngListsDwo)
1588
669
        .Case("str", eSectionTypeDWARFDebugStr)
1589
669
        .Case("str.dwo", eSectionTypeDWARFDebugStrDwo)
1590
669
        .Case("str_offsets", eSectionTypeDWARFDebugStrOffsets)
1591
669
        .Case("str_offsets.dwo", eSectionTypeDWARFDebugStrOffsetsDwo)
1592
669
        .Case("tu_index", eSectionTypeDWARFDebugTuIndex)
1593
669
        .Case("types", eSectionTypeDWARFDebugTypes)
1594
669
        .Case("types.dwo", eSectionTypeDWARFDebugTypesDwo)
1595
669
        .Default(eSectionTypeOther);
1596
669
  }
1597
66.6k
  return llvm::StringSwitch<SectionType>(Name)
1598
66.6k
      .Case(".ARM.exidx", eSectionTypeARMexidx)
1599
66.6k
      .Case(".ARM.extab", eSectionTypeARMextab)
1600
66.6k
      .Cases(".bss", ".tbss", eSectionTypeZeroFill)
1601
66.6k
      .Cases(".data", ".tdata", eSectionTypeData)
1602
66.6k
      .Case(".eh_frame", eSectionTypeEHFrame)
1603
66.6k
      .Case(".gnu_debugaltlink", eSectionTypeDWARFGNUDebugAltLink)
1604
66.6k
      .Case(".gosymtab", eSectionTypeGoSymtab)
1605
66.6k
      .Case(".text", eSectionTypeCode)
1606
66.6k
      .Default(eSectionTypeOther);
1607
67.2k
}
1608
1609
67.9k
SectionType ObjectFileELF::GetSectionType(const ELFSectionHeaderInfo &H) const {
1610
67.9k
  switch (H.sh_type) {
1611
66.8k
  case SHT_PROGBITS:
1612
66.8k
    if (H.sh_flags & SHF_EXECINSTR)
1613
271
      return eSectionTypeCode;
1614
66.5k
    break;
1615
66.5k
  case SHT_SYMTAB:
1616
144
    return eSectionTypeELFSymbolTable;
1617
39
  case SHT_DYNSYM:
1618
39
    return eSectionTypeELFDynamicSymbols;
1619
165
  case SHT_RELA:
1620
165
  case SHT_REL:
1621
165
    return eSectionTypeELFRelocationEntries;
1622
39
  case SHT_DYNAMIC:
1623
39
    return eSectionTypeELFDynamicLinkInfo;
1624
67.9k
  }
1625
67.2k
  return GetSectionTypeFromName(H.section_name.GetStringRef());
1626
67.9k
}
1627
1628
67.9k
static uint32_t GetTargetByteSize(SectionType Type, const ArchSpec &arch) {
1629
67.9k
  switch (Type) {
1630
64
  case eSectionTypeData:
1631
87
  case eSectionTypeZeroFill:
1632
87
    return arch.GetDataByteSize();
1633
271
  case eSectionTypeCode:
1634
271
    return arch.GetCodeByteSize();
1635
67.5k
  default:
1636
67.5k
    return 1;
1637
67.9k
  }
1638
67.9k
}
1639
1640
67.9k
static Permissions GetPermissions(const ELFSectionHeader &H) {
1641
67.9k
  Permissions Perm = Permissions(0);
1642
67.9k
  if (H.sh_flags & SHF_ALLOC)
1643
910
    Perm |= ePermissionsReadable;
1644
67.9k
  if (H.sh_flags & SHF_WRITE)
1645
185
    Perm |= ePermissionsWritable;
1646
67.9k
  if (H.sh_flags & SHF_EXECINSTR)
1647
271
    Perm |= ePermissionsExecutable;
1648
67.9k
  return Perm;
1649
67.9k
}
1650
1651
153
static Permissions GetPermissions(const ELFProgramHeader &H) {
1652
153
  Permissions Perm = Permissions(0);
1653
153
  if (H.p_flags & PF_R)
1654
152
    Perm |= ePermissionsReadable;
1655
153
  if (H.p_flags & PF_W)
1656
67
    Perm |= ePermissionsWritable;
1657
153
  if (H.p_flags & PF_X)
1658
88
    Perm |= ePermissionsExecutable;
1659
153
  return Perm;
1660
153
}
1661
1662
namespace {
1663
1664
using VMRange = lldb_private::Range<addr_t, addr_t>;
1665
1666
struct SectionAddressInfo {
1667
  SectionSP Segment;
1668
  VMRange Range;
1669
};
1670
1671
// (Unlinked) ELF object files usually have 0 for every section address, meaning
1672
// we need to compute synthetic addresses in order for "file addresses" from
1673
// different sections to not overlap. This class handles that logic.
1674
class VMAddressProvider {
1675
  using VMMap = llvm::IntervalMap<addr_t, SectionSP, 4,
1676
                                       llvm::IntervalMapHalfOpenInfo<addr_t>>;
1677
1678
  ObjectFile::Type ObjectType;
1679
  addr_t NextVMAddress = 0;
1680
  VMMap::Allocator Alloc;
1681
  VMMap Segments = VMMap(Alloc);
1682
  VMMap Sections = VMMap(Alloc);
1683
  lldb_private::Log *Log = GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES);
1684
  size_t SegmentCount = 0;
1685
  std::string SegmentName;
1686
1687
67.9k
  VMRange GetVMRange(const ELFSectionHeader &H) {
1688
67.9k
    addr_t Address = H.sh_addr;
1689
67.9k
    addr_t Size = H.sh_flags & SHF_ALLOC ? 
H.sh_size915
:
067.0k
;
1690
67.9k
    if (ObjectType == ObjectFile::Type::eTypeObjectFile && 
Segments.empty()66.3k
&&
(H.sh_flags & SHF_ALLOC)66.3k
) {
1691
113
      NextVMAddress =
1692
113
          llvm::alignTo(NextVMAddress, std::max<addr_t>(H.sh_addralign, 1));
1693
113
      Address = NextVMAddress;
1694
113
      NextVMAddress += Size;
1695
113
    }
1696
67.9k
    return VMRange(Address, Size);
1697
67.9k
  }
1698
1699
public:
1700
  VMAddressProvider(ObjectFile::Type Type, llvm::StringRef SegmentName)
1701
496
      : ObjectType(Type), SegmentName(std::string(SegmentName)) {}
1702
1703
153
  std::string GetNextSegmentName() const {
1704
153
    return llvm::formatv("{0}[{1}]", SegmentName, SegmentCount).str();
1705
153
  }
1706
1707
157
  llvm::Optional<VMRange> GetAddressInfo(const ELFProgramHeader &H) {
1708
157
    if (H.p_memsz == 0) {
1709
1
      LLDB_LOG(Log, "Ignoring zero-sized {0} segment. Corrupt object file?",
1710
1
               SegmentName);
1711
1
      return llvm::None;
1712
1
    }
1713
1714
156
    if (Segments.overlaps(H.p_vaddr, H.p_vaddr + H.p_memsz)) {
1715
3
      LLDB_LOG(Log, "Ignoring overlapping {0} segment. Corrupt object file?",
1716
3
               SegmentName);
1717
3
      return llvm::None;
1718
3
    }
1719
153
    return VMRange(H.p_vaddr, H.p_memsz);
1720
156
  }
1721
1722
67.9k
  llvm::Optional<SectionAddressInfo> GetAddressInfo(const ELFSectionHeader &H) {
1723
67.9k
    VMRange Range = GetVMRange(H);
1724
67.9k
    SectionSP Segment;
1725
67.9k
    auto It = Segments.find(Range.GetRangeBase());
1726
67.9k
    if ((H.sh_flags & SHF_ALLOC) && 
It.valid()915
) {
1727
701
      addr_t MaxSize;
1728
701
      if (It.start() <= Range.GetRangeBase()) {
1729
692
        MaxSize = It.stop() - Range.GetRangeBase();
1730
692
        Segment = *It;
1731
692
      } else
1732
9
        MaxSize = It.start() - Range.GetRangeBase();
1733
701
      if (Range.GetByteSize() > MaxSize) {
1734
2
        LLDB_LOG(Log, "Shortening section crossing segment boundaries. "
1735
2
                      "Corrupt object file?");
1736
2
        Range.SetByteSize(MaxSize);
1737
2
      }
1738
701
    }
1739
67.9k
    if (Range.GetByteSize() > 0 &&
1740
67.9k
        
Sections.overlaps(Range.GetRangeBase(), Range.GetRangeEnd())870
) {
1741
5
      LLDB_LOG(Log, "Ignoring overlapping section. Corrupt object file?");
1742
5
      return llvm::None;
1743
5
    }
1744
67.9k
    if (Segment)
1745
689
      Range.Slide(-Segment->GetFileAddress());
1746
67.9k
    return SectionAddressInfo{Segment, Range};
1747
67.9k
  }
1748
1749
153
  void AddSegment(const VMRange &Range, SectionSP Seg) {
1750
153
    Segments.insert(Range.GetRangeBase(), Range.GetRangeEnd(), std::move(Seg));
1751
153
    ++SegmentCount;
1752
153
  }
1753
1754
67.9k
  void AddSection(SectionAddressInfo Info, SectionSP Sect) {
1755
67.9k
    if (Info.Range.GetByteSize() == 0)
1756
67.0k
      return;
1757
865
    if (Info.Segment)
1758
685
      Info.Range.Slide(Info.Segment->GetFileAddress());
1759
865
    Sections.insert(Info.Range.GetRangeBase(), Info.Range.GetRangeEnd(),
1760
865
                    std::move(Sect));
1761
865
  }
1762
};
1763
}
1764
1765
252
void ObjectFileELF::CreateSections(SectionList &unified_section_list) {
1766
252
  if (m_sections_up)
1767
4
    return;
1768
1769
248
  m_sections_up = std::make_unique<SectionList>();
1770
248
  VMAddressProvider regular_provider(GetType(), "PT_LOAD");
1771
248
  VMAddressProvider tls_provider(GetType(), "PT_TLS");
1772
1773
383
  for (const auto &EnumPHdr : llvm::enumerate(ProgramHeaders())) {
1774
383
    const ELFProgramHeader &PHdr = EnumPHdr.value();
1775
383
    if (PHdr.p_type != PT_LOAD && 
PHdr.p_type != PT_TLS230
)
1776
226
      continue;
1777
1778
157
    VMAddressProvider &provider =
1779
157
        PHdr.p_type == PT_TLS ? 
tls_provider4
:
regular_provider153
;
1780
157
    auto InfoOr = provider.GetAddressInfo(PHdr);
1781
157
    if (!InfoOr)
1782
4
      continue;
1783
1784
153
    uint32_t Log2Align = llvm::Log2_64(std::max<elf_xword>(PHdr.p_align, 1));
1785
153
    SectionSP Segment = std::make_shared<Section>(
1786
153
        GetModule(), this, SegmentID(EnumPHdr.index()),
1787
153
        ConstString(provider.GetNextSegmentName()), eSectionTypeContainer,
1788
153
        InfoOr->GetRangeBase(), InfoOr->GetByteSize(), PHdr.p_offset,
1789
153
        PHdr.p_filesz, Log2Align, /*flags*/ 0);
1790
153
    Segment->SetPermissions(GetPermissions(PHdr));
1791
153
    Segment->SetIsThreadSpecific(PHdr.p_type == PT_TLS);
1792
153
    m_sections_up->AddSection(Segment);
1793
1794
153
    provider.AddSegment(*InfoOr, std::move(Segment));
1795
153
  }
1796
1797
248
  ParseSectionHeaders();
1798
248
  if (m_section_headers.empty())
1799
1
    return;
1800
1801
247
  for (SectionHeaderCollIter I = std::next(m_section_headers.begin());
1802
68.1k
       I != m_section_headers.end(); 
++I67.9k
) {
1803
67.9k
    const ELFSectionHeaderInfo &header = *I;
1804
1805
67.9k
    ConstString &name = I->section_name;
1806
67.9k
    const uint64_t file_size =
1807
67.9k
        header.sh_type == SHT_NOBITS ? 
023
:
header.sh_size67.9k
;
1808
1809
67.9k
    VMAddressProvider &provider =
1810
67.9k
        header.sh_flags & SHF_TLS ? 
tls_provider6
:
regular_provider67.9k
;
1811
67.9k
    auto InfoOr = provider.GetAddressInfo(header);
1812
67.9k
    if (!InfoOr)
1813
5
      continue;
1814
1815
67.9k
    SectionType sect_type = GetSectionType(header);
1816
1817
67.9k
    const uint32_t target_bytes_size =
1818
67.9k
        GetTargetByteSize(sect_type, m_arch_spec);
1819
1820
67.9k
    elf::elf_xword log2align =
1821
67.9k
        (header.sh_addralign == 0) ? 
025
:
llvm::Log2_64(header.sh_addralign)67.9k
;
1822
1823
67.9k
    SectionSP section_sp(new Section(
1824
67.9k
        InfoOr->Segment, GetModule(), // Module to which this section belongs.
1825
67.9k
        this,            // ObjectFile to which this section belongs and should
1826
                         // read section data from.
1827
67.9k
        SectionIndex(I), // Section ID.
1828
67.9k
        name,            // Section name.
1829
67.9k
        sect_type,       // Section type.
1830
67.9k
        InfoOr->Range.GetRangeBase(), // VM address.
1831
67.9k
        InfoOr->Range.GetByteSize(),  // VM size in bytes of this section.
1832
67.9k
        header.sh_offset,             // Offset of this section in the file.
1833
67.9k
        file_size,           // Size of the section as found in the file.
1834
67.9k
        log2align,           // Alignment of the section
1835
67.9k
        header.sh_flags,     // Flags for this section.
1836
67.9k
        target_bytes_size)); // Number of host bytes per target byte
1837
1838
67.9k
    section_sp->SetPermissions(GetPermissions(header));
1839
67.9k
    section_sp->SetIsThreadSpecific(header.sh_flags & SHF_TLS);
1840
67.9k
    (InfoOr->Segment ? 
InfoOr->Segment->GetChildren()689
:
*m_sections_up67.2k
)
1841
67.9k
        .AddSection(section_sp);
1842
67.9k
    provider.AddSection(std::move(*InfoOr), std::move(section_sp));
1843
67.9k
  }
1844
1845
  // For eTypeDebugInfo files, the Symbol Vendor will take care of updating the
1846
  // unified section list.
1847
247
  if (GetType() != eTypeDebugInfo)
1848
242
    unified_section_list = *m_sections_up;
1849
1850
  // If there's a .gnu_debugdata section, we'll try to read the .symtab that's
1851
  // embedded in there and replace the one in the original object file (if any).
1852
  // If there's none in the orignal object file, we add it to it.
1853
247
  if (auto gdd_obj_file = GetGnuDebugDataObjectFile()) {
1854
1
    if (auto gdd_objfile_section_list = gdd_obj_file->GetSectionList()) {
1855
1
      if (SectionSP symtab_section_sp =
1856
1
              gdd_objfile_section_list->FindSectionByType(
1857
1
                  eSectionTypeELFSymbolTable, true)) {
1858
1
        SectionSP module_section_sp = unified_section_list.FindSectionByType(
1859
1
            eSectionTypeELFSymbolTable, true);
1860
1
        if (module_section_sp)
1861
0
          unified_section_list.ReplaceSection(module_section_sp->GetID(),
1862
0
                                              symtab_section_sp);
1863
1
        else
1864
1
          unified_section_list.AddSection(symtab_section_sp);
1865
1
      }
1866
1
    }
1867
1
  }
1868
247
}
1869
1870
247
std::shared_ptr<ObjectFileELF> ObjectFileELF::GetGnuDebugDataObjectFile() {
1871
247
  if (m_gnu_debug_data_object_file != nullptr)
1872
0
    return m_gnu_debug_data_object_file;
1873
1874
247
  SectionSP section =
1875
247
      GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"));
1876
247
  if (!section)
1877
245
    return nullptr;
1878
1879
2
  if (!lldb_private::lzma::isAvailable()) {
1880
0
    GetModule()->ReportWarning(
1881
0
        "No LZMA support found for reading .gnu_debugdata section");
1882
0
    return nullptr;
1883
0
  }
1884
1885
  // Uncompress the data
1886
2
  DataExtractor data;
1887
2
  section->GetSectionData(data);
1888
2
  llvm::SmallVector<uint8_t, 0> uncompressedData;
1889
2
  auto err = lldb_private::lzma::uncompress(data.GetData(), uncompressedData);
1890
2
  if (err) {
1891
1
    GetModule()->ReportWarning(
1892
1
        "An error occurred while decompression the section %s: %s",
1893
1
        section->GetName().AsCString(), llvm::toString(std::move(err)).c_str());
1894
1
    return nullptr;
1895
1
  }
1896
1897
  // Construct ObjectFileELF object from decompressed buffer
1898
1
  DataBufferSP gdd_data_buf(
1899
1
      new DataBufferHeap(uncompressedData.data(), uncompressedData.size()));
1900
1
  auto fspec = GetFileSpec().CopyByAppendingPathComponent(
1901
1
      llvm::StringRef("gnu_debugdata"));
1902
1
  m_gnu_debug_data_object_file.reset(new ObjectFileELF(
1903
1
      GetModule(), gdd_data_buf, 0, &fspec, 0, gdd_data_buf->GetByteSize()));
1904
1905
  // This line is essential; otherwise a breakpoint can be set but not hit.
1906
1
  m_gnu_debug_data_object_file->SetType(ObjectFile::eTypeDebugInfo);
1907
1908
1
  ArchSpec spec = m_gnu_debug_data_object_file->GetArchitecture();
1909
1
  if (spec && m_gnu_debug_data_object_file->SetModulesArchitecture(spec))
1910
1
    return m_gnu_debug_data_object_file;
1911
1912
0
  return nullptr;
1913
1
}
1914
1915
// Find the arm/aarch64 mapping symbol character in the given symbol name.
1916
// Mapping symbols have the form of "$<char>[.<any>]*". Additionally we
1917
// recognize cases when the mapping symbol prefixed by an arbitrary string
1918
// because if a symbol prefix added to each symbol in the object file with
1919
// objcopy then the mapping symbols are also prefixed.
1920
232
static char FindArmAarch64MappingSymbol(const char *symbol_name) {
1921
232
  if (!symbol_name)
1922
0
    return '\0';
1923
1924
232
  const char *dollar_pos = ::strchr(symbol_name, '$');
1925
232
  if (!dollar_pos || 
dollar_pos[1] == '\0'66
)
1926
166
    return '\0';
1927
1928
66
  if (dollar_pos[2] == '\0' || 
dollar_pos[2] == '.'8
)
1929
66
    return dollar_pos[1];
1930
0
  return '\0';
1931
66
}
1932
1933
0
#define STO_MIPS_ISA (3 << 6)
1934
0
#define STO_MICROMIPS (2 << 6)
1935
0
#define IS_MICROMIPS(ST_OTHER) (((ST_OTHER)&STO_MIPS_ISA) == STO_MICROMIPS)
1936
1937
// private
1938
unsigned ObjectFileELF::ParseSymbols(Symtab *symtab, user_id_t start_id,
1939
                                     SectionList *section_list,
1940
                                     const size_t num_symbols,
1941
                                     const DataExtractor &symtab_data,
1942
143
                                     const DataExtractor &strtab_data) {
1943
143
  ELFSymbol symbol;
1944
143
  lldb::offset_t offset = 0;
1945
1946
143
  static ConstString text_section_name(".text");
1947
143
  static ConstString init_section_name(".init");
1948
143
  static ConstString fini_section_name(".fini");
1949
143
  static ConstString ctors_section_name(".ctors");
1950
143
  static ConstString dtors_section_name(".dtors");
1951
1952
143
  static ConstString data_section_name(".data");
1953
143
  static ConstString rodata_section_name(".rodata");
1954
143
  static ConstString rodata1_section_name(".rodata1");
1955
143
  static ConstString data2_section_name(".data1");
1956
143
  static ConstString bss_section_name(".bss");
1957
143
  static ConstString opd_section_name(".opd"); // For ppc64
1958
1959
  // On Android the oatdata and the oatexec symbols in the oat and odex files
1960
  // covers the full .text section what causes issues with displaying unusable
1961
  // symbol name to the user and very slow unwinding speed because the
1962
  // instruction emulation based unwind plans try to emulate all instructions
1963
  // in these symbols. Don't add these symbols to the symbol list as they have
1964
  // no use for the debugger and they are causing a lot of trouble. Filtering
1965
  // can't be restricted to Android because this special object file don't
1966
  // contain the note section specifying the environment to Android but the
1967
  // custom extension and file name makes it highly unlikely that this will
1968
  // collide with anything else.
1969
143
  ConstString file_extension = m_file.GetFileNameExtension();
1970
143
  bool skip_oatdata_oatexec =
1971
143
      file_extension == ".oat" || file_extension == ".odex";
1972
1973
143
  ArchSpec arch = GetArchitecture();
1974
143
  ModuleSP module_sp(GetModule());
1975
143
  SectionList *module_section_list =
1976
143
      module_sp ? module_sp->GetSectionList() : 
nullptr0
;
1977
1978
  // Local cache to avoid doing a FindSectionByName for each symbol. The "const
1979
  // char*" key must came from a ConstString object so they can be compared by
1980
  // pointer
1981
143
  std::unordered_map<const char *, lldb::SectionSP> section_name_to_section;
1982
1983
143
  unsigned i;
1984
2.38k
  for (i = 0; i < num_symbols; 
++i2.24k
) {
1985
2.24k
    if (!symbol.Parse(symtab_data, &offset))
1986
0
      break;
1987
1988
2.24k
    const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
1989
2.24k
    if (!symbol_name)
1990
0
      symbol_name = "";
1991
1992
    // No need to add non-section symbols that have no names
1993
2.24k
    if (symbol.getType() != STT_SECTION &&
1994
2.24k
        
(1.52k
symbol_name == nullptr1.52k
||
symbol_name[0] == '\0'1.52k
))
1995
170
      continue;
1996
1997
    // Skipping oatdata and oatexec sections if it is requested. See details
1998
    // above the definition of skip_oatdata_oatexec for the reasons.
1999
2.07k
    if (skip_oatdata_oatexec && 
(0
::strcmp(symbol_name, "oatdata") == 00
||
2000
0
                                 ::strcmp(symbol_name, "oatexec") == 0))
2001
0
      continue;
2002
2003
2.07k
    SectionSP symbol_section_sp;
2004
2.07k
    SymbolType symbol_type = eSymbolTypeInvalid;
2005
2.07k
    Elf64_Half shndx = symbol.st_shndx;
2006
2007
2.07k
    switch (shndx) {
2008
119
    case SHN_ABS:
2009
119
      symbol_type = eSymbolTypeAbsolute;
2010
119
      break;
2011
125
    case SHN_UNDEF:
2012
125
      symbol_type = eSymbolTypeUndefined;
2013
125
      break;
2014
1.82k
    default:
2015
1.82k
      symbol_section_sp = section_list->FindSectionByID(shndx);
2016
1.82k
      break;
2017
2.07k
    }
2018
2019
    // If a symbol is undefined do not process it further even if it has a STT
2020
    // type
2021
2.07k
    if (symbol_type != eSymbolTypeUndefined) {
2022
1.94k
      switch (symbol.getType()) {
2023
0
      default:
2024
696
      case STT_NOTYPE:
2025
        // The symbol's type is not specified.
2026
696
        break;
2027
2028
182
      case STT_OBJECT:
2029
        // The symbol is associated with a data object, such as a variable, an
2030
        // array, etc.
2031
182
        symbol_type = eSymbolTypeData;
2032
182
        break;
2033
2034
274
      case STT_FUNC:
2035
        // The symbol is associated with a function or other executable code.
2036
274
        symbol_type = eSymbolTypeCode;
2037
274
        break;
2038
2039
715
      case STT_SECTION:
2040
        // The symbol is associated with a section. Symbol table entries of
2041
        // this type exist primarily for relocation and normally have STB_LOCAL
2042
        // binding.
2043
715
        break;
2044
2045
78
      case STT_FILE:
2046
        // Conventionally, the symbol's name gives the name of the source file
2047
        // associated with the object file. A file symbol has STB_LOCAL
2048
        // binding, its section index is SHN_ABS, and it precedes the other
2049
        // STB_LOCAL symbols for the file, if it is present.
2050
78
        symbol_type = eSymbolTypeSourceFile;
2051
78
        break;
2052
2053
0
      case STT_GNU_IFUNC:
2054
        // The symbol is associated with an indirect function. The actual
2055
        // function will be resolved if it is referenced.
2056
0
        symbol_type = eSymbolTypeResolver;
2057
0
        break;
2058
1.94k
      }
2059
1.94k
    }
2060
2061
2.07k
    if (symbol_type == eSymbolTypeInvalid && 
symbol.getType() != STT_SECTION1.38k
) {
2062
669
      if (symbol_section_sp) {
2063
669
        ConstString sect_name = symbol_section_sp->GetName();
2064
669
        if (sect_name == text_section_name || 
sect_name == init_section_name535
||
2065
669
            
sect_name == fini_section_name531
||
sect_name == ctors_section_name527
||
2066
669
            
sect_name == dtors_section_name511
) {
2067
158
          symbol_type = eSymbolTypeCode;
2068
511
        } else if (sect_name == data_section_name ||
2069
511
                   
sect_name == data2_section_name209
||
2070
511
                   
sect_name == rodata_section_name209
||
2071
511
                   
sect_name == rodata1_section_name202
||
2072
511
                   
sect_name == bss_section_name202
) {
2073
339
          symbol_type = eSymbolTypeData;
2074
339
        }
2075
669
      }
2076
669
    }
2077
2078
2.07k
    int64_t symbol_value_offset = 0;
2079
2.07k
    uint32_t additional_flags = 0;
2080
2081
2.07k
    if (arch.IsValid()) {
2082
2.07k
      if (arch.GetMachine() == llvm::Triple::arm) {
2083
0
        if (symbol.getBinding() == STB_LOCAL) {
2084
0
          char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2085
0
          if (symbol_type == eSymbolTypeCode) {
2086
0
            switch (mapping_symbol) {
2087
0
            case 'a':
2088
              // $a[.<any>]* - marks an ARM instruction sequence
2089
0
              m_address_class_map[symbol.st_value] = AddressClass::eCode;
2090
0
              break;
2091
0
            case 'b':
2092
0
            case 't':
2093
              // $b[.<any>]* - marks a THUMB BL instruction sequence
2094
              // $t[.<any>]* - marks a THUMB instruction sequence
2095
0
              m_address_class_map[symbol.st_value] =
2096
0
                  AddressClass::eCodeAlternateISA;
2097
0
              break;
2098
0
            case 'd':
2099
              // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2100
0
              m_address_class_map[symbol.st_value] = AddressClass::eData;
2101
0
              break;
2102
0
            }
2103
0
          }
2104
0
          if (mapping_symbol)
2105
0
            continue;
2106
0
        }
2107
2.07k
      } else if (arch.GetMachine() == llvm::Triple::aarch64) {
2108
353
        if (symbol.getBinding() == STB_LOCAL) {
2109
232
          char mapping_symbol = FindArmAarch64MappingSymbol(symbol_name);
2110
232
          if (symbol_type == eSymbolTypeCode) {
2111
28
            switch (mapping_symbol) {
2112
17
            case 'x':
2113
              // $x[.<any>]* - marks an A64 instruction sequence
2114
17
              m_address_class_map[symbol.st_value] = AddressClass::eCode;
2115
17
              break;
2116
0
            case 'd':
2117
              // $d[.<any>]* - marks a data item sequence (e.g. lit pool)
2118
0
              m_address_class_map[symbol.st_value] = AddressClass::eData;
2119
0
              break;
2120
28
            }
2121
28
          }
2122
232
          if (mapping_symbol)
2123
66
            continue;
2124
232
        }
2125
353
      }
2126
2127
2.00k
      if (arch.GetMachine() == llvm::Triple::arm) {
2128
0
        if (symbol_type == eSymbolTypeCode) {
2129
0
          if (symbol.st_value & 1) {
2130
            // Subtracting 1 from the address effectively unsets the low order
2131
            // bit, which results in the address actually pointing to the
2132
            // beginning of the symbol. This delta will be used below in
2133
            // conjunction with symbol.st_value to produce the final
2134
            // symbol_value that we store in the symtab.
2135
0
            symbol_value_offset = -1;
2136
0
            m_address_class_map[symbol.st_value ^ 1] =
2137
0
                AddressClass::eCodeAlternateISA;
2138
0
          } else {
2139
            // This address is ARM
2140
0
            m_address_class_map[symbol.st_value] = AddressClass::eCode;
2141
0
          }
2142
0
        }
2143
0
      }
2144
2145
      /*
2146
       * MIPS:
2147
       * The bit #0 of an address is used for ISA mode (1 for microMIPS, 0 for
2148
       * MIPS).
2149
       * This allows processor to switch between microMIPS and MIPS without any
2150
       * need
2151
       * for special mode-control register. However, apart from .debug_line,
2152
       * none of
2153
       * the ELF/DWARF sections set the ISA bit (for symbol or section). Use
2154
       * st_other
2155
       * flag to check whether the symbol is microMIPS and then set the address
2156
       * class
2157
       * accordingly.
2158
      */
2159
2.00k
      if (arch.IsMIPS()) {
2160
0
        if (IS_MICROMIPS(symbol.st_other))
2161
0
          m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2162
0
        else if ((symbol.st_value & 1) && (symbol_type == eSymbolTypeCode)) {
2163
0
          symbol.st_value = symbol.st_value & (~1ull);
2164
0
          m_address_class_map[symbol.st_value] = AddressClass::eCodeAlternateISA;
2165
0
        } else {
2166
0
          if (symbol_type == eSymbolTypeCode)
2167
0
            m_address_class_map[symbol.st_value] = AddressClass::eCode;
2168
0
          else if (symbol_type == eSymbolTypeData)
2169
0
            m_address_class_map[symbol.st_value] = AddressClass::eData;
2170
0
          else
2171
0
            m_address_class_map[symbol.st_value] = AddressClass::eUnknown;
2172
0
        }
2173
0
      }
2174
2.00k
    }
2175
2176
    // symbol_value_offset may contain 0 for ARM symbols or -1 for THUMB
2177
    // symbols. See above for more details.
2178
2.00k
    uint64_t symbol_value = symbol.st_value + symbol_value_offset;
2179
2180
2.00k
    if (symbol_section_sp == nullptr && 
shndx == SHN_ABS246
&&
2181
2.00k
        
symbol.st_size != 0119
) {
2182
      // We don't have a section for a symbol with non-zero size. Create a new
2183
      // section for it so the address range covered by the symbol is also
2184
      // covered by the module (represented through the section list). It is
2185
      // needed so module lookup for the addresses covered by this symbol will
2186
      // be successfull. This case happens for absolute symbols.
2187
0
      ConstString fake_section_name(std::string(".absolute.") + symbol_name);
2188
0
      symbol_section_sp =
2189
0
          std::make_shared<Section>(module_sp, this, SHN_ABS, fake_section_name,
2190
0
                                    eSectionTypeAbsoluteAddress, symbol_value,
2191
0
                                    symbol.st_size, 0, 0, 0, SHF_ALLOC);
2192
2193
0
      module_section_list->AddSection(symbol_section_sp);
2194
0
      section_list->AddSection(symbol_section_sp);
2195
0
    }
2196
2197
2.00k
    if (symbol_section_sp &&
2198
2.00k
        
CalculateType() != ObjectFile::Type::eTypeObjectFile1.75k
)
2199
1.12k
      symbol_value -= symbol_section_sp->GetFileAddress();
2200
2201
2.00k
    if (symbol_section_sp && 
module_section_list1.75k
&&
2202
2.00k
        
module_section_list != section_list1.75k
) {
2203
1.75k
      ConstString sect_name = symbol_section_sp->GetName();
2204
1.75k
      auto section_it = section_name_to_section.find(sect_name.GetCString());
2205
1.75k
      if (section_it == section_name_to_section.end())
2206
828
        section_it =
2207
828
            section_name_to_section
2208
828
                .emplace(sect_name.GetCString(),
2209
828
                         module_section_list->FindSectionByName(sect_name))
2210
828
                .first;
2211
1.75k
      if (section_it->second)
2212
1.75k
        symbol_section_sp = section_it->second;
2213
1.75k
    }
2214
2215
2.00k
    bool is_global = symbol.getBinding() == STB_GLOBAL;
2216
2.00k
    uint32_t flags = symbol.st_other << 8 | symbol.st_info | additional_flags;
2217
2.00k
    llvm::StringRef symbol_ref(symbol_name);
2218
2219
    // Symbol names may contain @VERSION suffixes. Find those and strip them
2220
    // temporarily.
2221
2.00k
    size_t version_pos = symbol_ref.find('@');
2222
2.00k
    bool has_suffix = version_pos != llvm::StringRef::npos;
2223
2.00k
    llvm::StringRef symbol_bare = symbol_ref.substr(0, version_pos);
2224
2.00k
    Mangled mangled(symbol_bare);
2225
2226
    // Now append the suffix back to mangled and unmangled names. Only do it if
2227
    // the demangling was successful (string is not empty).
2228
2.00k
    if (has_suffix) {
2229
11
      llvm::StringRef suffix = symbol_ref.substr(version_pos);
2230
2231
11
      llvm::StringRef mangled_name = mangled.GetMangledName().GetStringRef();
2232
11
      if (!mangled_name.empty())
2233
1
        mangled.SetMangledName(ConstString((mangled_name + suffix).str()));
2234
2235
11
      ConstString demangled = mangled.GetDemangledName();
2236
11
      llvm::StringRef demangled_name = demangled.GetStringRef();
2237
11
      if (!demangled_name.empty())
2238
10
        mangled.SetDemangledName(ConstString((demangled_name + suffix).str()));
2239
11
    }
2240
2241
    // In ELF all symbol should have a valid size but it is not true for some
2242
    // function symbols coming from hand written assembly. As none of the
2243
    // function symbol should have 0 size we try to calculate the size for
2244
    // these symbols in the symtab with saying that their original size is not
2245
    // valid.
2246
2.00k
    bool symbol_size_valid =
2247
2.00k
        symbol.st_size != 0 || 
symbol.getType() != STT_FUNC1.66k
;
2248
2249
2.00k
    Symbol dc_symbol(
2250
2.00k
        i + start_id, // ID is the original symbol table index.
2251
2.00k
        mangled,
2252
2.00k
        symbol_type,                    // Type of this symbol
2253
2.00k
        is_global,                      // Is this globally visible?
2254
2.00k
        false,                          // Is this symbol debug info?
2255
2.00k
        false,                          // Is this symbol a trampoline?
2256
2.00k
        false,                          // Is this symbol artificial?
2257
2.00k
        AddressRange(symbol_section_sp, // Section in which this symbol is
2258
                                        // defined or null.
2259
2.00k
                     symbol_value,      // Offset in section or symbol value.
2260
2.00k
                     symbol.st_size),   // Size in bytes of this symbol.
2261
2.00k
        symbol_size_valid,              // Symbol size is valid
2262
2.00k
        has_suffix,                     // Contains linker annotations?
2263
2.00k
        flags);                         // Symbol flags.
2264
2.00k
    if (symbol.getBinding() == STB_WEAK)
2265
63
      dc_symbol.SetIsWeak(true);
2266
2.00k
    symtab->AddSymbol(dc_symbol);
2267
2.00k
  }
2268
143
  return i;
2269
143
}
2270
2271
unsigned ObjectFileELF::ParseSymbolTable(Symtab *symbol_table,
2272
                                         user_id_t start_id,
2273
149
                                         lldb_private::Section *symtab) {
2274
149
  if (symtab->GetObjectFile() != this) {
2275
    // If the symbol table section is owned by a different object file, have it
2276
    // do the parsing.
2277
5
    ObjectFileELF *obj_file_elf =
2278
5
        static_cast<ObjectFileELF *>(symtab->GetObjectFile());
2279
5
    return obj_file_elf->ParseSymbolTable(symbol_table, start_id, symtab);
2280
5
  }
2281
2282
  // Get section list for this object file.
2283
144
  SectionList *section_list = m_sections_up.get();
2284
144
  if (!section_list)
2285
0
    return 0;
2286
2287
144
  user_id_t symtab_id = symtab->GetID();
2288
144
  const ELFSectionHeaderInfo *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2289
144
  assert(symtab_hdr->sh_type == SHT_SYMTAB ||
2290
144
         symtab_hdr->sh_type == SHT_DYNSYM);
2291
2292
  // sh_link: section header index of associated string table.
2293
0
  user_id_t strtab_id = symtab_hdr->sh_link;
2294
144
  Section *strtab = section_list->FindSectionByID(strtab_id).get();
2295
2296
144
  if (symtab && strtab) {
2297
143
    assert(symtab->GetObjectFile() == this);
2298
0
    assert(strtab->GetObjectFile() == this);
2299
2300
0
    DataExtractor symtab_data;
2301
143
    DataExtractor strtab_data;
2302
143
    if (ReadSectionData(symtab, symtab_data) &&
2303
143
        ReadSectionData(strtab, strtab_data)) {
2304
143
      size_t num_symbols = symtab_data.GetByteSize() / symtab_hdr->sh_entsize;
2305
2306
143
      return ParseSymbols(symbol_table, start_id, section_list, num_symbols,
2307
143
                          symtab_data, strtab_data);
2308
143
    }
2309
143
  }
2310
2311
1
  return 0;
2312
144
}
2313
2314
299
size_t ObjectFileELF::ParseDynamicSymbols() {
2315
299
  if (m_dynamic_symbols.size())
2316
35
    return m_dynamic_symbols.size();
2317
2318
264
  SectionList *section_list = GetSectionList();
2319
264
  if (!section_list)
2320
0
    return 0;
2321
2322
  // Find the SHT_DYNAMIC section.
2323
264
  Section *dynsym =
2324
264
      section_list->FindSectionByType(eSectionTypeELFDynamicLinkInfo, true)
2325
264
          .get();
2326
264
  if (!dynsym)
2327
227
    return 0;
2328
37
  assert(dynsym->GetObjectFile() == this);
2329
2330
0
  ELFDynamic symbol;
2331
37
  DataExtractor dynsym_data;
2332
37
  if (ReadSectionData(dynsym, dynsym_data)) {
2333
37
    const lldb::offset_t section_size = dynsym_data.GetByteSize();
2334
37
    lldb::offset_t cursor = 0;
2335
2336
742
    while (cursor < section_size) {
2337
705
      if (!symbol.Parse(dynsym_data, &cursor))
2338
0
        break;
2339
2340
705
      m_dynamic_symbols.push_back(symbol);
2341
705
    }
2342
37
  }
2343
2344
37
  return m_dynamic_symbols.size();
2345
264
}
2346
2347
253
const ELFDynamic *ObjectFileELF::FindDynamicSymbol(unsigned tag) {
2348
253
  if (!ParseDynamicSymbols())
2349
193
    return nullptr;
2350
2351
60
  DynamicSymbolCollIter I = m_dynamic_symbols.begin();
2352
60
  DynamicSymbolCollIter E = m_dynamic_symbols.end();
2353
778
  for (; I != E; 
++I718
) {
2354
764
    ELFDynamic *symbol = &*I;
2355
2356
764
    if (symbol->d_tag == tag)
2357
46
      return symbol;
2358
764
  }
2359
2360
14
  return nullptr;
2361
60
}
2362
2363
22
unsigned ObjectFileELF::PLTRelocationType() {
2364
  // DT_PLTREL
2365
  //  This member specifies the type of relocation entry to which the
2366
  //  procedure linkage table refers. The d_val member holds DT_REL or
2367
  //  DT_RELA, as appropriate. All relocations in a procedure linkage table
2368
  //  must use the same relocation.
2369
22
  const ELFDynamic *symbol = FindDynamicSymbol(DT_PLTREL);
2370
2371
22
  if (symbol)
2372
22
    return symbol->d_val;
2373
2374
0
  return 0;
2375
22
}
2376
2377
// Returns the size of the normal plt entries and the offset of the first
2378
// normal plt entry. The 0th entry in the plt table is usually a resolution
2379
// entry which have different size in some architectures then the rest of the
2380
// plt entries.
2381
static std::pair<uint64_t, uint64_t>
2382
GetPltEntrySizeAndOffset(const ELFSectionHeader *rel_hdr,
2383
22
                         const ELFSectionHeader *plt_hdr) {
2384
22
  const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2385
2386
  // Clang 3.3 sets entsize to 4 for 32-bit binaries, but the plt entries are
2387
  // 16 bytes. So round the entsize up by the alignment if addralign is set.
2388
22
  elf_xword plt_entsize =
2389
22
      plt_hdr->sh_addralign
2390
22
          ? llvm::alignTo(plt_hdr->sh_entsize, plt_hdr->sh_addralign)
2391
22
          : 
plt_hdr->sh_entsize0
;
2392
2393
  // Some linkers e.g ld for arm, fill plt_hdr->sh_entsize field incorrectly.
2394
  // PLT entries relocation code in general requires multiple instruction and
2395
  // should be greater than 4 bytes in most cases. Try to guess correct size
2396
  // just in case.
2397
22
  if (plt_entsize <= 4) {
2398
    // The linker haven't set the plt_hdr->sh_entsize field. Try to guess the
2399
    // size of the plt entries based on the number of entries and the size of
2400
    // the plt section with the assumption that the size of the 0th entry is at
2401
    // least as big as the size of the normal entries and it isn't much bigger
2402
    // then that.
2403
3
    if (plt_hdr->sh_addralign)
2404
3
      plt_entsize = plt_hdr->sh_size / plt_hdr->sh_addralign /
2405
3
                    (num_relocations + 1) * plt_hdr->sh_addralign;
2406
0
    else
2407
0
      plt_entsize = plt_hdr->sh_size / (num_relocations + 1);
2408
3
  }
2409
2410
22
  elf_xword plt_offset = plt_hdr->sh_size - num_relocations * plt_entsize;
2411
2412
22
  return std::make_pair(plt_entsize, plt_offset);
2413
22
}
2414
2415
static unsigned ParsePLTRelocations(
2416
    Symtab *symbol_table, user_id_t start_id, unsigned rel_type,
2417
    const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2418
    const ELFSectionHeader *plt_hdr, const ELFSectionHeader *sym_hdr,
2419
    const lldb::SectionSP &plt_section_sp, DataExtractor &rel_data,
2420
22
    DataExtractor &symtab_data, DataExtractor &strtab_data) {
2421
22
  ELFRelocation rel(rel_type);
2422
22
  ELFSymbol symbol;
2423
22
  lldb::offset_t offset = 0;
2424
2425
22
  uint64_t plt_offset, plt_entsize;
2426
22
  std::tie(plt_entsize, plt_offset) =
2427
22
      GetPltEntrySizeAndOffset(rel_hdr, plt_hdr);
2428
22
  const elf_xword num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2429
2430
22
  typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2431
22
  reloc_info_fn reloc_type;
2432
22
  reloc_info_fn reloc_symbol;
2433
2434
22
  if (hdr->Is32Bit()) {
2435
0
    reloc_type = ELFRelocation::RelocType32;
2436
0
    reloc_symbol = ELFRelocation::RelocSymbol32;
2437
22
  } else {
2438
22
    reloc_type = ELFRelocation::RelocType64;
2439
22
    reloc_symbol = ELFRelocation::RelocSymbol64;
2440
22
  }
2441
2442
22
  unsigned slot_type = hdr->GetRelocationJumpSlotType();
2443
22
  unsigned i;
2444
123
  for (i = 0; i < num_relocations; 
++i101
) {
2445
101
    if (!rel.Parse(rel_data, &offset))
2446
0
      break;
2447
2448
101
    if (reloc_type(rel) != slot_type)
2449
0
      continue;
2450
2451
101
    lldb::offset_t symbol_offset = reloc_symbol(rel) * sym_hdr->sh_entsize;
2452
101
    if (!symbol.Parse(symtab_data, &symbol_offset))
2453
0
      break;
2454
2455
101
    const char *symbol_name = strtab_data.PeekCStr(symbol.st_name);
2456
101
    uint64_t plt_index = plt_offset + i * plt_entsize;
2457
2458
101
    Symbol jump_symbol(
2459
101
        i + start_id,          // Symbol table index
2460
101
        symbol_name,           // symbol name.
2461
101
        eSymbolTypeTrampoline, // Type of this symbol
2462
101
        false,                 // Is this globally visible?
2463
101
        false,                 // Is this symbol debug info?
2464
101
        true,                  // Is this symbol a trampoline?
2465
101
        true,                  // Is this symbol artificial?
2466
101
        plt_section_sp, // Section in which this symbol is defined or null.
2467
101
        plt_index,      // Offset in section or symbol value.
2468
101
        plt_entsize,    // Size in bytes of this symbol.
2469
101
        true,           // Size is valid
2470
101
        false,          // Contains linker annotations?
2471
101
        0);             // Symbol flags.
2472
2473
101
    symbol_table->AddSymbol(jump_symbol);
2474
101
  }
2475
2476
22
  return i;
2477
22
}
2478
2479
unsigned
2480
ObjectFileELF::ParseTrampolineSymbols(Symtab *symbol_table, user_id_t start_id,
2481
                                      const ELFSectionHeaderInfo *rel_hdr,
2482
22
                                      user_id_t rel_id) {
2483
22
  assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2484
2485
  // The link field points to the associated symbol table.
2486
0
  user_id_t symtab_id = rel_hdr->sh_link;
2487
2488
  // If the link field doesn't point to the appropriate symbol name table then
2489
  // try to find it by name as some compiler don't fill in the link fields.
2490
22
  if (!symtab_id)
2491
0
    symtab_id = GetSectionIndexByName(".dynsym");
2492
2493
  // Get PLT section.  We cannot use rel_hdr->sh_info, since current linkers
2494
  // point that to the .got.plt or .got section instead of .plt.
2495
22
  user_id_t plt_id = GetSectionIndexByName(".plt");
2496
2497
22
  if (!symtab_id || !plt_id)
2498
0
    return 0;
2499
2500
22
  const ELFSectionHeaderInfo *plt_hdr = GetSectionHeaderByIndex(plt_id);
2501
22
  if (!plt_hdr)
2502
0
    return 0;
2503
2504
22
  const ELFSectionHeaderInfo *sym_hdr = GetSectionHeaderByIndex(symtab_id);
2505
22
  if (!sym_hdr)
2506
0
    return 0;
2507
2508
22
  SectionList *section_list = m_sections_up.get();
2509
22
  if (!section_list)
2510
0
    return 0;
2511
2512
22
  Section *rel_section = section_list->FindSectionByID(rel_id).get();
2513
22
  if (!rel_section)
2514
0
    return 0;
2515
2516
22
  SectionSP plt_section_sp(section_list->FindSectionByID(plt_id));
2517
22
  if (!plt_section_sp)
2518
0
    return 0;
2519
2520
22
  Section *symtab = section_list->FindSectionByID(symtab_id).get();
2521
22
  if (!symtab)
2522
0
    return 0;
2523
2524
  // sh_link points to associated string table.
2525
22
  Section *strtab = section_list->FindSectionByID(sym_hdr->sh_link).get();
2526
22
  if (!strtab)
2527
0
    return 0;
2528
2529
22
  DataExtractor rel_data;
2530
22
  if (!ReadSectionData(rel_section, rel_data))
2531
0
    return 0;
2532
2533
22
  DataExtractor symtab_data;
2534
22
  if (!ReadSectionData(symtab, symtab_data))
2535
0
    return 0;
2536
2537
22
  DataExtractor strtab_data;
2538
22
  if (!ReadSectionData(strtab, strtab_data))
2539
0
    return 0;
2540
2541
22
  unsigned rel_type = PLTRelocationType();
2542
22
  if (!rel_type)
2543
0
    return 0;
2544
2545
22
  return ParsePLTRelocations(symbol_table, start_id, rel_type, &m_header,
2546
22
                             rel_hdr, plt_hdr, sym_hdr, plt_section_sp,
2547
22
                             rel_data, symtab_data, strtab_data);
2548
22
}
2549
2550
unsigned ObjectFileELF::ApplyRelocations(
2551
    Symtab *symtab, const ELFHeader *hdr, const ELFSectionHeader *rel_hdr,
2552
    const ELFSectionHeader *symtab_hdr, const ELFSectionHeader *debug_hdr,
2553
    DataExtractor &rel_data, DataExtractor &symtab_data,
2554
94
    DataExtractor &debug_data, Section *rel_section) {
2555
94
  ELFRelocation rel(rel_hdr->sh_type);
2556
94
  lldb::addr_t offset = 0;
2557
94
  const unsigned num_relocations = rel_hdr->sh_size / rel_hdr->sh_entsize;
2558
94
  typedef unsigned (*reloc_info_fn)(const ELFRelocation &rel);
2559
94
  reloc_info_fn reloc_type;
2560
94
  reloc_info_fn reloc_symbol;
2561
2562
94
  if (hdr->Is32Bit()) {
2563
0
    reloc_type = ELFRelocation::RelocType32;
2564
0
    reloc_symbol = ELFRelocation::RelocSymbol32;
2565
94
  } else {
2566
94
    reloc_type = ELFRelocation::RelocType64;
2567
94
    reloc_symbol = ELFRelocation::RelocSymbol64;
2568
94
  }
2569
2570
1.87k
  for (unsigned i = 0; i < num_relocations; 
++i1.78k
) {
2571
1.78k
    if (!rel.Parse(rel_data, &offset))
2572
0
      break;
2573
2574
1.78k
    Symbol *symbol = nullptr;
2575
2576
1.78k
    if (hdr->Is32Bit()) {
2577
0
      switch (reloc_type(rel)) {
2578
0
      case R_386_32:
2579
0
      case R_386_PC32:
2580
0
      default:
2581
        // FIXME: This asserts with this input:
2582
        //
2583
        // foo.cpp
2584
        // int main(int argc, char **argv) { return 0; }
2585
        //
2586
        // clang++.exe --target=i686-unknown-linux-gnu -g -c foo.cpp -o foo.o
2587
        //
2588
        // and running this on the foo.o module.
2589
0
        assert(false && "unexpected relocation type");
2590
0
      }
2591
1.78k
    } else {
2592
1.78k
      switch (reloc_type(rel)) {
2593
2
      case R_AARCH64_ABS64:
2594
411
      case R_X86_64_64: {
2595
411
        symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2596
411
        if (symbol) {
2597
411
          addr_t value = symbol->GetAddressRef().GetFileAddress();
2598
411
          DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2599
411
          uint64_t *dst = reinterpret_cast<uint64_t *>(
2600
411
              data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2601
411
              ELFRelocation::RelocOffset64(rel));
2602
411
          uint64_t val_offset = value + ELFRelocation::RelocAddend64(rel);
2603
411
          memcpy(dst, &val_offset, sizeof(uint64_t));
2604
411
        }
2605
411
        break;
2606
2
      }
2607
1.36k
      case R_X86_64_32:
2608
1.36k
      case R_X86_64_32S:
2609
1.37k
      case R_AARCH64_ABS32: {
2610
1.37k
        symbol = symtab->FindSymbolByID(reloc_symbol(rel));
2611
1.37k
        if (symbol) {
2612
1.37k
          addr_t value = symbol->GetAddressRef().GetFileAddress();
2613
1.37k
          value += ELFRelocation::RelocAddend32(rel);
2614
1.37k
          if ((reloc_type(rel) == R_X86_64_32 && 
(value > UINT32_MAX)1.36k
) ||
2615
1.37k
              (reloc_type(rel) == R_X86_64_32S &&
2616
1.37k
               
(0
(int64_t)value > INT32_MAX0
&&
(int64_t)value < INT32_MIN0
)) ||
2617
1.37k
              (reloc_type(rel) == R_AARCH64_ABS32 &&
2618
1.37k
               
(7
(int64_t)value > INT32_MAX7
&&
(int64_t)value < INT32_MIN0
))) {
2619
0
            Log *log =
2620
0
                lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_MODULES);
2621
0
            LLDB_LOGF(log, "Failed to apply debug info relocations");
2622
0
            break;
2623
0
          }
2624
1.37k
          uint32_t truncated_addr = (value & 0xFFFFFFFF);
2625
1.37k
          DataBufferSP &data_buffer_sp = debug_data.GetSharedDataBuffer();
2626
1.37k
          uint32_t *dst = reinterpret_cast<uint32_t *>(
2627
1.37k
              data_buffer_sp->GetBytes() + rel_section->GetFileOffset() +
2628
1.37k
              ELFRelocation::RelocOffset32(rel));
2629
1.37k
          memcpy(dst, &truncated_addr, sizeof(uint32_t));
2630
1.37k
        }
2631
1.37k
        break;
2632
1.37k
      }
2633
1.37k
      case R_X86_64_PC32:
2634
0
      default:
2635
0
        assert(false && "unexpected relocation type");
2636
1.78k
      }
2637
1.78k
    }
2638
1.78k
  }
2639
2640
94
  return 0;
2641
94
}
2642
2643
unsigned ObjectFileELF::RelocateDebugSections(const ELFSectionHeader *rel_hdr,
2644
                                              user_id_t rel_id,
2645
94
                                              lldb_private::Symtab *thetab) {
2646
94
  assert(rel_hdr->sh_type == SHT_RELA || rel_hdr->sh_type == SHT_REL);
2647
2648
  // Parse in the section list if needed.
2649
0
  SectionList *section_list = GetSectionList();
2650
94
  if (!section_list)
2651
0
    return 0;
2652
2653
94
  user_id_t symtab_id = rel_hdr->sh_link;
2654
94
  user_id_t debug_id = rel_hdr->sh_info;
2655
2656
94
  const ELFSectionHeader *symtab_hdr = GetSectionHeaderByIndex(symtab_id);
2657
94
  if (!symtab_hdr)
2658
0
    return 0;
2659
2660
94
  const ELFSectionHeader *debug_hdr = GetSectionHeaderByIndex(debug_id);
2661
94
  if (!debug_hdr)
2662
0
    return 0;
2663
2664
94
  Section *rel = section_list->FindSectionByID(rel_id).get();
2665
94
  if (!rel)
2666
0
    return 0;
2667
2668
94
  Section *symtab = section_list->FindSectionByID(symtab_id).get();
2669
94
  if (!symtab)
2670
0
    return 0;
2671
2672
94
  Section *debug = section_list->FindSectionByID(debug_id).get();
2673
94
  if (!debug)
2674
0
    return 0;
2675
2676
94
  DataExtractor rel_data;
2677
94
  DataExtractor symtab_data;
2678
94
  DataExtractor debug_data;
2679
2680
94
  if (GetData(rel->GetFileOffset(), rel->GetFileSize(), rel_data) &&
2681
94
      GetData(symtab->GetFileOffset(), symtab->GetFileSize(), symtab_data) &&
2682
94
      GetData(debug->GetFileOffset(), debug->GetFileSize(), debug_data)) {
2683
94
    ApplyRelocations(thetab, &m_header, rel_hdr, symtab_hdr, debug_hdr,
2684
94
                     rel_data, symtab_data, debug_data, debug);
2685
94
  }
2686
2687
94
  return 0;
2688
94
}
2689
2690
237
void ObjectFileELF::ParseSymtab(Symtab &lldb_symtab) {
2691
237
  ModuleSP module_sp(GetModule());
2692
237
  if (!module_sp)
2693
0
    return;
2694
2695
237
  Progress progress(
2696
237
      llvm::formatv("Parsing symbol table for {0}",
2697
237
                    m_file.GetFilename().AsCString("<Unknown>")));
2698
237
  ElapsedTime elapsed(module_sp->GetSymtabParseTime());
2699
2700
  // We always want to use the main object file so we (hopefully) only have one
2701
  // cached copy of our symtab, dynamic sections, etc.
2702
237
  ObjectFile *module_obj_file = module_sp->GetObjectFile();
2703
237
  if (module_obj_file && module_obj_file != this)
2704
6
    return module_obj_file->ParseSymtab(lldb_symtab);
2705
2706
231
  SectionList *section_list = module_sp->GetSectionList();
2707
231
  if (!section_list)
2708
0
    return;
2709
2710
231
  uint64_t symbol_id = 0;
2711
2712
  // Sharable objects and dynamic executables usually have 2 distinct symbol
2713
  // tables, one named ".symtab", and the other ".dynsym". The dynsym is a
2714
  // smaller version of the symtab that only contains global symbols. The
2715
  // information found in the dynsym is therefore also found in the symtab,
2716
  // while the reverse is not necessarily true.
2717
231
  Section *symtab =
2718
231
      section_list->FindSectionByType(eSectionTypeELFSymbolTable, true).get();
2719
231
  if (symtab)
2720
133
    symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, symtab);
2721
2722
  // The symtab section is non-allocable and can be stripped, while the
2723
  // .dynsym section which should always be always be there. To support the
2724
  // minidebuginfo case we parse .dynsym when there's a .gnu_debuginfo
2725
  // section, nomatter if .symtab was already parsed or not. This is because
2726
  // minidebuginfo normally removes the .symtab symbols which have their
2727
  // matching .dynsym counterparts.
2728
231
  if (!symtab ||
2729
231
      
GetSectionList()->FindSectionByName(ConstString(".gnu_debugdata"))133
) {
2730
99
    Section *dynsym =
2731
99
        section_list->FindSectionByType(eSectionTypeELFDynamicSymbols, true)
2732
99
            .get();
2733
99
    if (dynsym)
2734
11
      symbol_id += ParseSymbolTable(&lldb_symtab, symbol_id, dynsym);
2735
99
  }
2736
2737
  // DT_JMPREL
2738
  //      If present, this entry's d_ptr member holds the address of
2739
  //      relocation
2740
  //      entries associated solely with the procedure linkage table.
2741
  //      Separating
2742
  //      these relocation entries lets the dynamic linker ignore them during
2743
  //      process initialization, if lazy binding is enabled. If this entry is
2744
  //      present, the related entries of types DT_PLTRELSZ and DT_PLTREL must
2745
  //      also be present.
2746
231
  const ELFDynamic *symbol = FindDynamicSymbol(DT_JMPREL);
2747
231
  if (symbol) {
2748
    // Synthesize trampoline symbols to help navigate the PLT.
2749
24
    addr_t addr = symbol->d_ptr;
2750
24
    Section *reloc_section =
2751
24
        section_list->FindSectionContainingFileAddress(addr).get();
2752
24
    if (reloc_section) {
2753
24
      user_id_t reloc_id = reloc_section->GetID();
2754
24
      const ELFSectionHeaderInfo *reloc_header =
2755
24
          GetSectionHeaderByIndex(reloc_id);
2756
24
      if (reloc_header)
2757
22
        ParseTrampolineSymbols(&lldb_symtab, symbol_id, reloc_header, reloc_id);
2758
24
    }
2759
24
  }
2760
2761
231
  if (DWARFCallFrameInfo *eh_frame =
2762
231
          GetModule()->GetUnwindTable().GetEHFrameInfo()) {
2763
65
    ParseUnwindSymbols(&lldb_symtab, eh_frame);
2764
65
  }
2765
2766
  // In the event that there's no symbol entry for the entry point we'll
2767
  // artificially create one. We delegate to the symtab object the figuring
2768
  // out of the proper size, this will usually make it span til the next
2769
  // symbol it finds in the section. This means that if there are missing
2770
  // symbols the entry point might span beyond its function definition.
2771
  // We're fine with this as it doesn't make it worse than not having a
2772
  // symbol entry at all.
2773
231
  if (CalculateType() == eTypeExecutable) {
2774
130
    ArchSpec arch = GetArchitecture();
2775
130
    auto entry_point_addr = GetEntryPointAddress();
2776
130
    bool is_valid_entry_point =
2777
130
        entry_point_addr.IsValid() && entry_point_addr.IsSectionOffset();
2778
130
    addr_t entry_point_file_addr = entry_point_addr.GetFileAddress();
2779
130
    if (is_valid_entry_point && !lldb_symtab.FindSymbolContainingFileAddress(
2780
72
                                    entry_point_file_addr)) {
2781
28
      uint64_t symbol_id = lldb_symtab.GetNumSymbols();
2782
      // Don't set the name for any synthetic symbols, the Symbol
2783
      // object will generate one if needed when the name is accessed
2784
      // via accessors.
2785
28
      SectionSP section_sp = entry_point_addr.GetSection();
2786
28
      Symbol symbol(
2787
28
          /*symID=*/symbol_id,
2788
28
          /*name=*/llvm::StringRef(), // Name will be auto generated.
2789
28
          /*type=*/eSymbolTypeCode,
2790
28
          /*external=*/true,
2791
28
          /*is_debug=*/false,
2792
28
          /*is_trampoline=*/false,
2793
28
          /*is_artificial=*/true,
2794
28
          /*section_sp=*/section_sp,
2795
28
          /*offset=*/0,
2796
28
          /*size=*/0, // FDE can span multiple symbols so don't use its size.
2797
28
          /*size_is_valid=*/false,
2798
28
          /*contains_linker_annotations=*/false,
2799
28
          /*flags=*/0);
2800
      // When the entry point is arm thumb we need to explicitly set its
2801
      // class address to reflect that. This is important because expression
2802
      // evaluation relies on correctly setting a breakpoint at this
2803
      // address.
2804
28
      if (arch.GetMachine() == llvm::Triple::arm &&
2805
28
          
(entry_point_file_addr & 1)2
) {
2806
1
        symbol.GetAddressRef().SetOffset(entry_point_addr.GetOffset() ^ 1);
2807
1
        m_address_class_map[entry_point_file_addr ^ 1] =
2808
1
            AddressClass::eCodeAlternateISA;
2809
27
      } else {
2810
27
        m_address_class_map[entry_point_file_addr] = AddressClass::eCode;
2811
27
      }
2812
28
      lldb_symtab.AddSymbol(symbol);
2813
28
    }
2814
130
  }
2815
231
}
2816
2817
void ObjectFileELF::RelocateSection(lldb_private::Section *section)
2818
1.01k
{
2819
1.01k
  static const char *debug_prefix = ".debug";
2820
2821
  // Set relocated bit so we stop getting called, regardless of whether we
2822
  // actually relocate.
2823
1.01k
  section->SetIsRelocated(true);
2824
2825
  // We only relocate in ELF relocatable files
2826
1.01k
  if (CalculateType() != eTypeObjectFile)
2827
591
    return;
2828
2829
426
  const char *section_name = section->GetName().GetCString();
2830
  // Can't relocate that which can't be named
2831
426
  if (section_name == nullptr)
2832
0
    return;
2833
2834
  // We don't relocate non-debug sections at the moment
2835
426
  if (strncmp(section_name, debug_prefix, strlen(debug_prefix)))
2836
155
    return;
2837
2838
  // Relocation section names to look for
2839
271
  std::string needle = std::string(".rel") + section_name;
2840
271
  std::string needlea = std::string(".rela") + section_name;
2841
2842
271
  for (SectionHeaderCollIter I = m_section_headers.begin();
2843
2.95k
       I != m_section_headers.end(); 
++I2.67k
) {
2844
2.77k
    if (I->sh_type == SHT_RELA || 
I->sh_type == SHT_REL2.37k
) {
2845
396
      const char *hay_name = I->section_name.GetCString();
2846
396
      if (hay_name == nullptr)
2847
0
        continue;
2848
396
      if (needle == hay_name || needlea == hay_name) {
2849
94
        const ELFSectionHeader &reloc_header = *I;
2850
94
        user_id_t reloc_id = SectionIndex(I);
2851
94
        RelocateDebugSections(&reloc_header, reloc_id, GetSymtab());
2852
94
        break;
2853
94
      }
2854
396
    }
2855
2.77k
  }
2856
271
}
2857
2858
void ObjectFileELF::ParseUnwindSymbols(Symtab *symbol_table,
2859
65
                                       DWARFCallFrameInfo *eh_frame) {
2860
65
  SectionList *section_list = GetSectionList();
2861
65
  if (!section_list)
2862
0
    return;
2863
2864
  // First we save the new symbols into a separate list and add them to the
2865
  // symbol table after we collected all symbols we want to add. This is
2866
  // neccessary because adding a new symbol invalidates the internal index of
2867
  // the symtab what causing the next lookup to be slow because it have to
2868
  // recalculate the index first.
2869
65
  std::vector<Symbol> new_symbols;
2870
2871
65
  size_t num_symbols = symbol_table->GetNumSymbols();
2872
65
  uint64_t last_symbol_id =
2873
65
      num_symbols ? 
symbol_table->SymbolAtIndex(num_symbols - 1)->GetID()64
:
01
;
2874
65
  eh_frame->ForEachFDEEntries([&](lldb::addr_t file_addr, uint32_t size,
2875
204
                                  dw_offset_t) {
2876
204
    Symbol *symbol = symbol_table->FindSymbolAtFileAddress(file_addr);
2877
204
    if (symbol) {
2878
162
      if (!symbol->GetByteSizeIsValid()) {
2879
0
        symbol->SetByteSize(size);
2880
0
        symbol->SetSizeIsSynthesized(true);
2881
0
      }
2882
162
    } else {
2883
42
      SectionSP section_sp =
2884
42
          section_list->FindSectionContainingFileAddress(file_addr);
2885
42
      if (section_sp) {
2886
42
        addr_t offset = file_addr - section_sp->GetFileAddress();
2887
42
        uint64_t symbol_id = ++last_symbol_id;
2888
        // Don't set the name for any synthetic symbols, the Symbol
2889
        // object will generate one if needed when the name is accessed
2890
        // via accessors.
2891
42
        Symbol eh_symbol(
2892
42
            /*symID=*/symbol_id,
2893
42
            /*name=*/llvm::StringRef(), // Name will be auto generated.
2894
42
            /*type=*/eSymbolTypeCode,
2895
42
            /*external=*/true,
2896
42
            /*is_debug=*/false,
2897
42
            /*is_trampoline=*/false,
2898
42
            /*is_artificial=*/true,
2899
42
            /*section_sp=*/section_sp,
2900
42
            /*offset=*/offset,
2901
42
            /*size=*/0, // FDE can span multiple symbols so don't use its size.
2902
42
            /*size_is_valid=*/false,
2903
42
            /*contains_linker_annotations=*/false,
2904
42
            /*flags=*/0);
2905
42
        new_symbols.push_back(eh_symbol);
2906
42
      }
2907
42
    }
2908
204
    return true;
2909
204
  });
2910
2911
65
  for (const Symbol &s : new_symbols)
2912
42
    symbol_table->AddSymbol(s);
2913
65
}
2914
2915
238
bool ObjectFileELF::IsStripped() {
2916
  // TODO: determine this for ELF
2917
238
  return false;
2918
238
}
2919
2920
//===----------------------------------------------------------------------===//
2921
// Dump
2922
//
2923
// Dump the specifics of the runtime file container (such as any headers
2924
// segments, sections, etc).
2925
6
void ObjectFileELF::Dump(Stream *s) {
2926
6
  ModuleSP module_sp(GetModule());
2927
6
  if (!module_sp) {
2928
0
    return;
2929
0
  }
2930
2931
6
  std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
2932
6
  s->Printf("%p: ", static_cast<void *>(this));
2933
6
  s->Indent();
2934
6
  s->PutCString("ObjectFileELF");
2935
2936
6
  ArchSpec header_arch = GetArchitecture();
2937
2938
6
  *s << ", file = '" << m_file
2939
6
     << "', arch = " << header_arch.GetArchitectureName() << "\n";
2940
2941
6
  DumpELFHeader(s, m_header);
2942
6
  s->EOL();
2943
6
  DumpELFProgramHeaders(s);
2944
6
  s->EOL();
2945
6
  DumpELFSectionHeaders(s);
2946
6
  s->EOL();
2947
6
  SectionList *section_list = GetSectionList();
2948
6
  if (section_list)
2949
6
    section_list->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
2950
6
                       UINT32_MAX);
2951
6
  Symtab *symtab = GetSymtab();
2952
6
  if (symtab)
2953
6
    symtab->Dump(s, nullptr, eSortOrderNone);
2954
6
  s->EOL();
2955
6
  DumpDependentModules(s);
2956
6
  s->EOL();
2957
6
}
2958
2959
// DumpELFHeader
2960
//
2961
// Dump the ELF header to the specified output stream
2962
6
void ObjectFileELF::DumpELFHeader(Stream *s, const ELFHeader &header) {
2963
6
  s->PutCString("ELF Header\n");
2964
6
  s->Printf("e_ident[EI_MAG0   ] = 0x%2.2x\n", header.e_ident[EI_MAG0]);
2965
6
  s->Printf("e_ident[EI_MAG1   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG1],
2966
6
            header.e_ident[EI_MAG1]);
2967
6
  s->Printf("e_ident[EI_MAG2   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG2],
2968
6
            header.e_ident[EI_MAG2]);
2969
6
  s->Printf("e_ident[EI_MAG3   ] = 0x%2.2x '%c'\n", header.e_ident[EI_MAG3],
2970
6
            header.e_ident[EI_MAG3]);
2971
2972
6
  s->Printf("e_ident[EI_CLASS  ] = 0x%2.2x\n", header.e_ident[EI_CLASS]);
2973
6
  s->Printf("e_ident[EI_DATA   ] = 0x%2.2x ", header.e_ident[EI_DATA]);
2974
6
  DumpELFHeader_e_ident_EI_DATA(s, header.e_ident[EI_DATA]);
2975
6
  s->Printf("\ne_ident[EI_VERSION] = 0x%2.2x\n", header.e_ident[EI_VERSION]);
2976
6
  s->Printf("e_ident[EI_PAD    ] = 0x%2.2x\n", header.e_ident[EI_PAD]);
2977
2978
6
  s->Printf("e_type      = 0x%4.4x ", header.e_type);
2979
6
  DumpELFHeader_e_type(s, header.e_type);
2980
6
  s->Printf("\ne_machine   = 0x%4.4x\n", header.e_machine);
2981
6
  s->Printf("e_version   = 0x%8.8x\n", header.e_version);
2982
6
  s->Printf("e_entry     = 0x%8.8" PRIx64 "\n", header.e_entry);
2983
6
  s->Printf("e_phoff     = 0x%8.8" PRIx64 "\n", header.e_phoff);
2984
6
  s->Printf("e_shoff     = 0x%8.8" PRIx64 "\n", header.e_shoff);
2985
6
  s->Printf("e_flags     = 0x%8.8x\n", header.e_flags);
2986
6
  s->Printf("e_ehsize    = 0x%4.4x\n", header.e_ehsize);
2987
6
  s->Printf("e_phentsize = 0x%4.4x\n", header.e_phentsize);
2988
6
  s->Printf("e_phnum     = 0x%8.8x\n", header.e_phnum);
2989
6
  s->Printf("e_shentsize = 0x%4.4x\n", header.e_shentsize);
2990
6
  s->Printf("e_shnum     = 0x%8.8x\n", header.e_shnum);
2991
6
  s->Printf("e_shstrndx  = 0x%8.8x\n", header.e_shstrndx);
2992
6
}
2993
2994
// DumpELFHeader_e_type
2995
//
2996
// Dump an token value for the ELF header member e_type
2997
6
void ObjectFileELF::DumpELFHeader_e_type(Stream *s, elf_half e_type) {
2998
6
  switch (e_type) {
2999
0
  case ET_NONE:
3000
0
    *s << "ET_NONE";
3001
0
    break;
3002
4
  case ET_REL:
3003
4
    *s << "ET_REL";
3004
4
    break;
3005
1
  case ET_EXEC:
3006
1
    *s << "ET_EXEC";
3007
1
    break;
3008
1
  case ET_DYN:
3009
1
    *s << "ET_DYN";
3010
1
    break;
3011
0
  case ET_CORE:
3012
0
    *s << "ET_CORE";
3013
0
    break;
3014
0
  default:
3015
0
    break;
3016
6
  }
3017
6
}
3018
3019
// DumpELFHeader_e_ident_EI_DATA
3020
//
3021
// Dump an token value for the ELF header member e_ident[EI_DATA]
3022
void ObjectFileELF::DumpELFHeader_e_ident_EI_DATA(Stream *s,
3023
6
                                                  unsigned char ei_data) {
3024
6
  switch (ei_data) {
3025
0
  case ELFDATANONE:
3026
0
    *s << "ELFDATANONE";
3027
0
    break;
3028
6
  case ELFDATA2LSB:
3029
6
    *s << "ELFDATA2LSB - Little Endian";
3030
6
    break;
3031
0
  case ELFDATA2MSB:
3032
0
    *s << "ELFDATA2MSB - Big Endian";
3033
0
    break;
3034
0
  default:
3035
0
    break;
3036
6
  }
3037
6
}
3038
3039
// DumpELFProgramHeader
3040
//
3041
// Dump a single ELF program header to the specified output stream
3042
void ObjectFileELF::DumpELFProgramHeader(Stream *s,
3043
8
                                         const ELFProgramHeader &ph) {
3044
8
  DumpELFProgramHeader_p_type(s, ph.p_type);
3045
8
  s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, ph.p_offset,
3046
8
            ph.p_vaddr, ph.p_paddr);
3047
8
  s->Printf(" %8.8" PRIx64 " %8.8" PRIx64 " %8.8x (", ph.p_filesz, ph.p_memsz,
3048
8
            ph.p_flags);
3049
3050
8
  DumpELFProgramHeader_p_flags(s, ph.p_flags);
3051
8
  s->Printf(") %8.8" PRIx64, ph.p_align);
3052
8
}
3053
3054
// DumpELFProgramHeader_p_type
3055
//
3056
// Dump an token value for the ELF program header member p_type which describes
3057
// the type of the program header
3058
8
void ObjectFileELF::DumpELFProgramHeader_p_type(Stream *s, elf_word p_type) {
3059
8
  const int kStrWidth = 15;
3060
8
  switch (p_type) {
3061
0
    CASE_AND_STREAM(s, PT_NULL, kStrWidth);
3062
4
    CASE_AND_STREAM
(s, PT_LOAD, kStrWidth)0
;
3063
1
    CASE_AND_STREAM
(s, PT_DYNAMIC, kStrWidth)0
;
3064
0
    CASE_AND_STREAM(s, PT_INTERP, kStrWidth);
3065
0
    CASE_AND_STREAM(s, PT_NOTE, kStrWidth);
3066
0
    CASE_AND_STREAM(s, PT_SHLIB, kStrWidth);
3067
1
    CASE_AND_STREAM
(s, PT_PHDR, kStrWidth)0
;
3068
0
    CASE_AND_STREAM(s, PT_TLS, kStrWidth);
3069
0
    CASE_AND_STREAM(s, PT_GNU_EH_FRAME, kStrWidth);
3070
2
  default:
3071
2
    s->Printf("0x%8.8x%*s", p_type, kStrWidth - 10, "");
3072
2
    break;
3073
8
  }
3074
8
}
3075
3076
// DumpELFProgramHeader_p_flags
3077
//
3078
// Dump an token value for the ELF program header member p_flags
3079
8
void ObjectFileELF::DumpELFProgramHeader_p_flags(Stream *s, elf_word p_flags) {
3080
8
  *s << ((p_flags & PF_X) ? 
"PF_X"2
:
" "6
)
3081
8
     << (((p_flags & PF_X) && 
(p_flags & PF_W)2
) ?
'+'0
: ' ')
3082
8
     << ((p_flags & PF_W) ? 
"PF_W"3
:
" "5
)
3083
8
     << (((p_flags & PF_W) && 
(p_flags & PF_R)3
) ?
'+'3
:
' '5
)
3084
8
     << ((p_flags & PF_R) ? "PF_R" : 
" "0
);
3085
8
}
3086
3087
// DumpELFProgramHeaders
3088
//
3089
// Dump all of the ELF program header to the specified output stream
3090
6
void ObjectFileELF::DumpELFProgramHeaders(Stream *s) {
3091
6
  if (!ParseProgramHeaders())
3092
4
    return;
3093
3094
2
  s->PutCString("Program Headers\n");
3095
2
  s->PutCString("IDX  p_type          p_offset p_vaddr  p_paddr  "
3096
2
                "p_filesz p_memsz  p_flags                   p_align\n");
3097
2
  s->PutCString("==== --------------- -------- -------- -------- "
3098
2
                "-------- -------- ------------------------- --------\n");
3099
3100
8
  for (const auto &H : llvm::enumerate(m_program_headers)) {
3101
8
    s->Format("[{0,2}] ", H.index());
3102
8
    ObjectFileELF::DumpELFProgramHeader(s, H.value());
3103
8
    s->EOL();
3104
8
  }
3105
2
}
3106
3107
// DumpELFSectionHeader
3108
//
3109
// Dump a single ELF section header to the specified output stream
3110
void ObjectFileELF::DumpELFSectionHeader(Stream *s,
3111
62
                                         const ELFSectionHeaderInfo &sh) {
3112
62
  s->Printf("%8.8x ", sh.sh_name);
3113
62
  DumpELFSectionHeader_sh_type(s, sh.sh_type);
3114
62
  s->Printf(" %8.8" PRIx64 " (", sh.sh_flags);
3115
62
  DumpELFSectionHeader_sh_flags(s, sh.sh_flags);
3116
62
  s->Printf(") %8.8" PRIx64 " %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addr,
3117
62
            sh.sh_offset, sh.sh_size);
3118
62
  s->Printf(" %8.8x %8.8x", sh.sh_link, sh.sh_info);
3119
62
  s->Printf(" %8.8" PRIx64 " %8.8" PRIx64, sh.sh_addralign, sh.sh_entsize);
3120
62
}
3121
3122
// DumpELFSectionHeader_sh_type
3123
//
3124
// Dump an token value for the ELF section header member sh_type which
3125
// describes the type of the section
3126
62
void ObjectFileELF::DumpELFSectionHeader_sh_type(Stream *s, elf_word sh_type) {
3127
62
  const int kStrWidth = 12;
3128
62
  switch (sh_type) {
3129
6
    CASE_AND_STREAM
(s, SHT_NULL, kStrWidth)0
;
3130
29
    CASE_AND_STREAM
(s, SHT_PROGBITS, kStrWidth)0
;
3131
5
    CASE_AND_STREAM
(s, SHT_SYMTAB, kStrWidth)0
;
3132
9
    CASE_AND_STREAM
(s, SHT_STRTAB, kStrWidth)0
;
3133
8
    CASE_AND_STREAM
(s, SHT_RELA, kStrWidth)0
;
3134
1
    CASE_AND_STREAM
(s, SHT_HASH, kStrWidth)0
;
3135
1
    CASE_AND_STREAM
(s, SHT_DYNAMIC, kStrWidth)0
;
3136
0
    CASE_AND_STREAM(s, SHT_NOTE, kStrWidth);
3137
1
    CASE_AND_STREAM
(s, SHT_NOBITS, kStrWidth)0
;
3138
0
    CASE_AND_STREAM(s, SHT_REL, kStrWidth);
3139
0
    CASE_AND_STREAM(s, SHT_SHLIB, kStrWidth);
3140
1
    CASE_AND_STREAM
(s, SHT_DYNSYM, kStrWidth)0
;
3141
0
    CASE_AND_STREAM(s, SHT_LOPROC, kStrWidth);
3142
0
    CASE_AND_STREAM(s, SHT_HIPROC, kStrWidth);
3143
0
    CASE_AND_STREAM(s, SHT_LOUSER, kStrWidth);
3144
0
    CASE_AND_STREAM(s, SHT_HIUSER, kStrWidth);
3145
1
  default:
3146
1
    s->Printf("0x%8.8x%*s", sh_type, kStrWidth - 10, "");
3147
1
    break;
3148
62
  }
3149
62
}
3150
3151
// DumpELFSectionHeader_sh_flags
3152
//
3153
// Dump an token value for the ELF section header member sh_flags
3154
void ObjectFileELF::DumpELFSectionHeader_sh_flags(Stream *s,
3155
62
                                                  elf_xword sh_flags) {
3156
62
  *s << ((sh_flags & SHF_WRITE) ? 
"WRITE"5
:
" "57
)
3157
62
     << (((sh_flags & SHF_WRITE) && 
(sh_flags & SHF_ALLOC)5
) ?
'+'5
:
' '57
)
3158
62
     << ((sh_flags & SHF_ALLOC) ? 
"ALLOC"15
:
" "47
)
3159
62
     << (((sh_flags & SHF_ALLOC) && 
(sh_flags & SHF_EXECINSTR)15
) ?
'+'6
:
' '56
)
3160
62
     << ((sh_flags & SHF_EXECINSTR) ? 
"EXECINSTR"6
:
" "56
);
3161
62
}
3162
3163
// DumpELFSectionHeaders
3164
//
3165
// Dump all of the ELF section header to the specified output stream
3166
6
void ObjectFileELF::DumpELFSectionHeaders(Stream *s) {
3167
6
  if (!ParseSectionHeaders())
3168
0
    return;
3169
3170
6
  s->PutCString("Section Headers\n");
3171
6
  s->PutCString("IDX  name     type         flags                            "
3172
6
                "addr     offset   size     link     info     addralgn "
3173
6
                "entsize  Name\n");
3174
6
  s->PutCString("==== -------- ------------ -------------------------------- "
3175
6
                "-------- -------- -------- -------- -------- -------- "
3176
6
                "-------- ====================\n");
3177
3178
6
  uint32_t idx = 0;
3179
6
  for (SectionHeaderCollConstIter I = m_section_headers.begin();
3180
68
       I != m_section_headers.end(); 
++I, ++idx62
) {
3181
62
    s->Printf("[%2u] ", idx);
3182
62
    ObjectFileELF::DumpELFSectionHeader(s, *I);
3183
62
    const char *section_name = I->section_name.AsCString("");
3184
62
    if (section_name)
3185
62
      *s << ' ' << section_name << "\n";
3186
62
  }
3187
6
}
3188
3189
6
void ObjectFileELF::DumpDependentModules(lldb_private::Stream *s) {
3190
6
  size_t num_modules = ParseDependentModules();
3191
3192
6
  if (num_modules > 0) {
3193
0
    s->PutCString("Dependent Modules:\n");
3194
0
    for (unsigned i = 0; i < num_modules; ++i) {
3195
0
      const FileSpec &spec = m_filespec_up->GetFileSpecAtIndex(i);
3196
0
      s->Printf("   %s\n", spec.GetFilename().GetCString());
3197
0
    }
3198
0
  }
3199
6
}
3200
3201
1.30k
ArchSpec ObjectFileELF::GetArchitecture() {
3202
1.30k
  if (!ParseHeader())
3203
0
    return ArchSpec();
3204
3205
1.30k
  if (m_section_headers.empty()) {
3206
    // Allow elf notes to be parsed which may affect the detected architecture.
3207
688
    ParseSectionHeaders();
3208
688
  }
3209
3210
1.30k
  if (CalculateType() == eTypeCoreFile &&
3211
1.30k
      
!m_arch_spec.TripleOSWasSpecified()432
) {
3212
    // Core files don't have section headers yet they have PT_NOTE program
3213
    // headers that might shed more light on the architecture
3214
1.07k
    for (const elf::ELFProgramHeader &H : ProgramHeaders()) {
3215
1.07k
      if (H.p_type != PT_NOTE || 
H.p_offset == 041
||
H.p_filesz == 041
)
3216
1.03k
        continue;
3217
41
      DataExtractor data;
3218
41
      if (data.SetData(m_data, H.p_offset, H.p_filesz) == H.p_filesz) {
3219
41
        UUID uuid;
3220
41
        RefineModuleDetailsFromNote(data, m_arch_spec, uuid);
3221
41
      }
3222
41
    }
3223
41
  }
3224
1.30k
  return m_arch_spec;
3225
1.30k
}
3226
3227
4.62k
ObjectFile::Type ObjectFileELF::CalculateType() {
3228
4.62k
  switch (m_header.e_type) {
3229
0
  case llvm::ELF::ET_NONE:
3230
    // 0 - No file type
3231
0
    return eTypeUnknown;
3232
3233
1.44k
  case llvm::ELF::ET_REL:
3234
    // 1 - Relocatable file
3235
1.44k
    return eTypeObjectFile;
3236
3237
2.31k
  case llvm::ELF::ET_EXEC:
3238
    // 2 - Executable file
3239
2.31k
    return eTypeExecutable;
3240
3241
375
  case llvm::ELF::ET_DYN:
3242
    // 3 - Shared object file
3243
375
    return eTypeSharedLibrary;
3244
3245
486
  case ET_CORE:
3246
    // 4 - Core file
3247
486
    return eTypeCoreFile;
3248
3249
0
  default:
3250
0
    break;
3251
4.62k
  }
3252
0
  return eTypeUnknown;
3253
4.62k
}
3254
3255
69
ObjectFile::Strata ObjectFileELF::CalculateStrata() {
3256
69
  switch (m_header.e_type) {
3257
0
  case llvm::ELF::ET_NONE:
3258
    // 0 - No file type
3259
0
    return eStrataUnknown;
3260
3261
6
  case llvm::ELF::ET_REL:
3262
    // 1 - Relocatable file
3263
6
    return eStrataUnknown;
3264
3265
61
  case llvm::ELF::ET_EXEC:
3266
    // 2 - Executable file
3267
    // TODO: is there any way to detect that an executable is a kernel
3268
    // related executable by inspecting the program headers, section headers,
3269
    // symbols, or any other flag bits???
3270
61
    return eStrataUser;
3271
3272
1
  case llvm::ELF::ET_DYN:
3273
    // 3 - Shared object file
3274
    // TODO: is there any way to detect that an shared library is a kernel
3275
    // related executable by inspecting the program headers, section headers,
3276
    // symbols, or any other flag bits???
3277
1
    return eStrataUnknown;
3278
3279
1
  case ET_CORE:
3280
    // 4 - Core file
3281
    // TODO: is there any way to detect that an core file is a kernel
3282
    // related executable by inspecting the program headers, section headers,
3283
    // symbols, or any other flag bits???
3284
1
    return eStrataUnknown;
3285
3286
0
  default:
3287
0
    break;
3288
69
  }
3289
0
  return eStrataUnknown;
3290
69
}
3291
3292
size_t ObjectFileELF::ReadSectionData(Section *section,
3293
                       lldb::offset_t section_offset, void *dst,
3294
659
                       size_t dst_len) {
3295
  // If some other objectfile owns this data, pass this to them.
3296
659
  if (section->GetObjectFile() != this)
3297
0
    return section->GetObjectFile()->ReadSectionData(section, section_offset,
3298
0
                                                     dst, dst_len);
3299
3300
659
  if (!section->Test(SHF_COMPRESSED))
3301
659
    return ObjectFile::ReadSectionData(section, section_offset, dst, dst_len);
3302
3303
  // For compressed sections we need to read to full data to be able to
3304
  // decompress.
3305
0
  DataExtractor data;
3306
0
  ReadSectionData(section, data);
3307
0
  return data.CopyData(section_offset, dst_len, dst);
3308
659
}
3309
3310
size_t ObjectFileELF::ReadSectionData(Section *section,
3311
1.02k
                                      DataExtractor &section_data) {
3312
  // If some other objectfile owns this data, pass this to them.
3313
1.02k
  if (section->GetObjectFile() != this)
3314
0
    return section->GetObjectFile()->ReadSectionData(section, section_data);
3315
3316
1.02k
  size_t result = ObjectFile::ReadSectionData(section, section_data);
3317
1.02k
  if (result == 0 || !llvm::object::Decompressor::isCompressedELFSection(
3318
1.02k
                         section->Get(), section->GetName().GetStringRef()))
3319
1.02k
    return result;
3320
3321
6
  auto Decompressor = llvm::object::Decompressor::create(
3322
6
      section->GetName().GetStringRef(),
3323
6
      {reinterpret_cast<const char *>(section_data.GetDataStart()),
3324
6
       size_t(section_data.GetByteSize())},
3325
6
      GetByteOrder() == eByteOrderLittle, GetAddressByteSize() == 8);
3326
6
  if (!Decompressor) {
3327
1
    GetModule()->ReportWarning(
3328
1
        "Unable to initialize decompressor for section '%s': %s",
3329
1
        section->GetName().GetCString(),
3330
1
        llvm::toString(Decompressor.takeError()).c_str());
3331
1
    section_data.Clear();
3332
1
    return 0;
3333
1
  }
3334
3335
5
  auto buffer_sp =
3336
5
      std::make_shared<DataBufferHeap>(Decompressor->getDecompressedSize(), 0);
3337
5
  if (auto error = Decompressor->decompress(
3338
5
          {reinterpret_cast<char *>(buffer_sp->GetBytes()),
3339
5
           size_t(buffer_sp->GetByteSize())})) {
3340
0
    GetModule()->ReportWarning(
3341
0
        "Decompression of section '%s' failed: %s",
3342
0
        section->GetName().GetCString(),
3343
0
        llvm::toString(std::move(error)).c_str());
3344
0
    section_data.Clear();
3345
0
    return 0;
3346
0
  }
3347
3348
5
  section_data.SetData(buffer_sp);
3349
5
  return buffer_sp->GetByteSize();
3350
5
}
3351
3352
434
llvm::ArrayRef<ELFProgramHeader> ObjectFileELF::ProgramHeaders() {
3353
434
  ParseProgramHeaders();
3354
434
  return m_program_headers;
3355
434
}
3356
3357
1.31k
DataExtractor ObjectFileELF::GetSegmentData(const ELFProgramHeader &H) {
3358
1.31k
  return DataExtractor(m_data, H.p_offset, H.p_filesz);
3359
1.31k
}
3360
3361
2
bool ObjectFileELF::AnySegmentHasPhysicalAddress() {
3362
2
  for (const ELFProgramHeader &H : ProgramHeaders()) {
3363
2
    if (H.p_paddr != 0)
3364
2
      return true;
3365
2
  }
3366
0
  return false;
3367
2
}
3368
3369
std::vector<ObjectFile::LoadableData>
3370
2
ObjectFileELF::GetLoadableData(Target &target) {
3371
  // Create a list of loadable data from loadable segments, using physical
3372
  // addresses if they aren't all null
3373
2
  std::vector<LoadableData> loadables;
3374
2
  bool should_use_paddr = AnySegmentHasPhysicalAddress();
3375
4
  for (const ELFProgramHeader &H : ProgramHeaders()) {
3376
4
    LoadableData loadable;
3377
4
    if (H.p_type != llvm::ELF::PT_LOAD)
3378
0
      continue;
3379
4
    loadable.Dest = should_use_paddr ? H.p_paddr : 
H.p_vaddr0
;
3380
4
    if (loadable.Dest == LLDB_INVALID_ADDRESS)
3381
0
      continue;
3382
4
    if (H.p_filesz == 0)
3383
0
      continue;
3384
4
    auto segment_data = GetSegmentData(H);
3385
4
    loadable.Contents = llvm::ArrayRef<uint8_t>(segment_data.GetDataStart(),
3386
4
                                                segment_data.GetByteSize());
3387
4
    loadables.push_back(loadable);
3388
4
  }
3389
2
  return loadables;
3390
2
}