LLDB mainline
ObjectFileCOFF.cpp
Go to the documentation of this file.
1//===-- ObjectFileCOFF.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 "ObjectFileCOFF.h"
10
11#include "lldb/Core/Module.h"
16
17#include "llvm/Support/Error.h"
18#include "llvm/Support/FormatAdapters.h"
19
20using namespace lldb;
21using namespace lldb_private;
22
23using namespace llvm;
24using namespace llvm::object;
25
26static bool IsCOFFObjectFile(const DataBufferSP &data) {
27 return identify_magic(toStringRef(data->GetData())) ==
28 file_magic::coff_object;
29}
30
32
34
36
42
46
49 DataExtractorSP extractor_sp,
50 offset_t data_offset, const FileSpec *file,
51 offset_t file_offset, offset_t length) {
53
54 if (!extractor_sp || !extractor_sp->HasData()) {
55 DataBufferSP data_sp = MapFileData(*file, length, file_offset);
56 if (!data_sp) {
57 LLDB_LOG(log,
58 "Failed to create ObjectFileCOFF instance: cannot read file {0}",
59 file->GetPath());
60 return nullptr;
61 }
62 extractor_sp = std::make_shared<lldb_private::DataExtractor>(data_sp);
63 data_offset = 0;
64 }
65
66 assert(extractor_sp && extractor_sp->HasData() &&
67 "must have mapped file at this point");
68
69 if (!IsCOFFObjectFile(extractor_sp->GetSharedDataBuffer()))
70 return nullptr;
71
72 if (extractor_sp->GetByteSize() < length) {
73 DataBufferSP data_sp = MapFileData(*file, length, file_offset);
74 if (!data_sp) {
75 LLDB_LOG(log,
76 "Failed to create ObjectFileCOFF instance: cannot read file {0}",
77 file->GetPath());
78 return nullptr;
79 }
80 extractor_sp = std::make_shared<lldb_private::DataExtractor>(data_sp);
81 data_offset = 0;
82 }
83
84 MemoryBufferRef buffer{
85 toStringRef(extractor_sp->GetSharedDataBuffer()->GetData()),
86 file->GetFilename().GetStringRef()};
87
88 Expected<std::unique_ptr<Binary>> binary = createBinary(buffer);
89 if (!binary) {
90 LLDB_LOG_ERROR(log, binary.takeError(),
91 "Failed to create binary for file ({1}): {0}",
92 file->GetPath());
93 return nullptr;
94 }
95
96 LLDB_LOG(log, "ObjectFileCOFF::ObjectFileCOFF module = {1} ({2}), file = {3}",
97 module_sp.get(), module_sp->GetSpecificationDescription(),
98 file->GetPath());
99
100 return new ObjectFileCOFF(unique_dyn_cast<COFFObjectFile>(std::move(*binary)),
101 module_sp, extractor_sp, data_offset, file,
102 file_offset, length);
103}
104
106 const ModuleSP &module_sp, WritableDataBufferSP data_sp,
107 const ProcessSP &process_sp, addr_t header) {
108 // FIXME: do we need to worry about construction from a memory region?
109 return nullptr;
110}
111
113 const FileSpec &file, DataBufferSP &data_sp, offset_t data_offset,
114 offset_t file_offset, offset_t length, ModuleSpecList &specs) {
115 if (!IsCOFFObjectFile(data_sp))
116 return 0;
117
118 MemoryBufferRef buffer{toStringRef(data_sp->GetData()),
119 file.GetFilename().GetStringRef()};
120 Expected<std::unique_ptr<Binary>> binary = createBinary(buffer);
121 if (!binary) {
122 Log *log = GetLog(LLDBLog::Object);
123 LLDB_LOG_ERROR(log, binary.takeError(),
124 "Failed to create binary for file ({1}): {0}",
125 file.GetFilename());
126 return 0;
127 }
128
129 std::unique_ptr<COFFObjectFile> object =
130 unique_dyn_cast<COFFObjectFile>(std::move(*binary));
131 switch (static_cast<COFF::MachineTypes>(object->getMachine())) {
132 case COFF::IMAGE_FILE_MACHINE_I386:
133 specs.Append(ModuleSpec(file, ArchSpec("i686-unknown-windows-msvc")));
134 return 1;
135 case COFF::IMAGE_FILE_MACHINE_AMD64:
136 specs.Append(ModuleSpec(file, ArchSpec("x86_64-unknown-windows-msvc")));
137 return 1;
138 case COFF::IMAGE_FILE_MACHINE_ARMNT:
139 specs.Append(ModuleSpec(file, ArchSpec("armv7-unknown-windows-msvc")));
140 return 1;
141 case COFF::IMAGE_FILE_MACHINE_ARM64:
142 specs.Append(ModuleSpec(file, ArchSpec("aarch64-unknown-windows-msvc")));
143 return 1;
144 default:
145 return 0;
146 }
147}
148
150 ModuleSP module(GetModule());
151 if (!module)
152 return;
153
154 std::lock_guard<std::recursive_mutex> guard(module->GetMutex());
155
156 stream->Printf("%p: ", static_cast<void *>(this));
157 stream->Indent();
158 stream->PutCString("ObjectFileCOFF");
159 *stream << ", file = '" << m_file
160 << "', arch = " << GetArchitecture().GetArchitectureName() << '\n';
161
162 if (SectionList *sections = GetSectionList())
163 sections->Dump(stream->AsRawOstream(), stream->GetIndentLevel(), nullptr,
164 true, std::numeric_limits<uint32_t>::max());
165}
166
168 return const_cast<ObjectFileCOFF *>(this)->GetArchitecture().GetAddressByteSize();
169}
170
172 switch (static_cast<COFF::MachineTypes>(m_object->getMachine())) {
173 case COFF::IMAGE_FILE_MACHINE_I386:
174 return ArchSpec("i686-unknown-windows-msvc");
175 case COFF::IMAGE_FILE_MACHINE_AMD64:
176 return ArchSpec("x86_64-unknown-windows-msvc");
177 case COFF::IMAGE_FILE_MACHINE_ARMNT:
178 return ArchSpec("armv7-unknown-windows-msvc");
179 case COFF::IMAGE_FILE_MACHINE_ARM64:
180 return ArchSpec("aarch64-unknown-windows-msvc");
181 default:
182 return ArchSpec();
183 }
184}
185
187 if (m_sections_up)
188 return;
189
190 m_sections_up = std::make_unique<SectionList>();
191 ModuleSP module(GetModule());
192 if (!module)
193 return;
194
195 std::lock_guard<std::recursive_mutex> guard(module->GetMutex());
196
197 auto SectionType = [](StringRef Name,
198 const coff_section *Section) -> lldb::SectionType {
199 // DWARF Debug Sections
200 if (Name.consume_front(".debug_"))
201 return GetDWARFSectionTypeFromName(Name);
202
203 lldb::SectionType type = StringSwitch<lldb::SectionType>(Name)
204 // CodeView Debug Sections: .debug$S, .debug$T
205 .StartsWith(".debug$", eSectionTypeDebug)
206 .Case("clangast", eSectionTypeOther)
207 .Default(eSectionTypeInvalid);
208 if (type != eSectionTypeInvalid)
209 return type;
210
211 if (Section->Characteristics & COFF::IMAGE_SCN_CNT_CODE)
212 return eSectionTypeCode;
213 if (Section->Characteristics & COFF::IMAGE_SCN_CNT_INITIALIZED_DATA)
214 return eSectionTypeData;
215 if (Section->Characteristics & COFF::IMAGE_SCN_CNT_UNINITIALIZED_DATA)
216 return Section->SizeOfRawData ? eSectionTypeData : eSectionTypeZeroFill;
217 return eSectionTypeOther;
218 };
219 auto Permissions = [](const object::coff_section *Section) -> uint32_t {
220 uint32_t permissions = 0;
221 if (Section->Characteristics & COFF::IMAGE_SCN_MEM_EXECUTE)
222 permissions |= lldb::ePermissionsExecutable;
223 if (Section->Characteristics & COFF::IMAGE_SCN_MEM_READ)
224 permissions |= lldb::ePermissionsReadable;
225 if (Section->Characteristics & COFF::IMAGE_SCN_MEM_WRITE)
226 permissions |= lldb::ePermissionsWritable;
227 return permissions;
228 };
229
230 for (const auto &SecRef : m_object->sections()) {
231 const auto COFFSection = m_object->getCOFFSection(SecRef);
232
233 llvm::Expected<StringRef> Name = SecRef.getName();
234 StringRef SectionName = Name ? *Name : COFFSection->Name;
235 if (!Name)
236 consumeError(Name.takeError());
237
238 SectionSP section =
239 std::make_unique<Section>(module, this,
240 static_cast<user_id_t>(SecRef.getIndex()),
241 ConstString(SectionName),
242 SectionType(SectionName, COFFSection),
243 COFFSection->VirtualAddress,
244 COFFSection->VirtualSize,
245 COFFSection->PointerToRawData,
246 COFFSection->SizeOfRawData,
247 COFFSection->getAlignment(),
248 0);
249 section->SetPermissions(Permissions(COFFSection));
250
251 m_sections_up->AddSection(section);
252 sections.AddSection(section);
253 }
254}
255
257 Log *log = GetLog(LLDBLog::Object);
258
259 SectionList *sections = GetSectionList();
260 symtab.Reserve(symtab.GetNumSymbols() + m_object->getNumberOfSymbols());
261
262 auto SymbolType = [](const COFFSymbolRef &Symbol) -> lldb::SymbolType {
263 if (Symbol.getComplexType() == COFF::IMAGE_SYM_DTYPE_FUNCTION)
264 return eSymbolTypeCode;
265 if (Symbol.getBaseType() == COFF::IMAGE_SYM_TYPE_NULL &&
266 Symbol.getComplexType() == COFF::IMAGE_SYM_DTYPE_NULL)
267 return eSymbolTypeData;
268 return eSymbolTypeInvalid;
269 };
270
271 for (const auto &SymRef : m_object->symbols()) {
272 const auto COFFSymRef = m_object->getCOFFSymbol(SymRef);
273
274 Expected<StringRef> NameOrErr = SymRef.getName();
275 if (!NameOrErr) {
276 LLDB_LOG_ERROR(log, NameOrErr.takeError(),
277 "ObjectFileCOFF: failed to get symbol name: {0}");
278 continue;
279 }
280
281 Symbol symbol;
282 symbol.GetMangled().SetValue(ConstString(*NameOrErr));
283
284 int16_t SecIdx = static_cast<int16_t>(COFFSymRef.getSectionNumber());
285 if (SecIdx == COFF::IMAGE_SYM_ABSOLUTE) {
286 symbol.GetAddressRef() = Address{COFFSymRef.getValue()};
288 } else if (SecIdx >= 1) {
289 symbol.GetAddressRef() = Address(sections->GetSectionAtIndex(SecIdx - 1),
290 COFFSymRef.getValue());
291 symbol.SetType(SymbolType(COFFSymRef));
292 }
293
294 symtab.AddSymbol(symbol);
295 }
296
297 LLDB_LOG(log, "ObjectFileCOFF::ParseSymtab processed {0} symbols",
298 m_object->getNumberOfSymbols());
299}
300
302 ModuleSP module(GetModule());
303 if (!module)
304 return false;
305
306 std::lock_guard<std::recursive_mutex> guard(module->GetMutex());
307
308 m_data_nsp->SetByteOrder(eByteOrderLittle);
309 m_data_nsp->SetAddressByteSize(GetAddressByteSize());
310
311 return true;
312}
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:369
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:392
static bool IsCOFFObjectFile(const DataBufferSP &data)
#define LLDB_PLUGIN_DEFINE(PluginName)
uint32_t GetAddressByteSize() const override
Gets the address size in bytes for the current object file.
void ParseSymtab(lldb_private::Symtab &) override
Parse the symbol table into the provides symbol table object.
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)
static lldb_private::ObjectFile * CreateMemoryInstance(const lldb::ModuleSP &module_sp, lldb::WritableDataBufferSP data_sp, const lldb::ProcessSP &process_sp, lldb::addr_t header)
static void Initialize()
void Dump(lldb_private::Stream *stream) override
Dump a description of this object to a Stream.
void CreateSections(lldb_private::SectionList &) override
static char ID
static llvm::StringRef GetPluginDescriptionStatic()
lldb_private::ArchSpec GetArchitecture() override
Get the ArchSpec for this object file.
~ObjectFileCOFF() override
bool ParseHeader() override
Attempts to parse the object header.
static void Terminate()
std::unique_ptr< llvm::object::COFFObjectFile > m_object
ObjectFileCOFF(std::unique_ptr< llvm::object::COFFObjectFile > object, const lldb::ModuleSP &module_sp, lldb::DataExtractorSP extractor_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t file_offset, lldb::offset_t length)
static lldb_private::ObjectFile * CreateInstance(const lldb::ModuleSP &module_sp, lldb::DataExtractorSP extractor_sp, lldb::offset_t data_offset, const lldb_private::FileSpec *file, lldb::offset_t file_offset, lldb::offset_t length)
static llvm::StringRef GetPluginNameStatic()
A section + offset based address class.
Definition Address.h:62
An architecture specification class.
Definition ArchSpec.h:31
uint32_t GetAddressByteSize() const
Returns the size in bytes of an address of the current architecture.
Definition ArchSpec.cpp:685
const char * GetArchitectureName() const
Returns a static string representing the current architecture.
Definition ArchSpec.cpp:548
A uniqued constant string class.
Definition ConstString.h:40
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
A file utility class.
Definition FileSpec.h:57
const ConstString & GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:251
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:374
void SetValue(ConstString name)
Set the string value in this object.
Definition Mangled.cpp:124
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
void Append(const ModuleSpec &spec)
Definition ModuleSpec.h:326
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
std::unique_ptr< lldb_private::SectionList > m_sections_up
Definition ObjectFile.h:799
static lldb::DataBufferSP MapFileData(const FileSpec &file, uint64_t Size, uint64_t Offset)
static lldb::SectionType GetDWARFSectionTypeFromName(llvm::StringRef name)
Parses the section type from a section name for DWARF sections.
DataExtractorNSP m_data_nsp
The data for this object file so things can be parsed lazily.
Definition ObjectFile.h:792
virtual SectionList * GetSectionList(bool update_module_section_list=true)
Gets the section list for the currently selected architecture (and object for archives).
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static bool UnregisterPlugin(ABICreateInstance create_callback)
size_t AddSection(const lldb::SectionSP &section_sp)
Definition Section.cpp:488
lldb::SectionSP GetSectionAtIndex(size_t idx) const
Definition Section.cpp:557
A stream class that can stream formatted output to a file.
Definition Stream.h:28
llvm::raw_ostream & AsRawOstream()
Returns a raw_ostream that forwards the data to this Stream object.
Definition Stream.h:406
size_t Indent(llvm::StringRef s="")
Indent the current line in the stream.
Definition Stream.cpp:157
size_t Printf(const char *format,...) __attribute__((format(printf
Output printf formatted output to the stream.
Definition Stream.cpp:134
size_t PutCString(llvm::StringRef cstr)
Output a C string to the stream.
Definition Stream.cpp:65
unsigned GetIndentLevel() const
Get the current indentation level.
Definition Stream.cpp:187
void SetType(lldb::SymbolType type)
Definition Symbol.h:171
Mangled & GetMangled()
Definition Symbol.h:147
Address & GetAddressRef()
Definition Symbol.h:73
uint32_t AddSymbol(const Symbol &symbol)
Definition Symtab.cpp:64
size_t GetNumSymbols() const
Definition Symtab.cpp:77
void Reserve(size_t count)
Definition Symtab.cpp:51
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:332
uint64_t offset_t
Definition lldb-types.h:85
std::shared_ptr< lldb_private::Process > ProcessSP
SymbolType
Symbol types.
@ eSymbolTypeAbsolute
uint64_t user_id_t
Definition lldb-types.h:82
std::shared_ptr< lldb_private::DataBuffer > DataBufferSP
std::shared_ptr< lldb_private::Section > SectionSP
std::shared_ptr< lldb_private::WritableDataBuffer > WritableDataBufferSP
uint64_t addr_t
Definition lldb-types.h:80
@ eSectionTypeInvalid
@ eSectionTypeZeroFill
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::Module > ModuleSP