Coverage Report

Created: 2022-01-25 06:29

/Users/buildslave/jenkins/workspace/coverage/llvm-project/lldb/source/Plugins/ObjectFile/PECOFF/ObjectFilePECOFF.cpp
Line
Count
Source (jump to first uncovered line)
1
//===-- ObjectFilePECOFF.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 "ObjectFilePECOFF.h"
10
#include "PECallFrameInfo.h"
11
#include "WindowsMiniDump.h"
12
13
#include "lldb/Core/FileSpecList.h"
14
#include "lldb/Core/Module.h"
15
#include "lldb/Core/ModuleSpec.h"
16
#include "lldb/Core/PluginManager.h"
17
#include "lldb/Core/Section.h"
18
#include "lldb/Core/StreamFile.h"
19
#include "lldb/Symbol/ObjectFile.h"
20
#include "lldb/Target/Process.h"
21
#include "lldb/Target/SectionLoadList.h"
22
#include "lldb/Target/Target.h"
23
#include "lldb/Utility/ArchSpec.h"
24
#include "lldb/Utility/DataBufferHeap.h"
25
#include "lldb/Utility/FileSpec.h"
26
#include "lldb/Utility/Log.h"
27
#include "lldb/Utility/StreamString.h"
28
#include "lldb/Utility/Timer.h"
29
#include "lldb/Utility/UUID.h"
30
#include "llvm/BinaryFormat/COFF.h"
31
32
#include "llvm/Object/COFFImportFile.h"
33
#include "llvm/Support/Error.h"
34
#include "llvm/Support/MemoryBuffer.h"
35
36
2.96k
#define IMAGE_DOS_SIGNATURE 0x5A4D    // MZ
37
17
#define IMAGE_NT_SIGNATURE 0x00004550 // PE00
38
31
#define OPT_HEADER_MAGIC_PE32 0x010b
39
34
#define OPT_HEADER_MAGIC_PE32_PLUS 0x020b
40
41
using namespace lldb;
42
using namespace lldb_private;
43
44
LLDB_PLUGIN_DEFINE(ObjectFilePECOFF)
45
46
39
static UUID GetCoffUUID(llvm::object::COFFObjectFile &coff_obj) {
47
39
  const llvm::codeview::DebugInfo *pdb_info = nullptr;
48
39
  llvm::StringRef pdb_file;
49
50
39
  if (!coff_obj.getDebugPDBInfo(pdb_info, pdb_file) && pdb_info) {
51
7
    if (pdb_info->PDB70.CVSignature == llvm::OMF::Signature::PDB70) {
52
7
      UUID::CvRecordPdb70 info;
53
7
      memcpy(&info.Uuid, pdb_info->PDB70.Signature, sizeof(info.Uuid));
54
7
      info.Age = pdb_info->PDB70.Age;
55
7
      return UUID::fromCvRecord(info);
56
7
    }
57
7
  }
58
59
32
  return UUID();
60
39
}
61
62
char ObjectFilePECOFF::ID;
63
64
3.45k
void ObjectFilePECOFF::Initialize() {
65
3.45k
  PluginManager::RegisterPlugin(
66
3.45k
      GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance,
67
3.45k
      CreateMemoryInstance, GetModuleSpecifications, SaveCore);
68
3.45k
}
69
70
3.45k
void ObjectFilePECOFF::Terminate() {
71
3.45k
  PluginManager::UnregisterPlugin(CreateInstance);
72
3.45k
}
73
74
3.45k
llvm::StringRef ObjectFilePECOFF::GetPluginDescriptionStatic() {
75
3.45k
  return "Portable Executable and Common Object File Format object file reader "
76
3.45k
         "(32 and 64 bit)";
77
3.45k
}
78
79
ObjectFile *ObjectFilePECOFF::CreateInstance(const lldb::ModuleSP &module_sp,
80
                                             DataBufferSP &data_sp,
81
                                             lldb::offset_t data_offset,
82
                                             const lldb_private::FileSpec *file_p,
83
                                             lldb::offset_t file_offset,
84
230
                                             lldb::offset_t length) {
85
230
  FileSpec file = file_p ? *file_p : 
FileSpec()0
;
86
230
  if (!data_sp) {
87
0
    data_sp = MapFileData(file, length, file_offset);
88
0
    if (!data_sp)
89
0
      return nullptr;
90
0
    data_offset = 0;
91
0
  }
92
93
230
  if (!ObjectFilePECOFF::MagicBytesMatch(data_sp))
94
213
    return nullptr;
95
96
  // Update the data to contain the entire file if it doesn't already
97
17
  if (data_sp->GetByteSize() < length) {
98
11
    data_sp = MapFileData(file, length, file_offset);
99
11
    if (!data_sp)
100
0
      return nullptr;
101
11
  }
102
103
17
  auto objfile_up = std::make_unique<ObjectFilePECOFF>(
104
17
      module_sp, data_sp, data_offset, file_p, file_offset, length);
105
17
  if (!objfile_up || !objfile_up->ParseHeader())
106
0
    return nullptr;
107
108
  // Cache coff binary.
109
17
  if (!objfile_up->CreateBinary())
110
0
    return nullptr;
111
17
  return objfile_up.release();
112
17
}
113
114
ObjectFile *ObjectFilePECOFF::CreateMemoryInstance(
115
    const lldb::ModuleSP &module_sp, lldb::DataBufferSP &data_sp,
116
2
    const lldb::ProcessSP &process_sp, lldb::addr_t header_addr) {
117
2
  if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
118
2
    return nullptr;
119
0
  auto objfile_up = std::make_unique<ObjectFilePECOFF>(
120
0
      module_sp, data_sp, process_sp, header_addr);
121
0
  if (objfile_up.get() && objfile_up->ParseHeader()) {
122
0
    return objfile_up.release();
123
0
  }
124
0
  return nullptr;
125
0
}
126
127
size_t ObjectFilePECOFF::GetModuleSpecifications(
128
    const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
129
    lldb::offset_t data_offset, lldb::offset_t file_offset,
130
2.71k
    lldb::offset_t length, lldb_private::ModuleSpecList &specs) {
131
2.71k
  const size_t initial_count = specs.GetSize();
132
2.71k
  if (!data_sp || !ObjectFilePECOFF::MagicBytesMatch(data_sp))
133
2.67k
    return initial_count;
134
135
37
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
136
137
37
  if (data_sp->GetByteSize() < length)
138
23
    if (DataBufferSP full_sp = MapFileData(file, -1, file_offset))
139
23
      data_sp = std::move(full_sp);
140
37
  auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
141
37
      toStringRef(data_sp->GetData()), file.GetFilename().GetStringRef()));
142
143
37
  if (!binary) {
144
7
    LLDB_LOG_ERROR(log, binary.takeError(),
145
7
                   "Failed to create binary for file ({1}): {0}", file);
146
7
    return initial_count;
147
7
  }
148
149
30
  auto *COFFObj = llvm::dyn_cast<llvm::object::COFFObjectFile>(binary->get());
150
30
  if (!COFFObj)
151
0
    return initial_count;
152
153
30
  ModuleSpec module_spec(file);
154
30
  ArchSpec &spec = module_spec.GetArchitecture();
155
30
  lldb_private::UUID &uuid = module_spec.GetUUID();
156
30
  if (!uuid.IsValid())
157
30
    uuid = GetCoffUUID(*COFFObj);
