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