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     m_sections_ap (),
205     m_symtab_ap ()
206 {
207     if (file_spec_ptr)
208         m_file = *file_spec_ptr;
209     if (data_sp)
210         m_data.SetData (data_sp, data_offset, length);
211     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
212     if (log)
213     {
214         const ConstString object_name (module_sp->GetObjectName());
215         if (m_file)
216         {
217             log->Printf ("%p ObjectFile::ObjectFile() module = %p (%s%s%s%s), file = %s/%s, file_offset = 0x%8.8" PRIx64 ", size = %" PRIu64,
218                          this,
219                          module_sp.get(),
220                          module_sp->GetFileSpec().GetFilename().AsCString(),
221                          object_name ? "(" : "",
222                          object_name ? object_name.GetCString() : "",
223                          object_name ? ")" : "",
224                          m_file.GetDirectory().AsCString(),
225                          m_file.GetFilename().AsCString(),
226                          m_file_offset,
227                          m_length);
228         }
229         else
230         {
231             log->Printf ("%p ObjectFile::ObjectFile() module = %p (%s%s%s%s), file = <NULL>, file_offset = 0x%8.8" PRIx64 ", size = %" PRIu64,
232                          this,
233                          module_sp.get(),
234                          module_sp->GetFileSpec().GetFilename().AsCString(),
235                          object_name ? "(" : "",
236                          object_name ? object_name.GetCString() : "",
237                          object_name ? ")" : "",
238                          m_file_offset,
239                          m_length);
240         }
241     }
242 }
243 
244 
245 ObjectFile::ObjectFile (const lldb::ModuleSP &module_sp,
246                         const ProcessSP &process_sp,
247                         lldb::addr_t header_addr,
248                         DataBufferSP& header_data_sp) :
249     ModuleChild (module_sp),
250     m_file (),
251     m_type (eTypeInvalid),
252     m_strata (eStrataInvalid),
253     m_file_offset (0),
254     m_length (0),
255     m_data (),
256     m_unwind_table (*this),
257     m_process_wp (process_sp),
258     m_memory_addr (header_addr),
259     m_sections_ap (),
260     m_symtab_ap ()
261 {
262     if (header_data_sp)
263         m_data.SetData (header_data_sp, 0, header_data_sp->GetByteSize());
264     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
265     if (log)
266     {
267         const ConstString object_name (module_sp->GetObjectName());
268         log->Printf ("%p ObjectFile::ObjectFile() module = %p (%s%s%s%s), process = %p, header_addr = 0x%" PRIx64,
269                      this,
270                      module_sp.get(),
271                      module_sp->GetFileSpec().GetFilename().AsCString(),
272                      object_name ? "(" : "",
273                      object_name ? object_name.GetCString() : "",
274                      object_name ? ")" : "",
275                      process_sp.get(),
276                      m_memory_addr);
277     }
278 }
279 
280 
281 ObjectFile::~ObjectFile()
282 {
283     Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
284     if (log)
285         log->Printf ("%p ObjectFile::~ObjectFile ()\n", this);
286 }
287 
288 bool
289 ObjectFile::SetModulesArchitecture (const ArchSpec &new_arch)
290 {
291     ModuleSP module_sp (GetModule());
292     if (module_sp)
293         return module_sp->SetArchitecture (new_arch);
294     return false;
295 }
296 
297 AddressClass
298 ObjectFile::GetAddressClass (addr_t file_addr)
299 {
300     Symtab *symtab = GetSymtab();
301     if (symtab)
302     {
303         Symbol *symbol = symtab->FindSymbolContainingFileAddress(file_addr);
304         if (symbol)
305         {
306             if (symbol->ValueIsAddress())
307             {
308                 const SectionSP section_sp (symbol->GetAddress().GetSection());
309                 if (section_sp)
310                 {
311                     const SectionType section_type = section_sp->GetType();
312                     switch (section_type)
313                     {
314                     case eSectionTypeInvalid:               return eAddressClassUnknown;
315                     case eSectionTypeCode:                  return eAddressClassCode;
316                     case eSectionTypeContainer:             return eAddressClassUnknown;
317                     case eSectionTypeData:
318                     case eSectionTypeDataCString:
319                     case eSectionTypeDataCStringPointers:
320                     case eSectionTypeDataSymbolAddress:
321                     case eSectionTypeData4:
322                     case eSectionTypeData8:
323                     case eSectionTypeData16:
324                     case eSectionTypeDataPointers:
325                     case eSectionTypeZeroFill:
326                     case eSectionTypeDataObjCMessageRefs:
327                     case eSectionTypeDataObjCCFStrings:
328                         return eAddressClassData;
329                     case eSectionTypeDebug:
330                     case eSectionTypeDWARFDebugAbbrev:
331                     case eSectionTypeDWARFDebugAranges:
332                     case eSectionTypeDWARFDebugFrame:
333                     case eSectionTypeDWARFDebugInfo:
334                     case eSectionTypeDWARFDebugLine:
335                     case eSectionTypeDWARFDebugLoc:
336                     case eSectionTypeDWARFDebugMacInfo:
337                     case eSectionTypeDWARFDebugPubNames:
338                     case eSectionTypeDWARFDebugPubTypes:
339                     case eSectionTypeDWARFDebugRanges:
340                     case eSectionTypeDWARFDebugStr:
341                     case eSectionTypeDWARFAppleNames:
342                     case eSectionTypeDWARFAppleTypes:
343                     case eSectionTypeDWARFAppleNamespaces:
344                     case eSectionTypeDWARFAppleObjC:
345                         return eAddressClassDebug;
346                     case eSectionTypeEHFrame:               return eAddressClassRuntime;
347                     case eSectionTypeOther:                 return eAddressClassUnknown;
348                     }
349                 }
350             }
351 
352             const SymbolType symbol_type = symbol->GetType();
353             switch (symbol_type)
354             {
355             case eSymbolTypeAny:            return eAddressClassUnknown;
356             case eSymbolTypeAbsolute:       return eAddressClassUnknown;
357             case eSymbolTypeCode:           return eAddressClassCode;
358             case eSymbolTypeTrampoline:     return eAddressClassCode;
359             case eSymbolTypeResolver:       return eAddressClassCode;
360             case eSymbolTypeData:           return eAddressClassData;
361             case eSymbolTypeRuntime:        return eAddressClassRuntime;
362             case eSymbolTypeException:      return eAddressClassRuntime;
363             case eSymbolTypeSourceFile:     return eAddressClassDebug;
364             case eSymbolTypeHeaderFile:     return eAddressClassDebug;
365             case eSymbolTypeObjectFile:     return eAddressClassDebug;
366             case eSymbolTypeCommonBlock:    return eAddressClassDebug;
367             case eSymbolTypeBlock:          return eAddressClassDebug;
368             case eSymbolTypeLocal:          return eAddressClassData;
369             case eSymbolTypeParam:          return eAddressClassData;
370             case eSymbolTypeVariable:       return eAddressClassData;
371             case eSymbolTypeVariableType:   return eAddressClassDebug;
372             case eSymbolTypeLineEntry:      return eAddressClassDebug;
373             case eSymbolTypeLineHeader:     return eAddressClassDebug;
374             case eSymbolTypeScopeBegin:     return eAddressClassDebug;
375             case eSymbolTypeScopeEnd:       return eAddressClassDebug;
376             case eSymbolTypeAdditional:     return eAddressClassUnknown;
377             case eSymbolTypeCompiler:       return eAddressClassDebug;
378             case eSymbolTypeInstrumentation:return eAddressClassDebug;
379             case eSymbolTypeUndefined:      return eAddressClassUnknown;
380             case eSymbolTypeObjCClass:      return eAddressClassRuntime;
381             case eSymbolTypeObjCMetaClass:  return eAddressClassRuntime;
382             case eSymbolTypeObjCIVar:       return eAddressClassRuntime;
383             }
384         }
385     }
386     return eAddressClassUnknown;
387 }
388 
389 DataBufferSP
390 ObjectFile::ReadMemory (const ProcessSP &process_sp, lldb::addr_t addr, size_t byte_size)
391 {
392     DataBufferSP data_sp;
393     if (process_sp)
394     {
395         std::auto_ptr<DataBufferHeap> data_ap (new DataBufferHeap (byte_size, 0));
396         Error error;
397         const size_t bytes_read = process_sp->ReadMemory (addr,
398                                                           data_ap->GetBytes(),
399                                                           data_ap->GetByteSize(),
400                                                           error);
401         if (bytes_read == byte_size)
402             data_sp.reset (data_ap.release());
403     }
404     return data_sp;
405 }
406 
407 size_t
408 ObjectFile::GetData (off_t offset, size_t length, DataExtractor &data) const
409 {
410     // The entire file has already been mmap'ed into m_data, so just copy from there
411     // as the back mmap buffer will be shared with shared pointers.
412     return data.SetData (m_data, offset, length);
413 }
414 
415 size_t
416 ObjectFile::CopyData (off_t offset, size_t length, void *dst) const
417 {
418     // The entire file has already been mmap'ed into m_data, so just copy from there
419     return m_data.CopyByteOrderedData (offset, length, dst, length, lldb::endian::InlHostByteOrder());
420 }
421 
422 
423 size_t
424 ObjectFile::ReadSectionData (const Section *section, off_t section_offset, void *dst, size_t dst_len) const
425 {
426     if (IsInMemory())
427     {
428         ProcessSP process_sp (m_process_wp.lock());
429         if (process_sp)
430         {
431             Error error;
432             const addr_t base_load_addr = section->GetLoadBaseAddress (&process_sp->GetTarget());
433             if (base_load_addr != LLDB_INVALID_ADDRESS)
434                 return process_sp->ReadMemory (base_load_addr + section_offset, dst, dst_len, error);
435         }
436     }
437     else
438     {
439         const uint64_t section_file_size = section->GetFileSize();
440         if (section_offset < section_file_size)
441         {
442             const uint64_t section_bytes_left = section_file_size - section_offset;
443             uint64_t section_dst_len = dst_len;
444             if (section_dst_len > section_bytes_left)
445                 section_dst_len = section_bytes_left;
446             return CopyData (section->GetFileOffset() + section_offset, section_dst_len, dst);
447         }
448         else
449         {
450             if (section->GetType() == eSectionTypeZeroFill)
451             {
452                 const uint64_t section_size = section->GetByteSize();
453                 const uint64_t section_bytes_left = section_size - section_offset;
454                 uint64_t section_dst_len = dst_len;
455                 if (section_dst_len > section_bytes_left)
456                     section_dst_len = section_bytes_left;
457                 bzero(dst, section_dst_len);
458                 return section_dst_len;
459             }
460         }
461     }
462     return 0;
463 }
464 
465 //----------------------------------------------------------------------
466 // Get the section data the file on disk
467 //----------------------------------------------------------------------
468 size_t
469 ObjectFile::ReadSectionData (const Section *section, DataExtractor& section_data) const
470 {
471     if (IsInMemory())
472     {
473         ProcessSP process_sp (m_process_wp.lock());
474         if (process_sp)
475         {
476             const addr_t base_load_addr = section->GetLoadBaseAddress (&process_sp->GetTarget());
477             if (base_load_addr != LLDB_INVALID_ADDRESS)
478             {
479                 DataBufferSP data_sp (ReadMemory (process_sp, base_load_addr, section->GetByteSize()));
480                 if (data_sp)
481                 {
482                     section_data.SetData (data_sp, 0, data_sp->GetByteSize());
483                     section_data.SetByteOrder (process_sp->GetByteOrder());
484                     section_data.SetAddressByteSize (process_sp->GetAddressByteSize());
485                     return section_data.GetByteSize();
486                 }
487             }
488         }
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 MemoryMapSectionData (section, section_data);
494     }
495     section_data.Clear();
496     return 0;
497 }
498 
499 size_t
500 ObjectFile::MemoryMapSectionData (const Section *section, DataExtractor& section_data) const
501 {
502     if (IsInMemory())
503     {
504         return ReadSectionData (section, section_data);
505     }
506     else
507     {
508         // The object file now contains a full mmap'ed copy of the object file data, so just use this
509         return GetData(section->GetFileOffset(), section->GetFileSize(), section_data);
510     }
511     section_data.Clear();
512     return 0;
513 }
514 
515 
516 bool
517 ObjectFile::SplitArchivePathWithObject (const char *path_with_object, FileSpec &archive_file, ConstString &archive_object, bool must_exist)
518 {
519     RegularExpression g_object_regex("(.*)\\(([^\\)]+)\\)$");
520     if (g_object_regex.Execute (path_with_object, 2))
521     {
522         std::string path;
523         std::string obj;
524         if (g_object_regex.GetMatchAtIndex (path_with_object, 1, path) &&
525             g_object_regex.GetMatchAtIndex (path_with_object, 2, obj))
526         {
527             archive_file.SetFile (path.c_str(), false);
528             archive_object.SetCString(obj.c_str());
529             if (must_exist && !archive_file.Exists())
530                 return false;
531             return true;
532         }
533     }
534     return false;
535 }
536 
537 void
538 ObjectFile::ClearSymtab ()
539 {
540     ModuleSP module_sp(GetModule());
541     if (module_sp)
542     {
543         lldb_private::Mutex::Locker locker(module_sp->GetMutex());
544         Log *log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_OBJECT));
545         if (log)
546         {
547             log->Printf ("%p ObjectFile::ClearSymtab () symtab = %p",
548                          this,
549                          m_symtab_ap.get());
550         }
551         m_symtab_ap.reset();
552     }
553 }
554