158
159
30
  switch (COFFObj->getMachine()) {
160
14
  case MachineAmd64:
161
14
    spec.SetTriple("x86_64-pc-windows");
162
14
    specs.Append(module_spec);
163
14
    break;
164
11
  case MachineX86:
165
11
    spec.SetTriple("i386-pc-windows");
166
11
    specs.Append(module_spec);
167
11
    spec.SetTriple("i686-pc-windows");
168
11
    specs.Append(module_spec);
169
11
    break;
170
4
  case MachineArmNt:
171
4
    spec.SetTriple("armv7-pc-windows");
172
4
    specs.Append(module_spec);
173
4
    break;
174
1
  case MachineArm64:
175
1
    spec.SetTriple("aarch64-pc-windows");
176
1
    specs.Append(module_spec);
177
1
    break;
178
0
  default:
179
0
    break;
180
30
  }
181
182
30
  return specs.GetSize() - initial_count;
183
30
}
184
185
bool ObjectFilePECOFF::SaveCore(const lldb::ProcessSP &process_sp,
186
                                const lldb_private::FileSpec &outfile,
187
                                lldb::SaveCoreStyle &core_style,
188
0
                                lldb_private::Status &error) {
189
0
  core_style = eSaveCoreFull;
190
0
  return SaveMiniDump(process_sp, outfile, error);
191
0
}
192
193
2.94k
bool ObjectFilePECOFF::MagicBytesMatch(DataBufferSP &data_sp) {
194
2.94k
  DataExtractor data(data_sp, eByteOrderLittle, 4);
195
2.94k
  lldb::offset_t offset = 0;
196
2.94k
  uint16_t magic = data.GetU16(&offset);
197
2.94k
  return magic == IMAGE_DOS_SIGNATURE;
198
2.94k
}
199
200
10
lldb::SymbolType ObjectFilePECOFF::MapSymbolType(uint16_t coff_symbol_type) {
201
  // TODO:  We need to complete this mapping of COFF symbol types to LLDB ones.
202
  // For now, here's a hack to make sure our function have types.
203
10
  const auto complex_type =
204
10
      coff_symbol_type >> llvm::COFF::SCT_COMPLEX_TYPE_SHIFT;
205
10
  if (complex_type == llvm::COFF::IMAGE_SYM_DTYPE_FUNCTION) {
206
4
    return lldb::eSymbolTypeCode;
207
4
  }
208
6
  return lldb::eSymbolTypeInvalid;
209
10
}
210
211
29
bool ObjectFilePECOFF::CreateBinary() {
212
29
  if (m_binary)
213
12
    return true;
214
215
17
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
216
217
17
  auto binary = llvm::object::createBinary(llvm::MemoryBufferRef(
218
17
      toStringRef(m_data.GetData()), m_file.GetFilename().GetStringRef()));
219
17
  if (!binary) {
220
0
    LLDB_LOG_ERROR(log, binary.takeError(),
221
0
                   "Failed to create binary for file ({1}): {0}", m_file);
222
0
    return false;
223
0
  }
224
225
  // Make sure we only handle COFF format.
226
17
  m_binary =
227
17
      llvm::unique_dyn_cast<llvm::object::COFFObjectFile>(std::move(*binary));
228
17
  if (!m_binary)
229
0
    return false;
230
231
17
  LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
232
17
           this, GetModule().get(), GetModule()->GetSpecificationDescription(),
233
17
           m_file.GetPath(), m_binary.get());
234
17
  return true;
235
17
}
236
237
ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
238
                                   DataBufferSP &data_sp,
239
                                   lldb::offset_t data_offset,
240
                                   const FileSpec *file,
241
                                   lldb::offset_t file_offset,
242
                                   lldb::offset_t length)
243
    : ObjectFile(module_sp, file, file_offset, length, data_sp, data_offset),
244
      m_dos_header(), m_coff_header(), m_sect_headers(),
245
17
      m_entry_point_address(), m_deps_filespec() {
246
17
  ::memset(&m_dos_header, 0, sizeof(m_dos_header));
247
17
  ::memset(&m_coff_header, 0, sizeof(m_coff_header));
248
17
}
249
250
ObjectFilePECOFF::ObjectFilePECOFF(const lldb::ModuleSP &module_sp,
251
                                   DataBufferSP &header_data_sp,
252
                                   const lldb::ProcessSP &process_sp,
253
                                   addr_t header_addr)
254
    : ObjectFile(module_sp, process_sp, header_addr, header_data_sp),
255
      m_dos_header(), m_coff_header(), m_sect_headers(),
256
0
      m_entry_point_address(), m_deps_filespec() {
257
0
  ::memset(&m_dos_header, 0, sizeof(m_dos_header));
258
0
  ::memset(&m_coff_header, 0, sizeof(m_coff_header));
259
0
}
260
261
12
ObjectFilePECOFF::~ObjectFilePECOFF() = default;
262
263
17
bool ObjectFilePECOFF::ParseHeader() {
264
17
  ModuleSP module_sp(GetModule());
265
17
  if (module_sp) {
266
17
    std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
267
17
    m_sect_headers.clear();
268
17
    m_data.SetByteOrder(eByteOrderLittle);
269
17
    lldb::offset_t offset = 0;
270
271
17
    if (ParseDOSHeader(m_data, m_dos_header)) {
272
17
      offset = m_dos_header.e_lfanew;
273
17
      uint32_t pe_signature = m_data.GetU32(&offset);
274
17
      if (pe_signature != IMAGE_NT_SIGNATURE)
275
0
        return false;
276
17
      if (ParseCOFFHeader(m_data, &offset, m_coff_header)) {
277
17
        if (m_coff_header.hdrsize > 0)
278
17
          ParseCOFFOptionalHeader(&offset);
279
17
        ParseSectionHeaders(offset);
280
17
      }
281
17
      m_data.SetAddressByteSize(GetAddressByteSize());
282
17
      return true;
283
17
    }
284
17
  }
285
0
  return false;
286
17
}
287
288
bool ObjectFilePECOFF::SetLoadAddress(Target &target, addr_t value,
289
4
                                      bool value_is_offset) {
290
4
  bool changed = false;
291
4
  ModuleSP module_sp = GetModule();
292
4
  if (module_sp) {
293
4
    size_t num_loaded_sections = 0;
294
4
    SectionList *section_list = GetSectionList();
295
4
    if (section_list) {
296
4
      if (!value_is_offset) {
297
4
        value -= m_image_base;
298
4
      }
299
300
4
      const size_t num_sections = section_list->GetSize();
301
4
      size_t sect_idx = 0;
302
303
15
      for (sect_idx = 0; sect_idx < num_sections; 
++sect_idx11
) {
304
        // Iterate through the object file sections to find all of the sections
305
        // that have SHF_ALLOC in their flag bits.
306
11
        SectionSP section_sp(section_list->GetSectionAtIndex(sect_idx));
307
11
        if (section_sp && !section_sp->IsThreadSpecific()) {
308
11
          if (target.GetSectionLoadList().SetSectionLoadAddress(
309
11
                  section_sp, section_sp->GetFileAddress() + value))
310
11
            ++num_loaded_sections;
311
11
        }
312
11
      }
313
4
      changed = num_loaded_sections > 0;
314
4
    }
315
4
  }
316
4
  return changed;
317
4
}
318
319
0
ByteOrder ObjectFilePECOFF::GetByteOrder() const { return eByteOrderLittle; }
320
321
24
bool ObjectFilePECOFF::IsExecutable() const {
322
24
  return (m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0;
323
24
}
324
325
34
uint32_t ObjectFilePECOFF::GetAddressByteSize() const {
326
34
  if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32_PLUS)
327
20
    return 8;
328
14
  else if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32)
329
14
    return 4;
330
0
  return 4;
