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/PluginManager.h"
17 #include "lldb/Core/RegularExpression.h"
18 #include "lldb/Core/Section.h"
19 #include "lldb/Core/Timer.h"
20 #include "lldb/Symbol/ObjectFile.h"
21 #include "lldb/Symbol/ObjectContainer.h"
22 #include "lldb/Symbol/SymbolFile.h"
23 #include "lldb/Target/Process.h"
24 #include "Plugins/ObjectContainer/BSD-Archive/ObjectContainerBSDArchive.h"
25 
26 using namespace lldb;
27 using namespace lldb_private;
28 
29 ObjectFileSP
30 ObjectFile::FindPlugin (const lldb::ModuleSP &module_sp,
31                         const FileSpec* file,
32                         lldb::offset_t file_offset,
33                         lldb::offset_t file_size,
34                         DataBufferSP &data_sp,
35                         lldb::offset_t &data_offset)
36 {
37     ObjectFileSP object_file_sp;
38 
39     if (module_sp)
40     {
41         Timer scoped_timer (__PRETTY_FUNCTION__,
42                             "ObjectFile::FindPlugin (module = %s/%s, file = %p, file_offset = 0x%8.8" PRIx64 ", file_size = 0x%8.8" PRIx64 ")",
43                             module_sp->GetFileSpec().GetDirectory().AsCString(),
44                             module_sp->GetFileSpec().GetFilename().AsCString(),
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::auto_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::auto_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::auto_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 
153 ObjectFileSP
154 ObjectFile::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/%s, process = %p, header_addr = 0x%" PRIx64 ")",
165                             module_sp->GetFileSpec().GetDirectory().AsCString(),
166                             module_sp->GetFileSpec().GetFilename().AsCString(),
167                             process_sp.get(), header_addr);
168         uint32_t idx;
169 
170         // Check if this is a normal object file by iterating through
171         // all object file plugin instances.
172         ObjectFileCreateMemoryInstance create_callback;
173         for (idx = 0; (create_callback = PluginManager::GetObjectFileCreateMemoryCallbackAtIndex(idx)) != NULL; ++idx)
174         {
175             object_file_sp.reset (create_callback(module_sp, data_sp, process_sp, header_addr));
176             if (object_file_sp.get())
177                 return object_file_sp;
178         }
179 
180     }
181     // We didn't find it, so clear our shared pointer in case it
182     // contains anything and return an empty shared pointer
183     object_file_sp.reset();
184     return object_file_sp;
185 }
186 
187 ObjectFile::ObjectFile (const lldb::ModuleSP &module_sp,
188                         const FileSpec *file_spec_ptr,
189                         lldb::offset_t file_offset,
190                         lldb::offset_t length,
191                         lldb::DataBufferSP& data_sp,
192                         lldb::offset_t data_offset
193 ) :
194     ModuleChild (module_sp),
195     m_file (),  // This file could be different from the original module's file
196     m_type (eTypeInvalid),
197     m_strata (eStrataInvalid),
198     m_file_offset (file_offset),
199     m_length (length),
200     m_data (),
201     m_unwind_table (*this),
202     m_process_wp(),
203     m_memory_addr (LLDB_INVALID_ADDRESS)
204 {
205     if (file_spec_ptr)
206         m_file = *file_spec_ptr;
207     if (data_sp)
208         m_data.SetData (data_sp, data_offset, length);
209     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
210     if (log)
211     {
212         if (m_file)
213         {
214             log->Printf ("%p ObjectFile::ObjectFile () module = %s/%s, file = %s/%s, file_offset = 0x%8.8" PRIx64 ", size = %" PRIu64 "\n",
215                          this,
216                          module_sp->GetFileSpec().GetDirectory().AsCString(),
217                          module_sp->GetFileSpec().GetFilename().AsCString(),
218                          m_file.GetDirectory().AsCString(),
219                          m_file.GetFilename().AsCString(),
220                          m_file_offset,
221                          m_length);
222         }
223         else
224         {
225             log->Printf ("%p ObjectFile::ObjectFile () module = %s/%s, file = <NULL>, file_offset = 0x%8.8" PRIx64 ", size = %" PRIu64 "\n",
226                          this,
227                          module_sp->GetFileSpec().GetDirectory().AsCString(),
228                          module_sp->GetFileSpec().GetFilename().AsCString(),
229                          m_file_offset,
230                          m_length);
231         }
232     }
233 }
234 
235 
236 ObjectFile::ObjectFile (const lldb::ModuleSP &module_sp,
237                         const ProcessSP &process_sp,
238                         lldb::addr_t header_addr,
239                         DataBufferSP& header_data_sp) :
240     ModuleChild (module_sp),
241     m_file (),
242     m_type (eTypeInvalid),
243     m_strata (eStrataInvalid),
244     m_file_offset (0),
245     m_length (0),
246     m_data (),
247     m_unwind_table (*this),
248     m_process_wp (process_sp),
249     m_memory_addr (header_addr)
250 {
251     if (header_data_sp)
252         m_data.SetData (header_data_sp, 0, header_data_sp->GetByteSize());
253     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
254     if (log)
255     {
256         log->Printf ("%p ObjectFile::ObjectFile () module = %s/%s, process = %p, header_addr = 0x%" PRIx64 "\n",
257                      this,
258                      module_sp->GetFileSpec().GetDirectory().AsCString(),
259                      module_sp->GetFileSpec().GetFilename().AsCString(),
260                      process_sp.get(),
261                      m_memory_addr);
262     }
263 }
264 
265 
266 ObjectFile::~ObjectFile()
267 {
268     LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
269     if (log)
270         log->Printf ("%p ObjectFile::~ObjectFile ()\n", this);
271 }
272 
273 bool
274 ObjectFile::SetModulesArchitecture (const ArchSpec &new_arch)
275 {
276     ModuleSP module_sp (GetModule());
277     if (module_sp)
278         return module_sp->SetArchitecture (new_arch);
279     return false;
280 }
281 
282 AddressClass
283 ObjectFile::GetAddressClass (addr_t file_addr)
284 {
285     Symtab *symtab = GetSymtab();
286     if (symtab)
287     {
288         Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
289         if (symbol)
290         {
291             if (symbol->ValueIsAddress())
292             {
293                 const SectionSP section_sp (symbol->GetAddress().GetSection());
294                 if (section_sp)
295                 {
296                     const SectionType section_type = section_sp->GetType();
297                     switch (section_type)
298                     {
299                     case eSectionTypeInvalid:               return eAddressClassUnknown;
300                     case eSectionTypeCode:                  return eAddressClassCode;
301                     case eSectionTypeContainer:             return eAddressClassUnknown;
302                     case eSectionTypeData:
303                     case eSectionTypeDataCString:
304                     case eSectionTypeDataCStringPointers:
305                     case eSectionTypeDataSymbolAddress:
306                     case eSectionTypeData4:
307                     case eSectionTypeData8:
308                     case eSectionTypeData16:
309                     case eSectionTypeDataPointers:
310                     case eSectionTypeZeroFill:
311                     case eSectionTypeDataObjCMessageRefs:
312                     case eSectionTypeDataObjCCFStrings:
313                         return eAddressClassData;
314                     case eSectionTypeDebug:
315                     case eSectionTypeDWARFDebugAbbrev:
316                     case eSectionTypeDWARFDebugAranges:
317                     case eSectionTypeDWARFDebugFrame:
318                     case eSectionTypeDWARFDebugInfo:
319                     case eSectionTypeDWARFDebugLine:
320                     case eSectionTypeDWARFDebugLoc:
321                     case eSectionTypeDWARFDebugMacInfo:
322                     case eSectionTypeDWARFDebugPubNames:
323                     case eSectionTypeDWARFDebugPubTypes:
324                     case eSectionTypeDWARFDebugRanges:
325                     case eSectionTypeDWARFDebugStr:
326                     case eSectionTypeDWARFAppleNames:
327                     case eSectionTypeDWARFAppleTypes:
328                     case eSectionTypeDWARFAppleNamespaces:
329                     case eSectionTypeDWARFAppleObjC:
330                         return eAddressClassDebug;
331                     case eSectionTypeEHFrame:               return eAddressClassRuntime;
332                     case eSectionTypeOther:                 return eAddressClassUnknown;
333                     }
334                 }
335             }
336 
337             const SymbolType symbol_type = symbol->GetType();
338             switch (symbol_type)
339             {
340             case eSymbolTypeAny:            return eAddressClassUnknown;
341             case eSymbolTypeAbsolute:       return eAddressClassUnknown;
342             case eSymbolTypeCode:           return eAddressClassCode;
343             case eSymbolTypeTrampoline:     return eAddressClassCode;
344             case eSymbolTypeData:           return eAddressClassData;
345             case eSymbolTypeRuntime:        return eAddressClassRuntime;
346             case eSymbolTypeException:      return eAddressClassRuntime;
347             case eSymbolTypeSourceFile:     return eAddressClassDebug;
348             case eSymbolTypeHeaderFile:     return eAddressClassDebug;
349             case eSymbolTypeObjectFile:     return eAddressClassDebug;
350             case eSymbolTypeCommonBlock:    return eAddressClassDebug;
351             case eSymbolTypeBlock:          return eAddressClassDebug;
352             case eSymbolTypeLocal:          return eAddressClassData;
353             case eSymbolTypeParam:          return eAddressClassData;
354             case eSymbolTypeVariable:       return eAddressClassData;
355             case eSymbolTypeVariableType:   return eAddressClassDebug;
356             case eSymbolTypeLineEntry:      return eAddressClassDebug;
357             case eSymbolTypeLineHeader:     return eAddressClassDebug;
358             case eSymbolTypeScopeBegin:     return eAddressClassDebug;
359             case eSymbolTypeScopeEnd:       return eAddressClassDebug;
360             case eSymbolTypeAdditional:     return eAddressClassUnknown;
361             case eSymbolTypeCompiler:       return eAddressClassDebug;
362             case eSymbolTypeInstrumentation:return eAddressClassDebug;
363             case eSymbolTypeUndefined:      return eAddressClassUnknown;
364             case eSymbolTypeObjCClass:      return eAddressClassRuntime;
365             case eSymbolTypeObjCMetaClass:  return eAddressClassRuntime;
366             case eSymbolTypeObjCIVar:       return eAddressClassRuntime;
367             }
368         }
369     }
370     return eAddressClassUnknown;
371 }
372 
373 DataBufferSP
374 ObjectFile::ReadMemory (const ProcessSP &process_sp, lldb::addr_t addr, size_t byte_size)
375 {
376     DataBufferSP data_sp;
377     if (process_sp)
378     {
379         std::auto_ptr<DataBufferHeap> data_ap (new DataBufferHeap (byte_size, 0));
380         Error error;
381         const size_t bytes_read = process_sp->ReadMemory (addr,
382                                                           data_ap->GetBytes(),
383                                                           data_ap->GetByteSize(),
384                                                           error);
385         if (bytes_read == byte_size)
386             data_sp.reset (data_ap.release());
387     }
388     return data_sp;
389 }
390 
391 size_t
392 ObjectFile::GetData (off_t offset, size_t length, DataExtractor &data) const
393 {
394     // The entire file has already been mmap'ed into m_data, so just copy from there
395     // as the back mmap buffer will be shared with shared pointers.
396     return data.SetData (m_data, offset, length);
397 }
398 
399 size_t
400 ObjectFile::CopyData (off_t offset, size_t length, void *dst) const
401 {
402     // The entire file has already been mmap'ed into m_data, so just copy from there
403     return m_data.CopyByteOrderedData (offset, length, dst, length, lldb::endian::InlHostByteOrder());
404 }
405 
406 
407 size_t
408 ObjectFile::ReadSectionData (const Section *section, off_t section_offset, void *dst, size_t dst_len) const
409 {
410     if (IsInMemory())
411     {
412         ProcessSP process_sp (m_process_wp.lock());
413         if (process_sp)
414         {
415             Error error;
416             const addr_t base_load_addr = section->GetLoadBaseAddress (&process_sp->GetTarget());
417             if (base_load_addr != LLDB_INVALID_ADDRESS)
418                 return process_sp->ReadMemory (base_load_addr + section_offset, dst, dst_len, error);
419         }
420     }
421     else
422     {
423         const uint64_t section_file_size = section->GetFileSize();
424         if (section_offset < section_file_size)
425         {
426             const uint64_t section_bytes_left = section_file_size - section_offset;
427             uint64_t section_dst_len = dst_len;
428             if (section_dst_len > section_bytes_left)
429                 section_dst_len = section_bytes_left;
430             return CopyData (section->GetFileOffset() + section_offset, section_dst_len, dst);
431         }
432         else
433         {
434             if (section->GetType() == eSectionTypeZeroFill)
435             {
436                 const uint64_t section_size = section->GetByteSize();
437                 const uint64_t section_bytes_left = section_size - section_offset;
438                 uint64_t section_dst_len = dst_len;
439                 if (section_dst_len > section_bytes_left)
440                     section_dst_len = section_bytes_left;
441                 bzero(dst, section_dst_len);
442                 return section_dst_len;
443             }
444         }
445     }
446     return 0;
447 }
448 
449 //----------------------------------------------------------------------
450 // Get the section data the file on disk
451 //----------------------------------------------------------------------
452 size_t
453 ObjectFile::ReadSectionData (const Section *section, DataExtractor& section_data) const
454 {
455     if (IsInMemory())
456     {
457         ProcessSP process_sp (m_process_wp.lock());
458         if (process_sp)
459         {
460             const addr_t base_load_addr = section->GetLoadBaseAddress (&process_sp->GetTarget());
461             if (base_load_addr != LLDB_INVALID_ADDRESS)
462             {
463                 DataBufferSP data_sp (ReadMemory (process_sp, base_load_addr, section->GetByteSize()));
464                 if (data_sp)
465                 {
466                     section_data.SetData (data_sp, 0, data_sp->GetByteSize());
467                     section_data.SetByteOrder (process_sp->GetByteOrder());
468                     section_data.SetAddressByteSize (process_sp->GetAddressByteSize());
469                     return section_data.GetByteSize();
470                 }
471             }
472         }
473     }
474     else
475     {
476         // The object file now contains a full mmap'ed copy of the object file data, so just use this
477         return MemoryMapSectionData (section, section_data);
478     }
479     section_data.Clear();
480     return 0;
481 }
482 
483 size_t
484 ObjectFile::MemoryMapSectionData (const Section *section, DataExtractor& section_data) const
485 {
486     if (IsInMemory())
487     {
488         return ReadSectionData (section, section_data);
489     }
490     else
491     {
492         // The object file now contains a full mmap'ed copy of the object file data, so just use this
493         return GetData(section->GetFileOffset(), section->GetFileSize(), section_data);
494     }
495     section_data.Clear();
496     return 0;
497 }
498 
499 
500 bool
501 ObjectFile::SplitArchivePathWithObject (const char *path_with_object, FileSpec &archive_file, ConstString &archive_object, bool must_exist)
502 {
503     RegularExpression g_object_regex("(.*)\\(([^\\)]+)\\)$");
504     if (g_object_regex.Execute (path_with_object, 2))
505     {
506         std::string path;
507         std::string obj;
508         if (g_object_regex.GetMatchAtIndex (path_with_object, 1, path) &&
509             g_object_regex.GetMatchAtIndex (path_with_object, 2, obj))
510         {
511             archive_file.SetFile (path.c_str(), false);
512             archive_object.SetCString(obj.c_str());
513             if (must_exist && !archive_file.Exists())
514                 return false;
515             return true;
516         }
517     }
518     return false;
519 }
520 
521