1 //===-- ObjectFile.cpp ------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lldb/Symbol/ObjectFile.h"
11 #include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
12 #include "lldb/Core/Module.h"
13 #include "lldb/Core/ModuleSpec.h"
14 #include "lldb/Core/PluginManager.h"
15 #include "lldb/Core/Section.h"
16 #include "lldb/Core/Timer.h"
17 #include "lldb/Symbol/ObjectContainer.h"
18 #include "lldb/Symbol/SymbolFile.h"
19 #include "lldb/Target/Process.h"
20 #include "lldb/Target/RegisterContext.h"
21 #include "lldb/Target/SectionLoadList.h"
22 #include "lldb/Target/Target.h"
23 #include "lldb/Utility/DataBuffer.h"
24 #include "lldb/Utility/DataBufferHeap.h"
25 #include "lldb/Utility/DataBufferLLVM.h"
26 #include "lldb/Utility/Log.h"
27 #include "lldb/Utility/RegularExpression.h"
28 #include "lldb/lldb-private.h"
31 using namespace lldb_private;
34 ObjectFile::FindPlugin(const lldb::ModuleSP &module_sp, const FileSpec *file,
35 lldb::offset_t file_offset, lldb::offset_t file_size,
36 DataBufferSP &data_sp, lldb::offset_t &data_offset) {
37 ObjectFileSP object_file_sp;
42 "ObjectFile::FindPlugin (module = %s, file = %p, file_offset = "
43 "0x%8.8" PRIx64 ", file_size = 0x%8.8" PRIx64 ")",
44 module_sp->GetFileSpec().GetPath().c_str(),
45 static_cast<const void *>(file), static_cast<uint64_t>(file_offset),
46 static_cast<uint64_t>(file_size));
48 FileSpec archive_file;
49 ObjectContainerCreateInstance create_object_container_callback;
51 const bool file_exists = file->Exists();
53 // We have an object name which most likely means we have
54 // a .o file in a static archive (.a file). Try and see if
55 // we have a cached archive first without reading any data
57 if (file_exists && module_sp->GetObjectName()) {
58 for (uint32_t idx = 0;
59 (create_object_container_callback =
60 PluginManager::GetObjectContainerCreateCallbackAtIndex(
63 std::unique_ptr<ObjectContainer> object_container_ap(
64 create_object_container_callback(module_sp, data_sp,
65 data_offset, file, file_offset,
68 if (object_container_ap.get())
69 object_file_sp = object_container_ap->GetObjectFile(file);
71 if (object_file_sp.get())
72 return object_file_sp;
75 // Ok, we didn't find any containers that have a named object, now
76 // lets read the first 512 bytes from the file so the object file
77 // and object container plug-ins can use these bytes to see if they
78 // can parse this file.
81 DataBufferLLVM::CreateSliceFromPath(file->GetPath(), 512, file_offset);
86 if (!data_sp || data_sp->GetByteSize() == 0) {
87 // Check for archive file with format "/path/to/archive.a(object.o)"
88 char path_with_object[PATH_MAX * 2];
89 module_sp->GetFileSpec().GetPath(path_with_object,
90 sizeof(path_with_object));
92 ConstString archive_object;
93 const bool must_exist = true;
94 if (ObjectFile::SplitArchivePathWithObject(
95 path_with_object, archive_file, archive_object, must_exist)) {
96 file_size = archive_file.GetByteSize();
99 module_sp->SetFileSpecAndObjectName(archive_file, archive_object);
100 // Check if this is a object container by iterating through all
102 // container plugin instances and then trying to get an object file
103 // from the container plugins since we had a name. Also, don't read
104 // ANY data in case there is data cached in the container plug-ins
105 // (like BSD archives caching the contained objects within an file).
106 for (uint32_t idx = 0;
107 (create_object_container_callback =
108 PluginManager::GetObjectContainerCreateCallbackAtIndex(
111 std::unique_ptr<ObjectContainer> object_container_ap(
112 create_object_container_callback(module_sp, data_sp,
114 file_offset, file_size));
116 if (object_container_ap.get())
117 object_file_sp = object_container_ap->GetObjectFile(file);
119 if (object_file_sp.get())
120 return object_file_sp;
122 // We failed to find any cached object files in the container
123 // plug-ins, so lets read the first 512 bytes and try again below...
124 data_sp = DataBufferLLVM::CreateSliceFromPath(archive_file.GetPath(),
130 if (data_sp && data_sp->GetByteSize() > 0) {
131 // Check if this is a normal object file by iterating through
132 // all object file plugin instances.
133 ObjectFileCreateInstance create_object_file_callback;
134 for (uint32_t idx = 0;
135 (create_object_file_callback =
136 PluginManager::GetObjectFileCreateCallbackAtIndex(idx)) !=
139 object_file_sp.reset(create_object_file_callback(
140 module_sp, data_sp, data_offset, file, file_offset, file_size));
141 if (object_file_sp.get())
142 return object_file_sp;
145 // Check if this is a object container by iterating through
146 // all object container plugin instances and then trying to get
147 // an object file from the container.
148 for (uint32_t idx = 0;
149 (create_object_container_callback =
150 PluginManager::GetObjectContainerCreateCallbackAtIndex(
153 std::unique_ptr<ObjectContainer> object_container_ap(
154 create_object_container_callback(module_sp, data_sp, data_offset,
155 file, file_offset, file_size));
157 if (object_container_ap.get())
158 object_file_sp = object_container_ap->GetObjectFile(file);
160 if (object_file_sp.get())
161 return object_file_sp;
166 // We didn't find it, so clear our shared pointer in case it
167 // contains anything and return an empty shared pointer
168 object_file_sp.reset();
169 return object_file_sp;
172 ObjectFileSP ObjectFile::FindPlugin(const lldb::ModuleSP &module_sp,
173 const ProcessSP &process_sp,
174 lldb::addr_t header_addr,
175 DataBufferSP &data_sp) {
176 ObjectFileSP object_file_sp;
179 Timer scoped_timer(LLVM_PRETTY_FUNCTION, "ObjectFile::FindPlugin (module = "
180 "%s, process = %p, header_addr = "
182 module_sp->GetFileSpec().GetPath().c_str(),
183 static_cast<void *>(process_sp.get()), header_addr);
186 // Check if this is a normal object file by iterating through
187 // all object file plugin instances.
188 ObjectFileCreateMemoryInstance create_callback;
191 PluginManager::GetObjectFileCreateMemoryCallbackAtIndex(idx)) !=
194 object_file_sp.reset(
195 create_callback(module_sp, data_sp, process_sp, header_addr));
196 if (object_file_sp.get())
197 return object_file_sp;
201 // We didn't find it, so clear our shared pointer in case it
202 // contains anything and return an empty shared pointer
203 object_file_sp.reset();
204 return object_file_sp;
207 size_t ObjectFile::GetModuleSpecifications(const FileSpec &file,
208 lldb::offset_t file_offset,
209 lldb::offset_t file_size,
210 ModuleSpecList &specs) {
211 DataBufferSP data_sp = DataBufferLLVM::CreateSliceFromPath(file.GetPath(), 512, file_offset);
213 if (file_size == 0) {
214 const lldb::offset_t actual_file_size = file.GetByteSize();
215 if (actual_file_size > file_offset)
216 file_size = actual_file_size - file_offset;
218 return ObjectFile::GetModuleSpecifications(file, // file spec
219 data_sp, // data bytes
221 file_offset, // file offset
222 file_size, // file length
228 size_t ObjectFile::GetModuleSpecifications(
229 const lldb_private::FileSpec &file, lldb::DataBufferSP &data_sp,
230 lldb::offset_t data_offset, lldb::offset_t file_offset,
231 lldb::offset_t file_size, lldb_private::ModuleSpecList &specs) {
232 const size_t initial_count = specs.GetSize();
233 ObjectFileGetModuleSpecifications callback;
235 // Try the ObjectFile plug-ins
238 PluginManager::GetObjectFileGetModuleSpecificationsCallbackAtIndex(
241 if (callback(file, data_sp, data_offset, file_offset, file_size, specs) > 0)
242 return specs.GetSize() - initial_count;
245 // Try the ObjectContainer plug-ins
247 (callback = PluginManager::
248 GetObjectContainerGetModuleSpecificationsCallbackAtIndex(i)) !=
251 if (callback(file, data_sp, data_offset, file_offset, file_size, specs) > 0)
252 return specs.GetSize() - initial_count;
257 ObjectFile::ObjectFile(const lldb::ModuleSP &module_sp,
258 const FileSpec *file_spec_ptr,
259 lldb::offset_t file_offset, lldb::offset_t length,
260 const lldb::DataBufferSP &data_sp,
261 lldb::offset_t data_offset)
262 : ModuleChild(module_sp),
263 m_file(), // This file could be different from the original module's file
264 m_type(eTypeInvalid), m_strata(eStrataInvalid),
265 m_file_offset(file_offset), m_length(length), m_data(),
266 m_unwind_table(*this), m_process_wp(),
267 m_memory_addr(LLDB_INVALID_ADDRESS), m_sections_ap(), m_symtab_ap(),
268 m_synthetic_symbol_idx(0) {
270 m_file = *file_spec_ptr;
272 m_data.SetData(data_sp, data_offset, length);
273 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
275 log->Printf("%p ObjectFile::ObjectFile() module = %p (%s), file = %s, "
276 "file_offset = 0x%8.8" PRIx64 ", size = %" PRIu64,
277 static_cast<void *>(this), static_cast<void *>(module_sp.get()),
278 module_sp->GetSpecificationDescription().c_str(),
279 m_file ? m_file.GetPath().c_str() : "<NULL>", m_file_offset,
283 ObjectFile::ObjectFile(const lldb::ModuleSP &module_sp,
284 const ProcessSP &process_sp, lldb::addr_t header_addr,
285 DataBufferSP &header_data_sp)
286 : ModuleChild(module_sp), m_file(), m_type(eTypeInvalid),
287 m_strata(eStrataInvalid), m_file_offset(0), m_length(0), m_data(),
288 m_unwind_table(*this), m_process_wp(process_sp),
289 m_memory_addr(header_addr), m_sections_ap(), m_symtab_ap(),
290 m_synthetic_symbol_idx(0) {
292 m_data.SetData(header_data_sp, 0, header_data_sp->GetByteSize());
293 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
295 log->Printf("%p ObjectFile::ObjectFile() module = %p (%s), process = %p, "
296 "header_addr = 0x%" PRIx64,
297 static_cast<void *>(this), static_cast<void *>(module_sp.get()),
298 module_sp->GetSpecificationDescription().c_str(),
299 static_cast<void *>(process_sp.get()), m_memory_addr);
302 ObjectFile::~ObjectFile() {
303 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
305 log->Printf("%p ObjectFile::~ObjectFile ()\n", static_cast<void *>(this));
308 bool ObjectFile::SetModulesArchitecture(const ArchSpec &new_arch) {
309 ModuleSP module_sp(GetModule());
311 return module_sp->SetArchitecture(new_arch);
315 AddressClass ObjectFile::GetAddressClass(addr_t file_addr) {
316 Symtab *symtab = GetSymtab();
318 Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
320 if (symbol->ValueIsAddress()) {
321 const SectionSP section_sp(symbol->GetAddressRef().GetSection());
323 const SectionType section_type = section_sp->GetType();
324 switch (section_type) {
325 case eSectionTypeInvalid:
326 return eAddressClassUnknown;
327 case eSectionTypeCode:
328 return eAddressClassCode;
329 case eSectionTypeContainer:
330 return eAddressClassUnknown;
331 case eSectionTypeData:
332 case eSectionTypeDataCString:
333 case eSectionTypeDataCStringPointers:
334 case eSectionTypeDataSymbolAddress:
335 case eSectionTypeData4:
336 case eSectionTypeData8:
337 case eSectionTypeData16:
338 case eSectionTypeDataPointers:
339 case eSectionTypeZeroFill:
340 case eSectionTypeDataObjCMessageRefs:
341 case eSectionTypeDataObjCCFStrings:
342 case eSectionTypeGoSymtab:
343 return eAddressClassData;
344 case eSectionTypeDebug:
345 case eSectionTypeDWARFDebugAbbrev:
346 case eSectionTypeDWARFDebugAddr:
347 case eSectionTypeDWARFDebugAranges:
348 case eSectionTypeDWARFDebugFrame:
349 case eSectionTypeDWARFDebugInfo:
350 case eSectionTypeDWARFDebugLine:
351 case eSectionTypeDWARFDebugLoc:
352 case eSectionTypeDWARFDebugMacInfo:
353 case eSectionTypeDWARFDebugMacro:
354 case eSectionTypeDWARFDebugPubNames:
355 case eSectionTypeDWARFDebugPubTypes:
356 case eSectionTypeDWARFDebugRanges:
357 case eSectionTypeDWARFDebugStr:
358 case eSectionTypeDWARFDebugStrOffsets:
359 case eSectionTypeDWARFAppleNames:
360 case eSectionTypeDWARFAppleTypes:
361 case eSectionTypeDWARFAppleNamespaces:
362 case eSectionTypeDWARFAppleObjC:
363 return eAddressClassDebug;
364 case eSectionTypeEHFrame:
365 case eSectionTypeARMexidx:
366 case eSectionTypeARMextab:
367 case eSectionTypeCompactUnwind:
368 return eAddressClassRuntime;
369 case eSectionTypeELFSymbolTable:
370 case eSectionTypeELFDynamicSymbols:
371 case eSectionTypeELFRelocationEntries:
372 case eSectionTypeELFDynamicLinkInfo:
373 case eSectionTypeOther:
374 return eAddressClassUnknown;
375 case eSectionTypeAbsoluteAddress:
376 // In case of absolute sections decide the address class based on
378 // type because the section type isn't specify if it is a code or a
386 const SymbolType symbol_type = symbol->GetType();
387 switch (symbol_type) {
389 return eAddressClassUnknown;
390 case eSymbolTypeAbsolute:
391 return eAddressClassUnknown;
392 case eSymbolTypeCode:
393 return eAddressClassCode;
394 case eSymbolTypeTrampoline:
395 return eAddressClassCode;
396 case eSymbolTypeResolver:
397 return eAddressClassCode;
398 case eSymbolTypeData:
399 return eAddressClassData;
400 case eSymbolTypeRuntime:
401 return eAddressClassRuntime;
402 case eSymbolTypeException:
403 return eAddressClassRuntime;
404 case eSymbolTypeSourceFile:
405 return eAddressClassDebug;
406 case eSymbolTypeHeaderFile:
407 return eAddressClassDebug;
408 case eSymbolTypeObjectFile:
409 return eAddressClassDebug;
410 case eSymbolTypeCommonBlock:
411 return eAddressClassDebug;
412 case eSymbolTypeBlock:
413 return eAddressClassDebug;
414 case eSymbolTypeLocal:
415 return eAddressClassData;
416 case eSymbolTypeParam:
417 return eAddressClassData;
418 case eSymbolTypeVariable:
419 return eAddressClassData;
420 case eSymbolTypeVariableType:
421 return eAddressClassDebug;
422 case eSymbolTypeLineEntry:
423 return eAddressClassDebug;
424 case eSymbolTypeLineHeader:
425 return eAddressClassDebug;
426 case eSymbolTypeScopeBegin:
427 return eAddressClassDebug;
428 case eSymbolTypeScopeEnd:
429 return eAddressClassDebug;
430 case eSymbolTypeAdditional:
431 return eAddressClassUnknown;
432 case eSymbolTypeCompiler:
433 return eAddressClassDebug;
434 case eSymbolTypeInstrumentation:
435 return eAddressClassDebug;
436 case eSymbolTypeUndefined:
437 return eAddressClassUnknown;
438 case eSymbolTypeObjCClass:
439 return eAddressClassRuntime;
440 case eSymbolTypeObjCMetaClass:
441 return eAddressClassRuntime;
442 case eSymbolTypeObjCIVar:
443 return eAddressClassRuntime;
444 case eSymbolTypeReExported:
445 return eAddressClassRuntime;
449 return eAddressClassUnknown;
452 DataBufferSP ObjectFile::ReadMemory(const ProcessSP &process_sp,
453 lldb::addr_t addr, size_t byte_size) {
454 DataBufferSP data_sp;
456 std::unique_ptr<DataBufferHeap> data_ap(new DataBufferHeap(byte_size, 0));
458 const size_t bytes_read = process_sp->ReadMemory(
459 addr, data_ap->GetBytes(), data_ap->GetByteSize(), error);
460 if (bytes_read == byte_size)
461 data_sp.reset(data_ap.release());
466 size_t ObjectFile::GetData(lldb::offset_t offset, size_t length,
467 DataExtractor &data) const {
468 // The entire file has already been mmap'ed into m_data, so just copy from
470 // as the back mmap buffer will be shared with shared pointers.
471 return data.SetData(m_data, offset, length);
474 size_t ObjectFile::CopyData(lldb::offset_t offset, size_t length,
476 // The entire file has already been mmap'ed into m_data, so just copy from
478 // Note that the data remains in target byte order.
479 return m_data.CopyData(offset, length, dst);
482 size_t ObjectFile::ReadSectionData(const Section *section,
483 lldb::offset_t section_offset, void *dst,
484 size_t dst_len) const {
486 section_offset *= section->GetTargetByteSize();
488 // If some other objectfile owns this data, pass this to them.
489 if (section->GetObjectFile() != this)
490 return section->GetObjectFile()->ReadSectionData(section, section_offset,
494 ProcessSP process_sp(m_process_wp.lock());
497 const addr_t base_load_addr =
498 section->GetLoadBaseAddress(&process_sp->GetTarget());
499 if (base_load_addr != LLDB_INVALID_ADDRESS)
500 return process_sp->ReadMemory(base_load_addr + section_offset, dst,
504 const lldb::offset_t section_file_size = section->GetFileSize();
505 if (section_offset < section_file_size) {
506 const size_t section_bytes_left = section_file_size - section_offset;
507 size_t section_dst_len = dst_len;
508 if (section_dst_len > section_bytes_left)
509 section_dst_len = section_bytes_left;
510 return CopyData(section->GetFileOffset() + section_offset,
511 section_dst_len, dst);
513 if (section->GetType() == eSectionTypeZeroFill) {
514 const uint64_t section_size = section->GetByteSize();
515 const uint64_t section_bytes_left = section_size - section_offset;
516 uint64_t section_dst_len = dst_len;
517 if (section_dst_len > section_bytes_left)
518 section_dst_len = section_bytes_left;
519 memset(dst, 0, section_dst_len);
520 return section_dst_len;
527 //----------------------------------------------------------------------
528 // Get the section data the file on disk
529 //----------------------------------------------------------------------
530 size_t ObjectFile::ReadSectionData(const Section *section,
531 DataExtractor §ion_data) const {
532 // If some other objectfile owns this data, pass this to them.
533 if (section->GetObjectFile() != this)
534 return section->GetObjectFile()->ReadSectionData(section, section_data);
537 ProcessSP process_sp(m_process_wp.lock());
539 const addr_t base_load_addr =
540 section->GetLoadBaseAddress(&process_sp->GetTarget());
541 if (base_load_addr != LLDB_INVALID_ADDRESS) {
542 DataBufferSP data_sp(
543 ReadMemory(process_sp, base_load_addr, section->GetByteSize()));
545 section_data.SetData(data_sp, 0, data_sp->GetByteSize());
546 section_data.SetByteOrder(process_sp->GetByteOrder());
547 section_data.SetAddressByteSize(process_sp->GetAddressByteSize());
548 return section_data.GetByteSize();
552 return GetData(section->GetFileOffset(), section->GetFileSize(),
555 // The object file now contains a full mmap'ed copy of the object file data,
557 return MemoryMapSectionData(section, section_data);
561 size_t ObjectFile::MemoryMapSectionData(const Section *section,
562 DataExtractor §ion_data) const {
563 // If some other objectfile owns this data, pass this to them.
564 if (section->GetObjectFile() != this)
565 return section->GetObjectFile()->MemoryMapSectionData(section,
569 return ReadSectionData(section, section_data);
571 // The object file now contains a full mmap'ed copy of the object file data,
573 return GetData(section->GetFileOffset(), section->GetFileSize(),
578 bool ObjectFile::SplitArchivePathWithObject(const char *path_with_object,
579 FileSpec &archive_file,
580 ConstString &archive_object,
582 RegularExpression g_object_regex(llvm::StringRef("(.*)\\(([^\\)]+)\\)$"));
583 RegularExpression::Match regex_match(2);
584 if (g_object_regex.Execute(llvm::StringRef::withNullAsEmpty(path_with_object),
588 if (regex_match.GetMatchAtIndex(path_with_object, 1, path) &&
589 regex_match.GetMatchAtIndex(path_with_object, 2, obj)) {
590 archive_file.SetFile(path, false);
591 archive_object.SetCString(obj.c_str());
592 if (must_exist && !archive_file.Exists())
600 void ObjectFile::ClearSymtab() {
601 ModuleSP module_sp(GetModule());
603 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
604 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_OBJECT));
606 log->Printf("%p ObjectFile::ClearSymtab () symtab = %p",
607 static_cast<void *>(this),
608 static_cast<void *>(m_symtab_ap.get()));
613 SectionList *ObjectFile::GetSectionList(bool update_module_section_list) {
614 if (m_sections_ap.get() == nullptr) {
615 if (update_module_section_list) {
616 ModuleSP module_sp(GetModule());
618 std::lock_guard<std::recursive_mutex> guard(module_sp->GetMutex());
619 CreateSections(*module_sp->GetUnifiedSectionList());
622 SectionList unified_section_list;
623 CreateSections(unified_section_list);
626 return m_sections_ap.get();
630 ObjectFile::GetSymbolTypeFromName(llvm::StringRef name,
631 lldb::SymbolType symbol_type_hint) {
633 if (name.startswith("_OBJC_")) {
635 if (name.startswith("_OBJC_CLASS_$_"))
636 return lldb::eSymbolTypeObjCClass;
637 if (name.startswith("_OBJC_METACLASS_$_"))
638 return lldb::eSymbolTypeObjCMetaClass;
639 if (name.startswith("_OBJC_IVAR_$_"))
640 return lldb::eSymbolTypeObjCIVar;
641 } else if (name.startswith(".objc_class_name_")) {
643 return lldb::eSymbolTypeObjCClass;
646 return symbol_type_hint;
649 ConstString ObjectFile::GetNextSyntheticSymbolName() {
651 ConstString file_name = GetModule()->GetFileSpec().GetFilename();
652 ss.Printf("___lldb_unnamed_symbol%u$$%s", ++m_synthetic_symbol_idx,
653 file_name.GetCString());
654 return ConstString(ss.GetString());
657 Error ObjectFile::LoadInMemory(Target &target, bool set_pc) {
659 ProcessSP process = target.CalculateProcess();
661 return Error("No Process");
662 if (set_pc && !GetEntryPointAddress().IsValid())
663 return Error("No entry address in object file");
665 SectionList *section_list = GetSectionList();
667 return Error("No section in object file");
668 size_t section_count = section_list->GetNumSections(0);
669 for (size_t i = 0; i < section_count; ++i) {
670 SectionSP section_sp = section_list->GetSectionAtIndex(i);
671 addr_t addr = target.GetSectionLoadList().GetSectionLoadAddress(section_sp);
672 if (addr != LLDB_INVALID_ADDRESS) {
673 DataExtractor section_data;
674 // We can skip sections like bss
675 if (section_sp->GetFileSize() == 0)
677 section_sp->GetSectionData(section_data);
678 lldb::offset_t written = process->WriteMemory(
679 addr, section_data.GetDataStart(), section_data.GetByteSize(), error);
680 if (written != section_data.GetByteSize())
685 ThreadList &thread_list = process->GetThreadList();
686 ThreadSP curr_thread(thread_list.GetSelectedThread());
687 RegisterContextSP reg_context(curr_thread->GetRegisterContext());
688 Address file_entry = GetEntryPointAddress();
689 reg_context->SetPC(file_entry.GetLoadAddress(&target));