331
34
}
332
333
// NeedsEndianSwap
334
//
335
// Return true if an endian swap needs to occur when extracting data from this
336
// file.
337
0
bool ObjectFilePECOFF::NeedsEndianSwap() const {
338
0
#if defined(__LITTLE_ENDIAN__)
339
0
  return false;
340
#else
341
  return true;
342
#endif
343
0
}
344
// ParseDOSHeader
345
bool ObjectFilePECOFF::ParseDOSHeader(DataExtractor &data,
346
17
                                      dos_header_t &dos_header) {
347
17
  bool success = false;
348
17
  lldb::offset_t offset = 0;
349
17
  success = data.ValidOffsetForDataOfSize(0, sizeof(dos_header));
350
351
17
  if (success) {
352
17
    dos_header.e_magic = data.GetU16(&offset); // Magic number
353
17
    success = dos_header.e_magic == IMAGE_DOS_SIGNATURE;
354
355
17
    if (success) {
356
17
      dos_header.e_cblp = data.GetU16(&offset); // Bytes on last page of file
357
17
      dos_header.e_cp = data.GetU16(&offset);   // Pages in file
358
17
      dos_header.e_crlc = data.GetU16(&offset); // Relocations
359
17
      dos_header.e_cparhdr =
360
17
          data.GetU16(&offset); // Size of header in paragraphs
361
17
      dos_header.e_minalloc =
362
17
          data.GetU16(&offset); // Minimum extra paragraphs needed
363
17
      dos_header.e_maxalloc =
364
17
          data.GetU16(&offset);               // Maximum extra paragraphs needed
365
17
      dos_header.e_ss = data.GetU16(&offset); // Initial (relative) SS value
366
17
      dos_header.e_sp = data.GetU16(&offset); // Initial SP value
367
17
      dos_header.e_csum = data.GetU16(&offset); // Checksum
368
17
      dos_header.e_ip = data.GetU16(&offset);   // Initial IP value
369
17
      dos_header.e_cs = data.GetU16(&offset);   // Initial (relative) CS value
370
17
      dos_header.e_lfarlc =
371
17
          data.GetU16(&offset); // File address of relocation table
372
17
      dos_header.e_ovno = data.GetU16(&offset); // Overlay number
373
374
17
      dos_header.e_res[0] = data.GetU16(&offset); // Reserved words
375
17
      dos_header.e_res[1] = data.GetU16(&offset); // Reserved words
376
17
      dos_header.e_res[2] = data.GetU16(&offset); // Reserved words
377
17
      dos_header.e_res[3] = data.GetU16(&offset); // Reserved words
378
379
17
      dos_header.e_oemid =
380
17
          data.GetU16(&offset); // OEM identifier (for e_oeminfo)
381
17
      dos_header.e_oeminfo =
382
17
          data.GetU16(&offset); // OEM information; e_oemid specific
383
17
      dos_header.e_res2[0] = data.GetU16(&offset); // Reserved words
384
17
      dos_header.e_res2[1] = data.GetU16(&offset); // Reserved words
385
17
      dos_header.e_res2[2] = data.GetU16(&offset); // Reserved words
386
17
      dos_header.e_res2[3] = data.GetU16(&offset); // Reserved words
387
17
      dos_header.e_res2[4] = data.GetU16(&offset); // Reserved words
388
17
      dos_header.e_res2[5] = data.GetU16(&offset); // Reserved words
389
17
      dos_header.e_res2[6] = data.GetU16(&offset); // Reserved words
390
17
      dos_header.e_res2[7] = data.GetU16(&offset); // Reserved words
391
17
      dos_header.e_res2[8] = data.GetU16(&offset); // Reserved words
392
17
      dos_header.e_res2[9] = data.GetU16(&offset); // Reserved words
393
394
17
      dos_header.e_lfanew =
395
17
          data.GetU32(&offset); // File address of new exe header
396
17
    }
397
17
  }
398
17
  if (!success)
399
0
    memset(&dos_header, 0, sizeof(dos_header));
400
17
  return success;
401
17
}
402
403
// ParserCOFFHeader
404
bool ObjectFilePECOFF::ParseCOFFHeader(DataExtractor &data,
405
                                       lldb::offset_t *offset_ptr,
406
17
                                       coff_header_t &coff_header) {
407
17
  bool success =
408
17
      data.ValidOffsetForDataOfSize(*offset_ptr, sizeof(coff_header));
409
17
  if (success) {
410
17
    coff_header.machine = data.GetU16(offset_ptr);
411
17
    coff_header.nsects = data.GetU16(offset_ptr);
412
17
    coff_header.modtime = data.GetU32(offset_ptr);
413
17
    coff_header.symoff = data.GetU32(offset_ptr);
414
17
    coff_header.nsyms = data.GetU32(offset_ptr);
415
17
    coff_header.hdrsize = data.GetU16(offset_ptr);
416
17
    coff_header.flags = data.GetU16(offset_ptr);
417
17
  }
418
17
  if (!success)
419
0
    memset(&coff_header, 0, sizeof(coff_header));
420
17
  return success;
421
17
}
422
423
17
bool ObjectFilePECOFF::ParseCOFFOptionalHeader(lldb::offset_t *offset_ptr) {
424
17
  bool success = false;
425
17
  const lldb::offset_t end_offset = *offset_ptr + m_coff_header.hdrsize;
426
17
  if (*offset_ptr < end_offset) {
427
17
    success = true;
428
17
    m_coff_header_opt.magic = m_data.GetU16(offset_ptr);
429
17
    m_coff_header_opt.major_linker_version = m_data.GetU8(offset_ptr);
430
17
    m_coff_header_opt.minor_linker_version = m_data.GetU8(offset_ptr);
431
17
    m_coff_header_opt.code_size = m_data.GetU32(offset_ptr);
432
17
    m_coff_header_opt.data_size = m_data.GetU32(offset_ptr);
433
17
    m_coff_header_opt.bss_size = m_data.GetU32(offset_ptr);
434
17
    m_coff_header_opt.entry = m_data.GetU32(offset_ptr);
435
17
    m_coff_header_opt.code_offset = m_data.GetU32(offset_ptr);
436
437
17
    const uint32_t addr_byte_size = GetAddressByteSize();
438
439
17
    if (*offset_ptr < end_offset) {
440
17
      if (m_coff_header_opt.magic == OPT_HEADER_MAGIC_PE32) {
441
        // PE32 only
442
7
        m_coff_header_opt.data_offset = m_data.GetU32(offset_ptr);
443
7
      } else
444
10
        m_coff_header_opt.data_offset = 0;
445
446
17
      if (*offset_ptr < end_offset) {
447
17
        m_coff_header_opt.image_base =
448
17
            m_data.GetMaxU64(offset_ptr, addr_byte_size);
449
17
        m_coff_header_opt.sect_alignment = m_data.GetU32(offset_ptr);
450
17
        m_coff_header_opt.file_alignment = m_data.GetU32(offset_ptr);
451
17
        m_coff_header_opt.major_os_system_version = m_data.GetU16(offset_ptr);
452
17
        m_coff_header_opt.minor_os_system_version = m_data.GetU16(offset_ptr);
453
17
        m_coff_header_opt.major_image_version = m_data.GetU16(offset_ptr);
454
17
        m_coff_header_opt.minor_image_version = m_data.GetU16(offset_ptr);
455
17
        m_coff_header_opt.major_subsystem_version = m_data.GetU16(offset_ptr);
456
17
        m_coff_header_opt.minor_subsystem_version = m_data.GetU16(offset_ptr);
457
17
        m_coff_header_opt.reserved1 = m_data.GetU32(offset_ptr);
458
17
        m_coff_header_opt.image_size = m_data.GetU32(offset_ptr);
459
17
        m_coff_header_opt.header_size = m_data.GetU32(offset_ptr);
460
17
        m_coff_header_opt.checksum = m_data.GetU32(offset_ptr);
461
17
        m_coff_header_opt.subsystem = m_data.GetU16(offset_ptr);
462
17
        m_coff_header_opt.dll_flags = m_data.GetU16(offset_ptr);
463
17
        m_coff_header_opt.stack_reserve_size =
464
17
            m_data.GetMaxU64(offset_ptr, addr_byte_size);
465
17
        m_coff_header_opt.stack_commit_size =
466
17
            m_data.GetMaxU64(offset_ptr, addr_byte_size);
467
17
        m_coff_header_opt.heap_reserve_size =
468
17
            m_data.GetMaxU64(offset_ptr, addr_byte_size);
469
17
        m_coff_header_opt.heap_commit_size =
470
17
            m_data.GetMaxU64(offset_ptr, addr_byte_size);
471
17
        m_coff_header_opt.loader_flags = m_data.GetU32(offset_ptr);
472
17
        uint32_t num_data_dir_entries = m_data.GetU32(offset_ptr);
473
17
        m_coff_header_opt.data_dirs.clear();
474
17
        m_coff_header_opt.data_dirs.resize(num_data_dir_entries);
475
17
        uint32_t i;
476
289
        for (i = 0; i < num_data_dir_entries; 
i++272
) {
477
272
          m_coff_header_opt.data_dirs[i].vmaddr = m_data.GetU32(offset_ptr);
478
272
          m_coff_header_opt.data_dirs[i].vmsize = m_data.GetU32(offset_ptr);
479
272
        }
480
481
17
        m_image_base = m_coff_header_opt.image_base;
482
17
      }
483
17
    }
484
17
  }
485
  // Make sure we are on track for section data which follows
486
17
  *offset_ptr = end_offset;
487
17
  return success;
488
17
}
489
490
3
uint32_t ObjectFilePECOFF::GetRVA(const Address &addr) const {
491
3
  return addr.GetFileAddress() - m_image_base;
492
3
}
493
494
15
Address ObjectFilePECOFF::GetAddress(uint32_t rva) {
495
15
  SectionList *sect_list = GetSectionList();
496
15
  if (!sect_list)
497
0
    return Address(GetFileAddress(rva));
498
499
15
  return Address(GetFileAddress(rva), sect_list);
500
15
}
501
502
15
lldb::addr_t ObjectFilePECOFF::GetFileAddress(uint32_t rva) const {
503
15
  return m_image_base + rva;
504
15
}
505
506
35
DataExtractor ObjectFilePECOFF::ReadImageData(uint32_t offset, size_t size) {
507
35
  if (!size)
508
0
    return {};
509
510
35
  if (m_data.ValidOffsetForDataOfSize(offset, size))
511
35
    return DataExtractor(m_data, offset, size);
512
513
0
  ProcessSP process_sp(m_process_wp.lock());
514
0
  DataExtractor data;
515
0
  if (process_sp) {
516
0
    auto data_up = std::make_unique<DataBufferHeap>(size, 0);
517
0
    Status readmem_error;
518
0
    size_t bytes_read =
519
0
        process_sp->ReadMemory(m_image_base + offset, data_up->GetBytes(),
520
0
                               data_up->GetByteSize(), readmem_error);
521
0
    if (bytes_read == size) {
522
0
      DataBufferSP buffer_sp(data_up.release());
523
0
      data.SetData(buffer_sp, 0, buffer_sp->GetByteSize());
524
0
    }
525
0
  }
526
0
  return data;
527
35
}
528
529
12
DataExtractor ObjectFilePECOFF::ReadImageDataByRVA(uint32_t rva, size_t size) {
530
12
  Address addr = GetAddress(rva);
531
12
  SectionSP sect = addr.GetSection();
532
12
  if (!sect)
533
0
    return {};
534
12
  rva = sect->GetFileOffset() + addr.GetOffset();
535
536
12
  return ReadImageData(rva, size);
537
12
}
538
539
// ParseSectionHeaders
540
bool ObjectFilePECOFF::ParseSectionHeaders(
541
17
    uint32_t section_header_data_offset) {
542
17
  const uint32_t nsects = m_coff_header.nsects;
543
17
  m_sect_headers.clear();
544
545
17
  if (nsects > 0) {
546
17
    const size_t section_header_byte_size = nsects * sizeof(section_header_t);
547
17
    DataExtractor section_header_data =
548
17
        ReadImageData(section_header_data_offset, section_header_byte_size);
549
550
17
    lldb::offset_t offset = 0;
551
17
    if (section_header_data.ValidOffsetForDataOfSize(
552
17
            offset, section_header_byte_size)) {
553
17
      m_sect_headers.resize(nsects);
554
555
58
      for (uint32_t idx = 0; idx < nsects; 
++idx41
) {
556
41
        const void *name_data = section_header_data.GetData(&offset, 8);
557
41
        if (name_data) {
558
41
          memcpy(m_sect_headers[idx].name, name_data, 8);
559
41
          m_sect_headers[idx].vmsize = section_header_data.GetU32(&offset);
560
41
          m_sect_headers[idx].vmaddr = section_header_data.GetU32(&offset);
561
41
          m_sect_headers[idx].size = section_header_data.GetU32(&offset);
562
41
          m_sect_headers[idx].offset = section_header_data.GetU32(&offset);
563
41
          m_sect_headers[idx].reloff = section_header_data.GetU32(&offset);
564
41
          m_sect_headers[idx].lineoff = section_header_data.GetU32(&offset);
565
41
          m_sect_headers[idx].nreloc = section_header_data.GetU16(&offset);
566
41
          m_sect_headers[idx].nline = section_header_data.GetU16(&offset);
567
41
          m_sect_headers[idx].flags = section_header_data.GetU32(&offset);
568
41
        }
569
41
      }
570
17
    }
571
17
  }
572
573
17
  return !m_sect_headers.empty();
574
17
}
575
576
44
llvm::StringRef ObjectFilePECOFF::GetSectionName(const section_header_t &sect) {
577
44
  llvm::StringRef hdr_name(sect.name, llvm::array_lengthof(sect.name));
578
44
  hdr_name = hdr_name.split('\0').first;
579
44
  if (hdr_name.consume_front("/")) {
580
8
    lldb::offset_t stroff;
581
8
    if (!to_integer(hdr_name, stroff, 10))
582
0
      return "";
583
8
    lldb::offset_t string_file_offset =
584
8
        m_coff_header.symoff + (m_coff_header.nsyms * 18) + stroff;
585
8
    if (const char *name = m_data.GetCStr(&string_file_offset))
586
8
      return name;
587
0
    return "";
588
8
  }
589
36
  return hdr_name;
590
44
}
591
592
12
void ObjectFilePECOFF::ParseSymtab(Symtab &symtab) {
593
12
  SectionList *sect_list = GetSectionList();
594
12
  const uint32_t num_syms = m_coff_header.nsyms;
595
12
  if (m_file && num_syms > 0 && 
m_coff_header.symoff > 03
) {
596
3
    const uint32_t symbol_size = 18;
597
3
    const size_t symbol_data_size = num_syms * symbol_size;
598
    // Include the 4-byte string table size at the end of the symbols
599
3
    DataExtractor symtab_data =
600
3
        ReadImageData(m_coff_header.symoff, symbol_data_size + 4);
601
3
    lldb::offset_t offset = symbol_data_size;
602
3
    const uint32_t strtab_size = symtab_data.GetU32(&offset);
603
3
    if (strtab_size > 0) {
604
3
      DataExtractor strtab_data = ReadImageData(
605
3
          m_coff_header.symoff + symbol_data_size, strtab_size);
606
607
3
      offset = 0;
608
3
      std::string symbol_name;
609
3
      Symbol *symbols = symtab.Resize(num_syms);
610
14
      for (uint32_t i = 0; i < num_syms; 
++i11
) {
611
11
        coff_symbol_t symbol;
612
11
        const uint32_t symbol_offset = offset;
613
11
        const char *symbol_name_cstr = nullptr;
614
        // If the first 4 bytes of the symbol string are zero, then they
615
        // are followed by a 4-byte string table offset. Else these
616
        // 8 bytes contain the symbol name
617
11
        if (symtab_data.GetU32(&offset) == 0) {
618
          // Long string that doesn't fit into the symbol table name, so
619
          // now we must read the 4 byte string table offset
620
0
          uint32_t strtab_offset = symtab_data.GetU32(&offset);
621
0
          symbol_name_cstr = strtab_data.PeekCStr(strtab_offset);
622
0
          symbol_name.assign(symbol_name_cstr);
623
11
        } else {
624
          // Short string that fits into the symbol table name which is 8
625
          // bytes
626
11
          offset += sizeof(symbol.name) - 4; // Skip remaining
627
11
          symbol_name_cstr = symtab_data.PeekCStr(symbol_offset);
628
11
          if (symbol_name_cstr == nullptr)
629
0
            break;
630
11
          symbol_name.assign(symbol_name_cstr, sizeof(symbol.name));
631
11
        }
632
11
        symbol.value = symtab_data.GetU32(&offset);
633
11
        symbol.sect = symtab_data.GetU16(&offset);
634
11
        symbol.type = symtab_data.GetU16(&offset);
635
11
        symbol.storage = symtab_data.GetU8(&offset);
636
11
        symbol.naux = symtab_data.GetU8(&offset);
637
11
        symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
638
11
        if ((int16_t)symbol.sect >= 1) {
639
10
          Address symbol_addr(sect_list->FindSectionByID(symbol.sect),
640
10
                              symbol.value);
641
10
          symbols[i].GetAddressRef() = symbol_addr;
642
10
          symbols[i].SetType(MapSymbolType(symbol.type));
643
10
        }
644
645
11
        if (symbol.naux > 0) {
646
1
          i += symbol.naux;
647
1
          offset += symbol.naux * symbol_size;
648
1
        }
649
11
      }
650
3
    }
651
3
  }
652
653
  // Read export header
654
12
  if (coff_data_dir_export_table < m_coff_header_opt.data_dirs.size() &&
655
12
      m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmsize > 0 &&
656
12
      
m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr > 00
) {
657
0
    export_directory_entry export_table;
658
0
    uint32_t data_start =
659
0
        m_coff_header_opt.data_dirs[coff_data_dir_export_table].vmaddr;
660
661
0
    DataExtractor symtab_data = ReadImageDataByRVA(
662
0
        data_start, m_coff_header_opt.data_dirs[0].vmsize);
663
0
    lldb::offset_t offset = 0;
664
665
    // Read export_table header
666
0
    export_table.characteristics = symtab_data.GetU32(&offset);
667
0
    export_table.time_date_stamp = symtab_data.GetU32(&offset);
668
0
    export_table.major_version = symtab_data.GetU16(&offset);
669
0
    export_table.minor_version = symtab_data.GetU16(&offset);
670
0
    export_table.name = symtab_data.GetU32(&offset);
671
0
    export_table.base = symtab_data.GetU32(&offset);
672
0
    export_table.number_of_functions = symtab_data.GetU32(&offset);
673
0
    export_table.number_of_names = symtab_data.GetU32(&offset);
674
0
    export_table.address_of_functions = symtab_data.GetU32(&offset);
675
0
    export_table.address_of_names = symtab_data.GetU32(&offset);
676
0
    export_table.address_of_name_ordinals = symtab_data.GetU32(&offset);
677
678
0
    bool has_ordinal = export_table.address_of_name_ordinals != 0;
679
680
0
    lldb::offset_t name_offset = export_table.address_of_names - data_start;
681
0
    lldb::offset_t name_ordinal_offset =
682
0
        export_table.address_of_name_ordinals - data_start;
683
684
0
    Symbol *symbols = symtab.Resize(export_table.number_of_names);
685
686
0
    std::string symbol_name;
687
688
    // Read each export table entry
689
0
    for (size_t i = 0; i < export_table.number_of_names; ++i) {
690
0
      uint32_t name_ordinal =
691
0
          has_ordinal ? symtab_data.GetU16(&name_ordinal_offset) : i;
692
0
      uint32_t name_address = symtab_data.GetU32(&name_offset);
693
694
0
      const char *symbol_name_cstr =
695
0
          symtab_data.PeekCStr(name_address - data_start);
696
0
      symbol_name.assign(symbol_name_cstr);
697
698
0
      lldb::offset_t function_offset = export_table.address_of_functions -
699
0
                                        data_start +
700
0
                                        sizeof(uint32_t) * name_ordinal;
701
0
      uint32_t function_rva = symtab_data.GetU32(&function_offset);
702
703
0
      Address symbol_addr(m_coff_header_opt.image_base + function_rva,
704
0
                          sect_list);
705
0
      symbols[i].GetMangled().SetValue(ConstString(symbol_name.c_str()));
706
0
      symbols[i].GetAddressRef() = symbol_addr;
707
0
      symbols[i].SetType(lldb::eSymbolTypeCode);
708
0
      symbols[i].SetDebug(true);
709
0
    }
710
0
  }
711
12
}
712
713
5
std::unique_ptr<CallFrameInfo> ObjectFilePECOFF::CreateCallFrameInfo() {
714
5
  if (coff_data_dir_exception_table >= m_coff_header_opt.data_dirs.size())
715
0
    return {};
716
717
5
  data_directory data_dir_exception =
718
5
      m_coff_header_opt.data_dirs[coff_data_dir_exception_table];
719
5
  if (!data_dir_exception.vmaddr)
720
2
    return {};
721
722
3
  if (m_coff_header.machine != llvm::COFF::IMAGE_FILE_MACHINE_AMD64)
723
0
    return {};
724
725
3
  return std::make_unique<PECallFrameInfo>(*this, data_dir_exception.vmaddr,
726
3
                                           data_dir_exception.vmsize);
727
3
}
728
729
18
bool ObjectFilePECOFF::IsStripped() {
730
  // TODO: determine this for COFF
731
18
  return false;
732
18
}
733
734
SectionType ObjectFilePECOFF::GetSectionType(llvm::StringRef sect_name,
735
40
                                             const section_header_t &sect) {
736
40
  ConstString const_sect_name(sect_name);
737
40
  static ConstString g_code_sect_name(".code");
738
40
  static ConstString g_CODE_sect_name("CODE");
739
40
  static ConstString g_data_sect_name(".data");
740
40
  static ConstString g_DATA_sect_name("DATA");
741
40
  static ConstString g_bss_sect_name(".bss");
742
40
  static ConstString g_BSS_sect_name("BSS");
743
744
40
  if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE &&
745
40
      
(14
(const_sect_name == g_code_sect_name)14
||
746
14
       (const_sect_name == g_CODE_sect_name))) {
747
0
    return eSectionTypeCode;
748
0
  }
