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