ObjectFile.cpp revision 97a19b21dacd9063bb5475812df7781777262198
1//===-- ObjectFile.cpp ------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lldb/lldb-private.h"
11#include "lldb/lldb-private-log.h"
12#include "lldb/Core/DataBuffer.h"
13#include "lldb/Core/DataBufferHeap.h"
14#include "lldb/Core/Log.h"
15#include "lldb/Core/Module.h"
16#include "lldb/Core/ModuleSpec.h"
17#include "lldb/Core/PluginManager.h"
18#include "lldb/Core/RegularExpression.h"
19#include "lldb/Core/Section.h"
20#include "lldb/Core/Timer.h"
21#include "lldb/Symbol/ObjectFile.h"
22#include "lldb/Symbol/ObjectContainer.h"
23#include "lldb/Symbol/SymbolFile.h"
24#include "lldb/Target/Process.h"
25#include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
26
27using namespace lldb;
28using namespace lldb_private;
29
30ObjectFileSP
31ObjectFile::FindPlugin (const lldb::ModuleSP &module_sp,
32                        const FileSpec* file,
33                        lldb::offset_t file_offset,
34                        lldb::offset_t file_size,
35                        DataBufferSP &data_sp,
36                        lldb::offset_t &data_offset)
37{
38    ObjectFileSP object_file_sp;
39
40    if (module_sp)
41    {
42        Timer scoped_timer (__PRETTY_FUNCTION__,
43                            "ObjectFile::FindPlugin (module = %s, file = %p, file_offset = 0x%8.8" PRIx64 ", file_size = 0x%8.8" PRIx64 ")",
44                            module_sp->GetFileSpec().GetPath().c_str(),
45                            file, (uint64_t) file_offset, (uint64_t) file_size);
46        if (file)
47        {
48            FileSpec archive_file;
49            ObjectContainerCreateInstance create_object_container_callback;
50
51            const bool file_exists = file->Exists();
52            if (!data_sp)
53            {
54                // We have an object name which most likely means we have
55                // a .o file in a static archive (.a file). Try and see if
56                // we have a cached archive first without reading any data
57                // first
58                if (file_exists && module_sp->GetObjectName())
59                {
60                    for (uint32_t idx = 0; (create_object_container_callback = PluginManager::GetObjectContainerCreateCallbackAtIndex(idx)) != NULL; ++idx)
61                    {
62                        std::unique_ptr<ObjectContainer> object_container_ap(create_object_container_callback(module_sp, data_sp, data_offset, file, file_offset, file_size));
63
64                        if (object_container_ap.get())
65                            object_file_sp = object_container_ap->GetObjectFile(file);
66
67                        if (object_file_sp.get())
68                            return object_file_sp;
69                    }
70                }
71                // Ok, we didn't find any containers that have a named object, now
72                // lets read the first 512 bytes from the file so the object file
73                // and object container plug-ins can use these bytes to see if they
74                // can parse this file.
75                if (file_size > 0)
76                {
77                    data_sp = file->ReadFileContents(file_offset, std::min<size_t>(512, file_size));
78                    data_offset = 0;
79                }
80            }
81
82            if (!data_sp || data_sp->GetByteSize() == 0)
83            {
84                // Check for archive file with format "/path/to/archive.a(object.o)"
85                char path_with_object[PATH_MAX*2];
86                module_sp->GetFileSpec().GetPath(path_with_object, sizeof(path_with_object));
87
88                ConstString archive_object;
89                const bool must_exist = true;
90                if (ObjectFile::SplitArchivePathWithObject (path_with_object, archive_file, archive_object, must_exist))
91                {
92                    file_size = archive_file.GetByteSize();
93                    if (file_size > 0)
94                    {
95                        file = &archive_file;
96                        module_sp->SetFileSpecAndObjectName (archive_file, archive_object);
97                        // Check if this is a object container by iterating through all object
98                        // container plugin instances and then trying to get an object file
99                        // from the container plugins since we had a name. Also, don't read
100                        // ANY data in case there is data cached in the container plug-ins
101                        // (like BSD archives caching the contained objects within an file).
102                        for (uint32_t idx = 0; (create_object_container_callback = PluginManager::GetObjectContainerCreateCallbackAtIndex(idx)) != NULL; ++idx)
103                        {
104                            std::unique_ptr<ObjectContainer> object_container_ap(create_object_container_callback(module_sp, data_sp, data_offset, file, file_offset, file_size));
105
106                            if (object_container_ap.get())
107                                object_file_sp = object_container_ap->GetObjectFile(file);
108
109                            if (object_file_sp.get())
110                                return object_file_sp;
111                        }
112                        // We failed to find any cached object files in the container
113                        // plug-ins, so lets read the first 512 bytes and try again below...
114                        data_sp = archive_file.ReadFileContents(file_offset, 512);
115                    }
116                }
117            }
118
119            if (data_sp && data_sp->GetByteSize() > 0)
120            {
121                // Check if this is a normal object file by iterating through
122                // all object file plugin instances.
123                ObjectFileCreateInstance create_object_file_callback;
124                for (uint32_t idx = 0; (create_object_file_callback = PluginManager::GetObjectFileCreateCallbackAtIndex(idx)) != NULL; ++idx)
125                {
126                    object_file_sp.reset (create_object_file_callback(module_sp, data_sp, data_offset, file, file_offset, file_size));
127                    if (object_file_sp.get())
128                        return object_file_sp;
129                }
130
131                // Check if this is a object container by iterating through
132                // all object container plugin instances and then trying to get
133                // an object file from the container.
134                for (uint32_t idx = 0; (create_object_container_callback = PluginManager::GetObjectContainerCreateCallbackAtIndex(idx)) != NULL; ++idx)
135                {
136                    std::unique_ptr<ObjectContainer> object_container_ap(create_object_container_callback(module_sp, data_sp, data_offset, file, file_offset, file_size));
137
138                    if (object_container_ap.get())
139                        object_file_sp = object_container_ap->GetObjectFile(file);
140
141                    if (object_file_sp.get())
142                        return object_file_sp;
143                }
144            }
145        }
146    }
147    // We didn't find it, so clear our shared pointer in case it
148    // contains anything and return an empty shared pointer
149    object_file_sp.reset();
150    return object_file_sp;
151}
152
153ObjectFileSP
154ObjectFile::FindPlugin (const lldb::ModuleSP &module_sp,
155                        const ProcessSP &process_sp,
156                        lldb::addr_t header_addr,
157                        DataBufferSP &data_sp)
158{
159    ObjectFileSP object_file_sp;
160
161    if (module_sp)
162    {
163        Timer scoped_timer (__PRETTY_FUNCTION__,
164                            "ObjectFile::FindPlugin (module = %s, process = %p, header_addr = 0x%" PRIx64 ")",
165                            module_sp->GetFileSpec().GetPath().c_str(),
166                            process_sp.get(), header_addr);
167        uint32_t idx;
168
169        // Check if this is a normal object file by iterating through
170        // all object file plugin instances.
171        ObjectFileCreateMemoryInstance create_callback;
172        for (idx = 0; (create_callback = PluginManager::GetObjectFileCreateMemoryCallbackAtIndex(idx)) != NULL; ++idx)
173        {
174            object_file_sp.reset (create_callback(module_sp, data_sp, process_sp, header_addr));
175            if (object_file_sp.get())
176                return object_file_sp;
177        }
178
179    }
180    // We didn't find it, so clear our shared pointer in case it
181    // contains anything and return an empty shared pointer
182    object_file_sp.reset();
183    return object_file_sp;
184}
185
186size_t
187ObjectFile::GetModuleSpecifications (const FileSpec &file,
188                                     lldb::offset_t file_offset,
189                                     ModuleSpecList &specs)
190{
191    DataBufferSP data_sp (file.ReadFileContents(file_offset, 512));
192    if (data_sp)
193        return ObjectFile::GetModuleSpecifications (file,                    // file spec
194                                                    data_sp,                 // data bytes
195                                                    0,                       // data offset
196                                                    file_offset,             // file offset
197                                                    data_sp->GetByteSize(),  // data length
198                                                    specs);
199    return 0;
200}
201
202size_t
203ObjectFile::GetModuleSpecifications (const lldb_private::FileSpec& file,
204                                     lldb::DataBufferSP& data_sp,
205                                     lldb::offset_t data_offset,
206                                     lldb::offset_t file_offset,
207                                     lldb::offset_t length,
208                                     lldb_private::ModuleSpecList &specs)
209{
210    const size_t initial_count = specs.GetSize();
211    ObjectFileGetModuleSpecifications callback;
212    uint32_t i;
213    // Try the ObjectFile plug-ins
214    for (i = 0; (callback = PluginManager::GetObjectFileGetModuleSpecificationsCallbackAtIndex(i)) != NULL; ++i)
215    {
216        if (callback (file, data_sp, data_offset, file_offset, length, specs) > 0)
217            return specs.GetSize() - initial_count;
218    }
219
220    // Try the ObjectContainer plug-ins
221    for (i = 0; (callback = PluginManager::GetObjectContainerGetModuleSpecificationsCallbackAtIndex(i)) != NULL; ++i)
222    {
223        if (callback (file, data_sp, data_offset, file_offset, length, specs) > 0)
224            return specs.GetSize() - initial_count;
225    }
226    return 0;
227}
228
229ObjectFile::ObjectFile (const lldb::ModuleSP &module_sp,
230                        const FileSpec *file_spec_ptr,
231                        lldb::offset_t file_offset,
232                        lldb::offset_t length,
233                        lldb::DataBufferSP& data_sp,
234                        lldb::offset_t data_offset
235) :
236    ModuleChild (module_sp),
237    m_file (),  // This file could be different from the original module's file
238    m_type (eTypeInvalid),
239    m_strata (eStrataInvalid),
240    m_file_offset (file_offset),
241    m_length (length),
242    m_data (),
243    m_unwind_table (*this),
244    m_process_wp(),
245    m_memory_addr (LLDB_INVALID_ADDRESS),
246    m_sections_ap (),
247    m_symtab_ap ()
248{
249    if (file_spec_ptr)
250        m_file = *file_spec_ptr;
251    if (data_sp)
252        m_data.SetData (data_sp, data_offset, length);
253    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
254    if (log)
255    {
256        if (m_file)
257        {
258            log->Printf ("%p ObjectFile::ObjectFile() module = %p (%s), file = %s, file_offset = 0x%8.8" PRIx64 ", size = %" PRIu64,
259                         this,
260                         module_sp.get(),
261                         module_sp->GetSpecificationDescription().c_str(),
262                         m_file.GetPath().c_str(),
263                         m_file_offset,
264                         m_length);
265        }
266        else
267        {
268            log->Printf ("%p ObjectFile::ObjectFile() module = %p (%s), file = <NULL>, file_offset = 0x%8.8" PRIx64 ", size = %" PRIu64,
269                         this,
270                         module_sp.get(),
271                         module_sp->GetSpecificationDescription().c_str(),
272                         m_file_offset,
273                         m_length);
274        }
275    }
276}
277
278
279ObjectFile::ObjectFile (const lldb::ModuleSP &module_sp,
280                        const ProcessSP &process_sp,
281                        lldb::addr_t header_addr,
282                        DataBufferSP& header_data_sp) :
283    ModuleChild (module_sp),
284    m_file (),
285    m_type (eTypeInvalid),
286    m_strata (eStrataInvalid),
287    m_file_offset (0),
288    m_length (0),
289    m_data (),
290    m_unwind_table (*this),
291    m_process_wp (process_sp),
292    m_memory_addr (header_addr),
293    m_sections_ap (),
294    m_symtab_ap ()
295{
296    if (header_data_sp)
297        m_data.SetData (header_data_sp, 0, header_data_sp->GetByteSize());
298    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
299    if (log)
300    {
301        log->Printf ("%p ObjectFile::ObjectFile() module = %p (%s), process = %p, header_addr = 0x%" PRIx64,
302                     this,
303                     module_sp.get(),
304                     module_sp->GetSpecificationDescription().c_str(),
305                     process_sp.get(),
306                     m_memory_addr);
307    }
308}
309
310
311ObjectFile::~ObjectFile()
312{
313    Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
314    if (log)
315        log->Printf ("%p ObjectFile::~ObjectFile ()\n", this);
316}
317
318bool
319ObjectFile::SetModulesArchitecture (const ArchSpec &new_arch)
320{
321    ModuleSP module_sp (GetModule());
322    if (module_sp)
323        return module_sp->SetArchitecture (new_arch);
324    return false;
325}
326
327AddressClass
328ObjectFile::GetAddressClass (addr_t file_addr)
329{
330    Symtab *symtab = GetSymtab();
331    if (symtab)
332    {
333        Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
334        if (symbol)
335        {
336            if (symbol->ValueIsAddress())
337            {
338                const SectionSP section_sp (symbol->GetAddress().GetSection());
339                if (section_sp)
340                {
341                    const SectionType section_type = section_sp->GetType();
342                    switch (section_type)
343                    {
344                    case eSectionTypeInvalid:               return eAddressClassUnknown;
345                    case eSectionTypeCode:                  return eAddressClassCode;
346                    case eSectionTypeContainer:             return eAddressClassUnknown;
347                    case eSectionTypeData:
348                    case eSectionTypeDataCString:
349                    case eSectionTypeDataCStringPointers:
350                    case eSectionTypeDataSymbolAddress:
351                    case eSectionTypeData4:
352                    case eSectionTypeData8:
353                    case eSectionTypeData16:
354                    case eSectionTypeDataPointers:
355                    case eSectionTypeZeroFill:
356                    case eSectionTypeDataObjCMessageRefs:
357                    case eSectionTypeDataObjCCFStrings:
358                        return eAddressClassData;
359                    case eSectionTypeDebug:
360                    case eSectionTypeDWARFDebugAbbrev:
361                    case eSectionTypeDWARFDebugAranges:
362                    case eSectionTypeDWARFDebugFrame:
363                    case eSectionTypeDWARFDebugInfo:
364                    case eSectionTypeDWARFDebugLine:
365                    case eSectionTypeDWARFDebugLoc:
366                    case eSectionTypeDWARFDebugMacInfo:
367                    case eSectionTypeDWARFDebugPubNames:
368                    case eSectionTypeDWARFDebugPubTypes:
369                    case eSectionTypeDWARFDebugRanges:
370                    case eSectionTypeDWARFDebugStr:
371                    case eSectionTypeDWARFAppleNames:
372                    case eSectionTypeDWARFAppleTypes:
373                    case eSectionTypeDWARFAppleNamespaces:
374                    case eSectionTypeDWARFAppleObjC:
375                        return eAddressClassDebug;
376                    case eSectionTypeEHFrame:               return eAddressClassRuntime;
377                    case eSectionTypeOther:                 return eAddressClassUnknown;
378                    }
379                }
380            }
381
382            const SymbolType symbol_type = symbol->GetType();
383            switch (symbol_type)
384            {
385            case eSymbolTypeAny:            return eAddressClassUnknown;
386            case eSymbolTypeAbsolute:       return eAddressClassUnknown;
387            case eSymbolTypeCode:           return eAddressClassCode;
388            case eSymbolTypeTrampoline:     return eAddressClassCode;
389            case eSymbolTypeResolver:       return eAddressClassCode;
390            case eSymbolTypeData:           return eAddressClassData;
391            case eSymbolTypeRuntime:        return eAddressClassRuntime;
392            case eSymbolTypeException:      return eAddressClassRuntime;
393            case eSymbolTypeSourceFile:     return eAddressClassDebug;
394            case eSymbolTypeHeaderFile:     return eAddressClassDebug;
395            case eSymbolTypeObjectFile:     return eAddressClassDebug;
396            case eSymbolTypeCommonBlock:    return eAddressClassDebug;
397            case eSymbolTypeBlock:          return eAddressClassDebug;
398            case eSymbolTypeLocal:          return eAddressClassData;
399            case eSymbolTypeParam:          return eAddressClassData;
400            case eSymbolTypeVariable:       return eAddressClassData;
401            case eSymbolTypeVariableType:   return eAddressClassDebug;
402            case eSymbolTypeLineEntry:      return eAddressClassDebug;
403            case eSymbolTypeLineHeader:     return eAddressClassDebug;
404            case eSymbolTypeScopeBegin:     return eAddressClassDebug;
405            case eSymbolTypeScopeEnd:       return eAddressClassDebug;
406            case eSymbolTypeAdditional:     return eAddressClassUnknown;
407            case eSymbolTypeCompiler:       return eAddressClassDebug;
408            case eSymbolTypeInstrumentation:return eAddressClassDebug;
409            case eSymbolTypeUndefined:      return eAddressClassUnknown;
410            case eSymbolTypeObjCClass:      return eAddressClassRuntime;
411            case eSymbolTypeObjCMetaClass:  return eAddressClassRuntime;
412            case eSymbolTypeObjCIVar:       return eAddressClassRuntime;
413            }
414        }
415    }
416    return eAddressClassUnknown;
417}
418
419DataBufferSP
420ObjectFile::ReadMemory (const ProcessSP &process_sp, lldb::addr_t addr, size_t byte_size)
421{
422    DataBufferSP data_sp;
423    if (process_sp)
424    {
425        std::unique_ptr<DataBufferHeap> data_ap (new DataBufferHeap (byte_size, 0));
426        Error error;
427        const size_t bytes_read = process_sp->ReadMemory (addr,
428                                                          data_ap->GetBytes(),
429                                                          data_ap->GetByteSize(),
430                                                          error);
431        if (bytes_read == byte_size)
432            data_sp.reset (data_ap.release());
433    }
434    return data_sp;
435}
436
437size_t
438ObjectFile::GetData (off_t offset, size_t length, DataExtractor &data) const
439{
440    // The entire file has already been mmap'ed into m_data, so just copy from there
441    // as the back mmap buffer will be shared with shared pointers.
442    return data.SetData (m_data, offset, length);
443}
444
445size_t
446ObjectFile::CopyData (off_t offset, size_t length, void *dst) const
447{
448    // The entire file has already been mmap'ed into m_data, so just copy from there
449    return m_data.CopyByteOrderedData (offset, length, dst, length, lldb::endian::InlHostByteOrder());
450}
451
452
453size_t
454ObjectFile::ReadSectionData (const Section *section, off_t section_offset, void *dst, size_t dst_len) const
455{
456    if (IsInMemory())
457    {
458        ProcessSP process_sp (m_process_wp.lock());
459        if (process_sp)
460        {
461            Error error;
462            const addr_t base_load_addr = section->GetLoadBaseAddress (&process_sp->GetTarget());
463            if (base_load_addr != LLDB_INVALID_ADDRESS)
464                return process_sp->ReadMemory (base_load_addr + section_offset, dst, dst_len, error);
465        }
466    }
467    else
468    {
469        const uint64_t section_file_size = section->GetFileSize();
470        if (section_offset < section_file_size)
471        {
472            const uint64_t section_bytes_left = section_file_size - section_offset;
473            uint64_t section_dst_len = dst_len;
474            if (section_dst_len > section_bytes_left)
475                section_dst_len = section_bytes_left;
476            return CopyData (section->GetFileOffset() + section_offset, section_dst_len, dst);
477        }
478        else
479        {
480            if (section->GetType() == eSectionTypeZeroFill)
481            {
482                const uint64_t section_size = section->GetByteSize();
483                const uint64_t section_bytes_left = section_size - section_offset;
484                uint64_t section_dst_len = dst_len;
485                if (section_dst_len > section_bytes_left)
486                    section_dst_len = section_bytes_left;
487                bzero(dst, section_dst_len);
488                return section_dst_len;
489            }
490        }
491    }
492    return 0;
493}
494
495//----------------------------------------------------------------------
496// Get the section data the file on disk
497//----------------------------------------------------------------------
498size_t
499ObjectFile::ReadSectionData (const Section *section, DataExtractor& section_data) const
500{
501    if (IsInMemory())
502    {
503        ProcessSP process_sp (m_process_wp.lock());
504        if (process_sp)
505        {
506            const addr_t base_load_addr = section->GetLoadBaseAddress (&process_sp->GetTarget());
507            if (base_load_addr != LLDB_INVALID_ADDRESS)
508            {
509                DataBufferSP data_sp (ReadMemory (process_sp, base_load_addr, section->GetByteSize()));
510                if (data_sp)
511                {
512                    section_data.SetData (data_sp, 0, data_sp->GetByteSize());
513                    section_data.SetByteOrder (process_sp->GetByteOrder());
514                    section_data.SetAddressByteSize (process_sp->GetAddressByteSize());
515                    return section_data.GetByteSize();
516                }
517            }
518        }
519    }
520    else
521    {
522        // The object file now contains a full mmap'ed copy of the object file data, so just use this
523        return MemoryMapSectionData (section, section_data);
524    }
525    section_data.Clear();
526    return 0;
527}
528
529size_t
530ObjectFile::MemoryMapSectionData (const Section *section, DataExtractor& section_data) const
531{
532    if (IsInMemory())
533    {
534        return ReadSectionData (section, section_data);
535    }
536    else
537    {
538        // The object file now contains a full mmap'ed copy of the object file data, so just use this
539        return GetData(section->GetFileOffset(), section->GetFileSize(), section_data);
540    }
541    section_data.Clear();
542    return 0;
543}
544
545
546bool
547ObjectFile::SplitArchivePathWithObject (const char *path_with_object, FileSpec &archive_file, ConstString &archive_object, bool must_exist)
548{
549    RegularExpression g_object_regex("(.*)\\(([^\\)]+)\\)$");
550    RegularExpression::Match regex_match(2);
551    if (g_object_regex.Execute (path_with_object, &regex_match))
552    {
553        std::string path;
554        std::string obj;
555        if (regex_match.GetMatchAtIndex (path_with_object, 1, path) &&
556            regex_match.GetMatchAtIndex (path_with_object, 2, obj))
557        {
558            archive_file.SetFile (path.c_str(), false);
559            archive_object.SetCString(obj.c_str());
560            if (must_exist && !archive_file.Exists())
561                return false;
562            return true;
563        }
564    }
565    return false;
566}
567
568void
569ObjectFile::ClearSymtab ()
570{
571    ModuleSP module_sp(GetModule());
572    if (module_sp)
573    {
574        lldb_private::Mutex::Locker locker(module_sp->GetMutex());
575        Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
576        if (log)
577        {
578            log->Printf ("%p ObjectFile::ClearSymtab () symtab = %p",
579                         this,
580                         m_symtab_ap.get());
581        }
582        m_symtab_ap.reset();
583    }
584}
585