749
40
  if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA &&
750
40
             
(26
(const_sect_name == g_data_sect_name)26
||
751
26
              
(const_sect_name == g_DATA_sect_name)24
)) {
752
2
    if (sect.size == 0 && 
sect.offset == 01
)
753
1
      return eSectionTypeZeroFill;
754
1
    else
755
1
      return eSectionTypeData;
756
2
  }
757
38
  if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA &&
758
38
             
(0
(const_sect_name == g_bss_sect_name)0
||
759
0
              (const_sect_name == g_BSS_sect_name))) {
760
0
    if (sect.size == 0)
761
0
      return eSectionTypeZeroFill;
762
0
    else
763
0
      return eSectionTypeData;
764
0
  }
765
766
38
  SectionType section_type =
767
38
      llvm::StringSwitch<SectionType>(sect_name)
768
38
          .Case(".debug", eSectionTypeDebug)
769
38
          .Case(".stabstr", eSectionTypeDataCString)
770
38
          .Case(".reloc", eSectionTypeOther)
771
38
          .Case(".debug_abbrev", eSectionTypeDWARFDebugAbbrev)
772
38
          .Case(".debug_aranges", eSectionTypeDWARFDebugAranges)
773
38
          .Case(".debug_frame", eSectionTypeDWARFDebugFrame)
774
38
          .Case(".debug_info", eSectionTypeDWARFDebugInfo)
775
38
          .Case(".debug_line", eSectionTypeDWARFDebugLine)
776
38
          .Case(".debug_loc", eSectionTypeDWARFDebugLoc)
777
38
          .Case(".debug_loclists", eSectionTypeDWARFDebugLocLists)
778
38
          .Case(".debug_macinfo", eSectionTypeDWARFDebugMacInfo)
779
38
          .Case(".debug_names", eSectionTypeDWARFDebugNames)
780
38
          .Case(".debug_pubnames", eSectionTypeDWARFDebugPubNames)
781
38
          .Case(".debug_pubtypes", eSectionTypeDWARFDebugPubTypes)
782
38
          .Case(".debug_ranges", eSectionTypeDWARFDebugRanges)
783
38
          .Case(".debug_str", eSectionTypeDWARFDebugStr)
784
38
          .Case(".debug_types", eSectionTypeDWARFDebugTypes)
785
          // .eh_frame can be truncated to 8 chars.
786
38
          .Cases(".eh_frame", ".eh_fram", eSectionTypeEHFrame)
787
38
          .Case(".gosymtab", eSectionTypeGoSymtab)
788
38
          .Default(eSectionTypeInvalid);
789
38
  if (section_type != eSectionTypeInvalid)
790
12
    return section_type;
791
792
26
  if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_CODE)
793
14
    return eSectionTypeCode;
794
12
  if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
795
12
    return eSectionTypeData;
796
0
  if (sect.flags & llvm::COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA) {
797
0
    if (sect.size == 0)
798
0
      return eSectionTypeZeroFill;
799
0
    else
800
0
      return eSectionTypeData;
801
0
  }
802
0
  return eSectionTypeOther;
803
0
}
804
805
16
void ObjectFilePECOFF::CreateSections(SectionList &unified_section_list) {
806
16
  if (m_sections_up)
807
0
    return;
808
16
  m_sections_up = std::make_unique<SectionList>();
809
16
  ModuleSP module_sp(GetModule());
810
16
  if (module_sp) {
811
16
    std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
812
813
16
    SectionSP header_sp = std::make_shared<Section>(
814
16
        module_sp, this, ~user_id_t(0), ConstString("PECOFF header"),
815
16
        eSectionTypeOther, m_coff_header_opt.image_base,
816
16
        m_coff_header_opt.header_size,
817
16
        /*file_offset*/ 0, m_coff_header_opt.header_size,
818
16
        m_coff_header_opt.sect_alignment,
819
16
        /*flags*/ 0);
820
16
    header_sp->SetPermissions(ePermissionsReadable);
821
16
    m_sections_up->AddSection(header_sp);
822
16
    unified_section_list.AddSection(header_sp);
823
824
16
    const uint32_t nsects = m_sect_headers.size();
825
16
    ModuleSP module_sp(GetModule());
826
56
    for (uint32_t idx = 0; idx < nsects; 
++idx40
) {
827
40
      llvm::StringRef sect_name = GetSectionName(m_sect_headers[idx]);
828
40
      ConstString const_sect_name(sect_name);
829
40
      SectionType section_type = GetSectionType(sect_name, m_sect_headers[idx]);
830
831
40
      SectionSP section_sp(new Section(
832
40
          module_sp,       // Module to which this section belongs
833
40
          this,            // Object file to which this section belongs
834
40
          idx + 1,         // Section ID is the 1 based section index.
835
40
          const_sect_name, // Name of this section
836
40
          section_type,
837
40
          m_coff_header_opt.image_base +
838
40
              m_sect_headers[idx].vmaddr, // File VM address == addresses as
839
                                          // they are found in the object file
840
40
          m_sect_headers[idx].vmsize,     // VM size in bytes of this section
841
40
          m_sect_headers[idx]
842
40
              .offset, // Offset to the data for this section in the file
843
40
          m_sect_headers[idx]
844
40
              .size, // Size in bytes of this section as found in the file
845
40
          m_coff_header_opt.sect_alignment, // Section alignment
846
40
          m_sect_headers[idx].flags));      // Flags for this section
847
848
40
      uint32_t permissions = 0;
849
40
      if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_EXECUTE)
850
14
        permissions |= ePermissionsExecutable;
851
40
      if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_READ)
852
40
        permissions |= ePermissionsReadable;
853
40
      if (m_sect_headers[idx].flags & llvm::COFF::IMAGE_SCN_MEM_WRITE)
854
1
        permissions |= ePermissionsWritable;
855
40
      section_sp->SetPermissions(permissions);
856
857
40
      m_sections_up->AddSection(section_sp);
858
40
      unified_section_list.AddSection(section_sp);
859
40
    }
860
16
  }
861
16
}
862
863
9
UUID ObjectFilePECOFF::GetUUID() {
864
9
  if (m_uuid.IsValid())
865
0
    return m_uuid;
866
867
9
  if (!CreateBinary())
868
0
    return UUID();
869
870
9
  m_uuid = GetCoffUUID(*m_binary);
871
9
  return m_uuid;
872
9
}
873
874
3
uint32_t ObjectFilePECOFF::ParseDependentModules() {
875
3
  ModuleSP module_sp(GetModule());
876
3
  if (!module_sp)
877
0
    return 0;
878
879
3
  std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
880
3
  if (m_deps_filespec)
881
0
    return m_deps_filespec->GetSize();
882
883
  // Cache coff binary if it is not done yet.
884
3
  if (!CreateBinary())
885
0
    return 0;
886
887
3
  Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
888
3
  LLDB_LOG(log, "this = {0}, module = {1} ({2}), file = {3}, binary = {4}",
889
3
           this, GetModule().get(), GetModule()->GetSpecificationDescription(),
890
3
           m_file.GetPath(), m_binary.get());
891
892
3
  m_deps_filespec = FileSpecList();
893
894
3
  for (const auto &entry : m_binary->import_directories()) {
895
0
    llvm::StringRef dll_name;
896
    // Report a bogus entry.
897
0
    if (llvm::Error e = entry.getName(dll_name)) {
898
0
      LLDB_LOGF(log,
899
0
                "ObjectFilePECOFF::ParseDependentModules() - failed to get "
900
0
                "import directory entry name: %s",
901
0
                llvm::toString(std::move(e)).c_str());
902
0
      continue;
903
0
    }
904
905
    // At this moment we only have the base name of the DLL. The full path can
906
    // only be seen after the dynamic loading.  Our best guess is Try to get it
907
    // with the help of the object file's directory.
908
0
    llvm::SmallString<128> dll_fullpath;
909
0
    FileSpec dll_specs(dll_name);
910
0
    dll_specs.GetDirectory().SetString(m_file.GetDirectory().GetCString());
911
912
0
    if (!llvm::sys::fs::real_path(dll_specs.GetPath(), dll_fullpath))
913
0
      m_deps_filespec->EmplaceBack(dll_fullpath);
914
0
    else {
915
      // Known DLLs or DLL not found in the object file directory.
916
0
      m_deps_filespec->EmplaceBack(dll_name);
917
0
    }
918
0
  }
919
3
  return m_deps_filespec->GetSize();
920
3
}
921
922
1
uint32_t ObjectFilePECOFF::GetDependentModules(FileSpecList &files) {
923
1
  auto num_modules = ParseDependentModules();
924
1
  auto original_size = files.GetSize();
925
926
1
  for (unsigned i = 0; i < num_modules; 
++i0
)
927
0
    files.AppendIfUnique(m_deps_filespec->GetFileSpecAtIndex(i));
928
929
1
  return files.GetSize() - original_size;
930
1
}
931
932
0
lldb_private::Address ObjectFilePECOFF::GetEntryPointAddress() {
933
0
  if (m_entry_point_address.IsValid())
934
0
    return m_entry_point_address;
935
936
0
  if (!ParseHeader() || !IsExecutable())
937
0
    return m_entry_point_address;
938
939
0
  SectionList *section_list = GetSectionList();
940
0
  addr_t file_addr = m_coff_header_opt.entry + m_coff_header_opt.image_base;
941
942
0
  if (!section_list)
943
0
    m_entry_point_address.SetOffset(file_addr);
944
0
  else
945
0
    m_entry_point_address.ResolveAddressUsingFileSections(file_addr,
946
0
                                                          section_list);
947
0
  return m_entry_point_address;
948
0
}
949
950
12
Address ObjectFilePECOFF::GetBaseAddress() {
951
12
  return Address(GetSectionList()->GetSectionAtIndex(0), 0);
952
12
}
953
954
// Dump
955
//
956
// Dump the specifics of the runtime file container (such as any headers
957
// segments, sections, etc).
958
2
void ObjectFilePECOFF::Dump(Stream *s) {
959
2
  ModuleSP module_sp(GetModule());
960
2
  if (module_sp) {
961
2
    std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
962
2
    s->Printf("%p: ", static_cast<void *>(this));
963
2
    s->Indent();
964
2
    s->PutCString("ObjectFilePECOFF");
965
966
2
    ArchSpec header_arch = GetArchitecture();
967
968
2
    *s << ", file = '" << m_file
969
2
       << "', arch = " << header_arch.GetArchitectureName() << "\n";
970
971
2
    SectionList *sections = GetSectionList();
972
2
    if (sections)
973
2
      sections->Dump(s->AsRawOstream(), s->GetIndentLevel(), nullptr, true,
974
2
                     UINT32_MAX);
975
976
2
    if (m_symtab_up)
977
2
      m_symtab_up->Dump(s, nullptr, eSortOrderNone);
978
979
2
    if (m_dos_header.e_magic)
980
2
      DumpDOSHeader(s, m_dos_header);
981
2
    if (m_coff_header.machine) {
982
2
      DumpCOFFHeader(s, m_coff_header);
983
2
      if (m_coff_header.hdrsize)
984
2
        DumpOptCOFFHeader(s, m_coff_header_opt);
985
2
    }
986
2
    s->EOL();
987
2
    DumpSectionHeaders(s);
988
2
    s->EOL();
989
990
2
    DumpDependentModules(s);
991
2
    s->EOL();
992
2
  }
993
2
}
994
995
// DumpDOSHeader
996
//
997
// Dump the MS-DOS header to the specified output stream
998
2
void ObjectFilePECOFF::DumpDOSHeader(Stream *s, const dos_header_t &header) {
999
2
  s->PutCString("MSDOS Header\n");
1000
2
  s->Printf("  e_magic    = 0x%4.4x\n", header.e_magic);
1001
2
  s->Printf("  e_cblp     = 0x%4.4x\n", header.e_cblp);
1002
2
  s->Printf("  e_cp       = 0x%4.4x\n", header.e_cp);
1003
2
  s->Printf("  e_crlc     = 0x%4.4x\n", header.e_crlc);
1004
2
  s->Printf("  e_cparhdr  = 0x%4.4x\n", header.e_cparhdr);
1005
2
  s->Printf("  e_minalloc = 0x%4.4x\n", header.e_minalloc);
1006
2
  s->Printf("  e_maxalloc = 0x%4.4x\n", header.e_maxalloc);
1007
2
  s->Printf("  e_ss       = 0x%4.4x\n", header.e_ss);
1008
2
  s->Printf("  e_sp       = 0x%4.4x\n", header.e_sp);
1009
2
  s->Printf("  e_csum     = 0x%4.4x\n", header.e_csum);
1010
2
  s->Printf("  e_ip       = 0x%4.4x\n", header.e_ip);
1011
2
  s->Printf("  e_cs       = 0x%4.4x\n", header.e_cs);
1012
2
  s->Printf("  e_lfarlc   = 0x%4.4x\n", header.e_lfarlc);
1013
2
  s->Printf("  e_ovno     = 0x%4.4x\n", header.e_ovno);
1014
2
  s->Printf("  e_res[4]   = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1015
2
            header.e_res[0], header.e_res[1], header.e_res[2], header.e_res[3]);
1016
2
  s->Printf("  e_oemid    = 0x%4.4x\n", header.e_oemid);
1017
2
  s->Printf("  e_oeminfo  = 0x%4.4x\n", header.e_oeminfo);
1018
2
  s->Printf("  e_res2[10] = { 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, "
1019
2
            "0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x, 0x%4.4x }\n",
1020
2
            header.e_res2[0], header.e_res2[1], header.e_res2[2],
1021
2
            header.e_res2[3], header.e_res2[4], header.e_res2[5],
1022
2
            header.e_res2[6], header.e_res2[7], header.e_res2[8],
1023
2
            header.e_res2[9]);
1024
2
  s->Printf("  e_lfanew   = 0x%8.8x\n", header.e_lfanew);
1025
2
}
1026
1027
// DumpCOFFHeader
1028
//
1029
// Dump the COFF header to the specified output stream
1030
2
void ObjectFilePECOFF::DumpCOFFHeader(Stream *s, const coff_header_t &header) {
1031
2
  s->PutCString("COFF Header\n");
1032
2
  s->Printf("  machine = 0x%4.4x\n", header.machine);
1033
2
  s->Printf("  nsects  = 0x%4.4x\n", header.nsects);
1034
2
  s->Printf("  modtime = 0x%8.8x\n", header.modtime);
1035
2
  s->Printf("  symoff  = 0x%8.8x\n", header.symoff);
1036
2
  s->Printf("  nsyms   = 0x%8.8x\n", header.nsyms);
1037
2
  s->Printf("  hdrsize = 0x%4.4x\n", header.hdrsize);
1038
2
}
1039
1040
// DumpOptCOFFHeader
1041
//
1042
// Dump the optional COFF header to the specified output stream
1043
void ObjectFilePECOFF::DumpOptCOFFHeader(Stream *s,
1044
2
                                         const coff_opt_header_t &header) {
1045
2
  s->PutCString("Optional COFF Header\n");
1046
2
  s->Printf("  magic                   = 0x%4.4x\n", header.magic);
1047
2
  s->Printf("  major_linker_version    = 0x%2.2x\n",
1048
2
            header.major_linker_version);
1049
2
  s->Printf("  minor_linker_version    = 0x%2.2x\n",
1050
2
            header.minor_linker_version);
1051
2
  s->Printf("  code_size               = 0x%8.8x\n", header.code_size);
1052
2
  s->Printf("  data_size               = 0x%8.8x\n", header.data_size);
1053
2
  s->Printf("  bss_size                = 0x%8.8x\n", header.bss_size);
1054
2
  s->Printf("  entry                   = 0x%8.8x\n", header.entry);
1055
2
  s->Printf("  code_offset             = 0x%8.8x\n", header.code_offset);
1056
2
  s->Printf("  data_offset             = 0x%8.8x\n", header.data_offset);
1057
2
  s->Printf("  image_base              = 0x%16.16" PRIx64 "\n",
1058
2
            header.image_base);
1059
2
  s->Printf("  sect_alignment          = 0x%8.8x\n", header.sect_alignment);
1060
2
  s->Printf("  file_alignment          = 0x%8.8x\n", header.file_alignment);
1061
2
  s->Printf("  major_os_system_version = 0x%4.4x\n",
1062
2
            header.major_os_system_version);
1063
2
  s->Printf("  minor_os_system_version = 0x%4.4x\n",
1064
2
            header.minor_os_system_version);
1065
2
  s->Printf("  major_image_version     = 0x%4.4x\n",
1066
2
            header.major_image_version);
1067
2
  s->Printf("  minor_image_version     = 0x%4.4x\n",
1068
2
            header.minor_image_version);
1069
2
  s->Printf("  major_subsystem_version = 0x%4.4x\n",
1070
2
            header.major_subsystem_version);
1071
2
  s->Printf("  minor_subsystem_version = 0x%4.4x\n",
1072
2
            header.minor_subsystem_version);
1073
2
  s->Printf("  reserved1               = 0x%8.8x\n", header.reserved1);
1074
2
  s->Printf("  image_size              = 0x%8.8x\n", header.image_size);
1075
2
  s->Printf("  header_size             = 0x%8.8x\n", header.header_size);
1076
2
  s->Printf("  checksum                = 0x%8.8x\n", header.checksum);
1077
2
  s->Printf("  subsystem               = 0x%4.4x\n", header.subsystem);
1078
2
  s->Printf("  dll_flags               = 0x%4.4x\n", header.dll_flags);
1079
2
  s->Printf("  stack_reserve_size      = 0x%16.16" PRIx64 "\n",
1080
2
            header.stack_reserve_size);
1081
2
  s->Printf("  stack_commit_size       = 0x%16.16" PRIx64 "\n",
1082
2
            header.stack_commit_size);
1083
2
  s->Printf("  heap_reserve_size       = 0x%16.16" PRIx64 "\n",
1084
2
            header.heap_reserve_size);
1085
2
  s->Printf("  heap_commit_size        = 0x%16.16" PRIx64 "\n",
1086
2
            header.heap_commit_size);
1087
2
  s->Printf("  loader_flags            = 0x%8.8x\n", header.loader_flags);
1088
2
  s->Printf("  num_data_dir_entries    = 0x%8.8x\n",
1089
2
            (uint32_t)header.data_dirs.size());
1090
2
  uint32_t i;
1091
34
  for (i = 0; i < header.data_dirs.size(); 
i++32
) {
1092
32
    s->Printf("  data_dirs[%2u] vmaddr = 0x%8.8x, vmsize = 0x%8.8x\n", i,
1093
32
              header.data_dirs[i].vmaddr, header.data_dirs[i].vmsize);
1094
32
  }
1095
2
}
1096
// DumpSectionHeader
1097
//
1098
// Dump a single ELF section header to the specified output stream
1099
void ObjectFilePECOFF::DumpSectionHeader(Stream *s,
1100
4
                                         const section_header_t &sh) {
1101
4
  std::string name = std::string(GetSectionName(sh));
1102
4
  s->Printf("%-16s 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%8.8x 0x%4.4x "
1103
4
            "0x%4.4x 0x%8.8x\n",
1104
4
            name.c_str(), sh.vmaddr, sh.vmsize, sh.offset, sh.size, sh.reloff,
1105
4
            sh.lineoff, sh.nreloc, sh.nline, sh.flags);
1106
4
}
1107
1108
// DumpSectionHeaders
1109
//
1110
// Dump all of the ELF section header to the specified output stream
1111
2
void ObjectFilePECOFF::DumpSectionHeaders(Stream *s) {
1112
1113
2
  s->PutCString("Section Headers\n");
1114
2
  s->PutCString("IDX  name             vm addr    vm size    file off   file "
1115
2
                "size  reloc off  line off   nreloc nline  flags\n");
1116
2
  s->PutCString("==== ---------------- ---------- ---------- ---------- "
1117
2
                "---------- ---------- ---------- ------ ------ ----------\n");
1118
1119
2
  uint32_t idx = 0;
1120
2
  SectionHeaderCollIter pos, end = m_sect_headers.end();
1121
1122
6
  for (pos = m_sect_headers.begin(); pos != end; 
++pos, ++idx4
) {
1123
4
    s->Printf("[%2u] ", idx);
1124
4
    ObjectFilePECOFF::DumpSectionHeader(s, *pos);
1125
4
  }
1126
2
}
1127
1128
// DumpDependentModules
1129
//
1130
// Dump all of the dependent modules to the specified output stream
1131
2
void ObjectFilePECOFF::DumpDependentModules(lldb_private::Stream *s) {
1132
2
  auto num_modules = ParseDependentModules();
1133
2
  if (num_modules > 0) {
1134
0
    s->PutCString("Dependent Modules\n");
1135
0
    for (unsigned i = 0; i < num_modules; ++i) {
1136
0
      auto spec = m_deps_filespec->GetFileSpecAtIndex(i);
1137
0
      s->Printf("  %s\n", spec.GetFilename().GetCString());
1138
0
    }
1139
0
  }
1140
2
}
1141
1142
19
bool ObjectFilePECOFF::IsWindowsSubsystem() {
1143
19
  switch (m_coff_header_opt.subsystem) {
1144
0
  case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE:
1145
1
  case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI:
1146
19
  case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI:
1147
19
  case llvm::COFF::IMAGE_SUBSYSTEM_NATIVE_WINDOWS:
1148
19
  case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CE_GUI:
1149
19
  case llvm::COFF::IMAGE_SUBSYSTEM_XBOX:
1150
19
  case llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION:
1151
19
    return true;
1152
0
  default:
1153
0
    return false;
1154
19
  }
1155
19
}
1156
1157
19
ArchSpec ObjectFilePECOFF::GetArchitecture() {
1158
19
  uint16_t machine = m_coff_header.machine;
1159
19
  switch (machine) {
1160
0
  default:
1161
0
    break;
1162
10
  case llvm::COFF::IMAGE_FILE_MACHINE_AMD64:
1163
15
  case llvm::COFF::IMAGE_FILE_MACHINE_I386:
1164
15
  case llvm::COFF::IMAGE_FILE_MACHINE_POWERPC:
1165
15
  case llvm::COFF::IMAGE_FILE_MACHINE_POWERPCFP:
1166
15
  case llvm::COFF::IMAGE_FILE_MACHINE_ARM:
1167
18
  case llvm::COFF::IMAGE_FILE_MACHINE_ARMNT:
1168
18
  case llvm::COFF::IMAGE_FILE_MACHINE_THUMB:
1169
19
  case llvm::COFF::IMAGE_FILE_MACHINE_ARM64:
1170
19
    ArchSpec arch;
1171
19
    arch.SetArchitecture(eArchTypeCOFF, machine, LLDB_INVALID_CPUTYPE,
1172
19
                         IsWindowsSubsystem() ? llvm::Triple::Win32
1173
19
                                              : 
llvm::Triple::UnknownOS0
);
1174
19
    return arch;
1175
19
  }
1176
0
  return ArchSpec();
1177
19
}
1178
1179
12
ObjectFile::Type ObjectFilePECOFF::CalculateType() {
1180
12
  if (m_coff_header.machine != 0) {
1181
12
    if ((m_coff_header.flags & llvm::COFF::IMAGE_FILE_DLL) == 0)
1182
11
      return eTypeExecutable;
1183
1
    else
1184
1
      return eTypeSharedLibrary;
1185
12
  }
1186
0
  return eTypeExecutable;
1187
12
}
1188
1189
6
ObjectFile::Strata ObjectFilePECOFF::CalculateStrata() { return eStrataUser; }