1 //===-- Section.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/Core/Section.h"
11 #include "lldb/Core/Address.h" // for Address
12 #include "lldb/Core/Module.h"
13 #include "lldb/Symbol/ObjectFile.h"
14 #include "lldb/Target/SectionLoadList.h"
15 #include "lldb/Target/Target.h"
16 #include "lldb/Utility/FileSpec.h" // for FileSpec
17 #include "lldb/Utility/Stream.h"   // for Stream
18 #include "lldb/Utility/VMRange.h"  // for VMRange
19 
20 #include <inttypes.h> // for PRIx64
21 #include <limits>     // for numeric_limits
22 #include <utility>    // for distance
23 
24 namespace lldb_private {
25 class DataExtractor;
26 }
27 using namespace lldb;
28 using namespace lldb_private;
29 
30 const char *Section::GetTypeAsCString() const {
31   switch (m_type) {
32   case eSectionTypeInvalid:
33     return "invalid";
34   case eSectionTypeCode:
35     return "code";
36   case eSectionTypeContainer:
37     return "container";
38   case eSectionTypeData:
39     return "data";
40   case eSectionTypeDataCString:
41     return "data-cstr";
42   case eSectionTypeDataCStringPointers:
43     return "data-cstr-ptr";
44   case eSectionTypeDataSymbolAddress:
45     return "data-symbol-addr";
46   case eSectionTypeData4:
47     return "data-4-byte";
48   case eSectionTypeData8:
49     return "data-8-byte";
50   case eSectionTypeData16:
51     return "data-16-byte";
52   case eSectionTypeDataPointers:
53     return "data-ptrs";
54   case eSectionTypeDebug:
55     return "debug";
56   case eSectionTypeZeroFill:
57     return "zero-fill";
58   case eSectionTypeDataObjCMessageRefs:
59     return "objc-message-refs";
60   case eSectionTypeDataObjCCFStrings:
61     return "objc-cfstrings";
62   case eSectionTypeDWARFDebugAbbrev:
63     return "dwarf-abbrev";
64   case eSectionTypeDWARFDebugAddr:
65     return "dwarf-addr";
66   case eSectionTypeDWARFDebugAranges:
67     return "dwarf-aranges";
68   case eSectionTypeDWARFDebugCuIndex:
69     return "dwarf-cu-index";
70   case eSectionTypeDWARFDebugFrame:
71     return "dwarf-frame";
72   case eSectionTypeDWARFDebugInfo:
73     return "dwarf-info";
74   case eSectionTypeDWARFDebugLine:
75     return "dwarf-line";
76   case eSectionTypeDWARFDebugLoc:
77     return "dwarf-loc";
78   case eSectionTypeDWARFDebugMacInfo:
79     return "dwarf-macinfo";
80   case eSectionTypeDWARFDebugMacro:
81     return "dwarf-macro";
82   case eSectionTypeDWARFDebugPubNames:
83     return "dwarf-pubnames";
84   case eSectionTypeDWARFDebugPubTypes:
85     return "dwarf-pubtypes";
86   case eSectionTypeDWARFDebugRanges:
87     return "dwarf-ranges";
88   case eSectionTypeDWARFDebugStr:
89     return "dwarf-str";
90   case eSectionTypeDWARFDebugStrOffsets:
91     return "dwarf-str-offsets";
92   case eSectionTypeDWARFDebugTypes:
93     return "dwarf-types";
94   case eSectionTypeELFSymbolTable:
95     return "elf-symbol-table";
96   case eSectionTypeELFDynamicSymbols:
97     return "elf-dynamic-symbols";
98   case eSectionTypeELFRelocationEntries:
99     return "elf-relocation-entries";
100   case eSectionTypeELFDynamicLinkInfo:
101     return "elf-dynamic-link-info";
102   case eSectionTypeDWARFAppleNames:
103     return "apple-names";
104   case eSectionTypeDWARFAppleTypes:
105     return "apple-types";
106   case eSectionTypeDWARFAppleNamespaces:
107     return "apple-namespaces";
108   case eSectionTypeDWARFAppleObjC:
109     return "apple-objc";
110   case eSectionTypeEHFrame:
111     return "eh-frame";
112   case eSectionTypeARMexidx:
113     return "ARM.exidx";
114   case eSectionTypeARMextab:
115     return "ARM.extab";
116   case eSectionTypeCompactUnwind:
117     return "compact-unwind";
118   case eSectionTypeGoSymtab:
119     return "go-symtab";
120   case eSectionTypeAbsoluteAddress:
121     return "absolute";
122   case eSectionTypeDWARFGNUDebugAltLink:
123     return "dwarf-gnu-debugaltlink";
124   case eSectionTypeOther:
125     return "regular";
126   }
127   return "unknown";
128 }
129 
130 Section::Section(const ModuleSP &module_sp, ObjectFile *obj_file,
131                  user_id_t sect_id, const ConstString &name,
132                  SectionType sect_type, addr_t file_addr, addr_t byte_size,
133                  lldb::offset_t file_offset, lldb::offset_t file_size,
134                  uint32_t log2align, uint32_t flags,
135                  uint32_t target_byte_size /*=1*/)
136     : ModuleChild(module_sp), UserID(sect_id), Flags(flags),
137       m_obj_file(obj_file), m_type(sect_type), m_parent_wp(), m_name(name),
138       m_file_addr(file_addr), m_byte_size(byte_size),
139       m_file_offset(file_offset), m_file_size(file_size),
140       m_log2align(log2align), m_children(), m_fake(false), m_encrypted(false),
141       m_thread_specific(false), m_readable(false), m_writable(false),
142       m_executable(false), m_relocated(false), m_target_byte_size(target_byte_size) {
143   //    printf ("Section::Section(%p): module=%p, sect_id = 0x%16.16" PRIx64 ",
144   //    addr=[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 "), file [0x%16.16" PRIx64 "
145   //    - 0x%16.16" PRIx64 "), flags = 0x%8.8x, name = %s\n",
146   //            this, module_sp.get(), sect_id, file_addr, file_addr +
147   //            byte_size, file_offset, file_offset + file_size, flags,
148   //            name.GetCString());
149 }
150 
151 Section::Section(const lldb::SectionSP &parent_section_sp,
152                  const ModuleSP &module_sp, ObjectFile *obj_file,
153                  user_id_t sect_id, const ConstString &name,
154                  SectionType sect_type, addr_t file_addr, addr_t byte_size,
155                  lldb::offset_t file_offset, lldb::offset_t file_size,
156                  uint32_t log2align, uint32_t flags,
157                  uint32_t target_byte_size /*=1*/)
158     : ModuleChild(module_sp), UserID(sect_id), Flags(flags),
159       m_obj_file(obj_file), m_type(sect_type), m_parent_wp(), m_name(name),
160       m_file_addr(file_addr), m_byte_size(byte_size),
161       m_file_offset(file_offset), m_file_size(file_size),
162       m_log2align(log2align), m_children(), m_fake(false), m_encrypted(false),
163       m_thread_specific(false), m_readable(false), m_writable(false),
164       m_executable(false), m_relocated(false), m_target_byte_size(target_byte_size) {
165   //    printf ("Section::Section(%p): module=%p, sect_id = 0x%16.16" PRIx64 ",
166   //    addr=[0x%16.16" PRIx64 " - 0x%16.16" PRIx64 "), file [0x%16.16" PRIx64 "
167   //    - 0x%16.16" PRIx64 "), flags = 0x%8.8x, name = %s.%s\n",
168   //            this, module_sp.get(), sect_id, file_addr, file_addr +
169   //            byte_size, file_offset, file_offset + file_size, flags,
170   //            parent_section_sp->GetName().GetCString(), name.GetCString());
171   if (parent_section_sp)
172     m_parent_wp = parent_section_sp;
173 }
174 
175 Section::~Section() {
176   //    printf ("Section::~Section(%p)\n", this);
177 }
178 
179 addr_t Section::GetFileAddress() const {
180   SectionSP parent_sp(GetParent());
181   if (parent_sp) {
182     // This section has a parent which means m_file_addr is an offset into the
183     // parent section, so the file address for this section is the file address
184     // of the parent plus the offset
185     return parent_sp->GetFileAddress() + m_file_addr;
186   }
187   // This section has no parent, so m_file_addr is the file base address
188   return m_file_addr;
189 }
190 
191 bool Section::SetFileAddress(lldb::addr_t file_addr) {
192   SectionSP parent_sp(GetParent());
193   if (parent_sp) {
194     if (m_file_addr >= file_addr)
195       return parent_sp->SetFileAddress(m_file_addr - file_addr);
196     return false;
197   } else {
198     // This section has no parent, so m_file_addr is the file base address
199     m_file_addr = file_addr;
200     return true;
201   }
202 }
203 
204 lldb::addr_t Section::GetOffset() const {
205   // This section has a parent which means m_file_addr is an offset.
206   SectionSP parent_sp(GetParent());
207   if (parent_sp)
208     return m_file_addr;
209 
210   // This section has no parent, so there is no offset to be had
211   return 0;
212 }
213 
214 addr_t Section::GetLoadBaseAddress(Target *target) const {
215   addr_t load_base_addr = LLDB_INVALID_ADDRESS;
216   SectionSP parent_sp(GetParent());
217   if (parent_sp) {
218     load_base_addr = parent_sp->GetLoadBaseAddress(target);
219     if (load_base_addr != LLDB_INVALID_ADDRESS)
220       load_base_addr += GetOffset();
221   }
222   if (load_base_addr == LLDB_INVALID_ADDRESS) {
223     load_base_addr = target->GetSectionLoadList().GetSectionLoadAddress(
224         const_cast<Section *>(this)->shared_from_this());
225   }
226   return load_base_addr;
227 }
228 
229 bool Section::ResolveContainedAddress(addr_t offset, Address &so_addr,
230                                       bool allow_section_end) const {
231   const size_t num_children = m_children.GetSize();
232   for (size_t i = 0; i < num_children; i++) {
233     Section *child_section = m_children.GetSectionAtIndex(i).get();
234 
235     addr_t child_offset = child_section->GetOffset();
236     if (child_offset <= offset &&
237         offset - child_offset <
238             child_section->GetByteSize() + (allow_section_end ? 1 : 0))
239       return child_section->ResolveContainedAddress(offset - child_offset,
240                                                     so_addr, allow_section_end);
241   }
242   so_addr.SetOffset(offset);
243   so_addr.SetSection(const_cast<Section *>(this)->shared_from_this());
244 
245 #ifdef LLDB_CONFIGURATION_DEBUG
246   // For debug builds, ensure that there are no orphaned (i.e., moduleless)
247   // sections.
248   assert(GetModule().get());
249 #endif
250   return true;
251 }
252 
253 bool Section::ContainsFileAddress(addr_t vm_addr) const {
254   const addr_t file_addr = GetFileAddress();
255   if (file_addr != LLDB_INVALID_ADDRESS) {
256     if (file_addr <= vm_addr) {
257       const addr_t offset = (vm_addr - file_addr) * m_target_byte_size;
258       return offset < GetByteSize();
259     }
260   }
261   return false;
262 }
263 
264 int Section::Compare(const Section &a, const Section &b) {
265   if (&a == &b)
266     return 0;
267 
268   const ModuleSP a_module_sp = a.GetModule();
269   const ModuleSP b_module_sp = b.GetModule();
270   if (a_module_sp == b_module_sp) {
271     user_id_t a_sect_uid = a.GetID();
272     user_id_t b_sect_uid = b.GetID();
273     if (a_sect_uid < b_sect_uid)
274       return -1;
275     if (a_sect_uid > b_sect_uid)
276       return 1;
277     return 0;
278   } else {
279     // The modules are different, just compare the module pointers
280     if (a_module_sp.get() < b_module_sp.get())
281       return -1;
282     else
283       return 1; // We already know the modules aren't equal
284   }
285 }
286 
287 void Section::Dump(Stream *s, Target *target, uint32_t depth) const {
288   //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
289   s->Indent();
290   s->Printf("0x%8.8" PRIx64 " %-16s ", GetID(), GetTypeAsCString());
291   bool resolved = true;
292   addr_t addr = LLDB_INVALID_ADDRESS;
293 
294   if (GetByteSize() == 0)
295     s->Printf("%39s", "");
296   else {
297     if (target)
298       addr = GetLoadBaseAddress(target);
299 
300     if (addr == LLDB_INVALID_ADDRESS) {
301       if (target)
302         resolved = false;
303       addr = GetFileAddress();
304     }
305 
306     VMRange range(addr, addr + m_byte_size);
307     range.Dump(s, 0);
308   }
309 
310   s->Printf("%c %c%c%c  0x%8.8" PRIx64 " 0x%8.8" PRIx64 " 0x%8.8x ",
311             resolved ? ' ' : '*', m_readable ? 'r' : '-',
312             m_writable ? 'w' : '-', m_executable ? 'x' : '-', m_file_offset,
313             m_file_size, Get());
314 
315   DumpName(s);
316 
317   s->EOL();
318 
319   if (depth > 0)
320     m_children.Dump(s, target, false, depth - 1);
321 }
322 
323 void Section::DumpName(Stream *s) const {
324   SectionSP parent_sp(GetParent());
325   if (parent_sp) {
326     parent_sp->DumpName(s);
327     s->PutChar('.');
328   } else {
329     // The top most section prints the module basename
330     const char *name = NULL;
331     ModuleSP module_sp(GetModule());
332 
333     if (m_obj_file) {
334       const FileSpec &file_spec = m_obj_file->GetFileSpec();
335       name = file_spec.GetFilename().AsCString();
336     }
337     if ((!name || !name[0]) && module_sp)
338       name = module_sp->GetFileSpec().GetFilename().AsCString();
339     if (name && name[0])
340       s->Printf("%s.", name);
341   }
342   m_name.Dump(s);
343 }
344 
345 bool Section::IsDescendant(const Section *section) {
346   if (this == section)
347     return true;
348   SectionSP parent_sp(GetParent());
349   if (parent_sp)
350     return parent_sp->IsDescendant(section);
351   return false;
352 }
353 
354 bool Section::Slide(addr_t slide_amount, bool slide_children) {
355   if (m_file_addr != LLDB_INVALID_ADDRESS) {
356     if (slide_amount == 0)
357       return true;
358 
359     m_file_addr += slide_amount;
360 
361     if (slide_children)
362       m_children.Slide(slide_amount, slide_children);
363 
364     return true;
365   }
366   return false;
367 }
368 
369 //------------------------------------------------------------------
370 /// Get the permissions as OR'ed bits from lldb::Permissions
371 //------------------------------------------------------------------
372 uint32_t Section::GetPermissions() const {
373   uint32_t permissions = 0;
374   if (m_readable)
375     permissions |= ePermissionsReadable;
376   if (m_writable)
377     permissions |= ePermissionsWritable;
378   if (m_executable)
379     permissions |= ePermissionsExecutable;
380   return permissions;
381 }
382 
383 //------------------------------------------------------------------
384 /// Set the permissions using bits OR'ed from lldb::Permissions
385 //------------------------------------------------------------------
386 void Section::SetPermissions(uint32_t permissions) {
387   m_readable = (permissions & ePermissionsReadable) != 0;
388   m_writable = (permissions & ePermissionsWritable) != 0;
389   m_executable = (permissions & ePermissionsExecutable) != 0;
390 }
391 
392 lldb::offset_t Section::GetSectionData(void *dst, lldb::offset_t dst_len,
393                                        lldb::offset_t offset) {
394   if (m_obj_file)
395     return m_obj_file->ReadSectionData(this, offset, dst, dst_len);
396   return 0;
397 }
398 
399 lldb::offset_t Section::GetSectionData(DataExtractor &section_data) {
400   if (m_obj_file)
401     return m_obj_file->ReadSectionData(this, section_data);
402   return 0;
403 }
404 
405 #pragma mark SectionList
406 
407 SectionList::SectionList() : m_sections() {}
408 
409 SectionList::~SectionList() {}
410 
411 SectionList &SectionList::operator=(const SectionList &rhs) {
412   if (this != &rhs)
413     m_sections = rhs.m_sections;
414   return *this;
415 }
416 
417 size_t SectionList::AddSection(const lldb::SectionSP &section_sp) {
418   if (section_sp) {
419     size_t section_index = m_sections.size();
420     m_sections.push_back(section_sp);
421     return section_index;
422   }
423 
424   return std::numeric_limits<size_t>::max();
425 }
426 
427 // Warning, this can be slow as it's removing items from a std::vector.
428 bool SectionList::DeleteSection(size_t idx) {
429   if (idx < m_sections.size()) {
430     m_sections.erase(m_sections.begin() + idx);
431     return true;
432   }
433   return false;
434 }
435 
436 size_t SectionList::FindSectionIndex(const Section *sect) {
437   iterator sect_iter;
438   iterator begin = m_sections.begin();
439   iterator end = m_sections.end();
440   for (sect_iter = begin; sect_iter != end; ++sect_iter) {
441     if (sect_iter->get() == sect) {
442       // The secton was already in this section list
443       return std::distance(begin, sect_iter);
444     }
445   }
446   return UINT32_MAX;
447 }
448 
449 size_t SectionList::AddUniqueSection(const lldb::SectionSP &sect_sp) {
450   size_t sect_idx = FindSectionIndex(sect_sp.get());
451   if (sect_idx == UINT32_MAX) {
452     sect_idx = AddSection(sect_sp);
453   }
454   return sect_idx;
455 }
456 
457 bool SectionList::ReplaceSection(user_id_t sect_id,
458                                  const lldb::SectionSP &sect_sp,
459                                  uint32_t depth) {
460   iterator sect_iter, end = m_sections.end();
461   for (sect_iter = m_sections.begin(); sect_iter != end; ++sect_iter) {
462     if ((*sect_iter)->GetID() == sect_id) {
463       *sect_iter = sect_sp;
464       return true;
465     } else if (depth > 0) {
466       if ((*sect_iter)
467               ->GetChildren()
468               .ReplaceSection(sect_id, sect_sp, depth - 1))
469         return true;
470     }
471   }
472   return false;
473 }
474 
475 size_t SectionList::GetNumSections(uint32_t depth) const {
476   size_t count = m_sections.size();
477   if (depth > 0) {
478     const_iterator sect_iter, end = m_sections.end();
479     for (sect_iter = m_sections.begin(); sect_iter != end; ++sect_iter) {
480       count += (*sect_iter)->GetChildren().GetNumSections(depth - 1);
481     }
482   }
483   return count;
484 }
485 
486 SectionSP SectionList::GetSectionAtIndex(size_t idx) const {
487   SectionSP sect_sp;
488   if (idx < m_sections.size())
489     sect_sp = m_sections[idx];
490   return sect_sp;
491 }
492 
493 SectionSP
494 SectionList::FindSectionByName(const ConstString &section_dstr) const {
495   SectionSP sect_sp;
496   // Check if we have a valid section string
497   if (section_dstr && !m_sections.empty()) {
498     const_iterator sect_iter;
499     const_iterator end = m_sections.end();
500     for (sect_iter = m_sections.begin();
501          sect_iter != end && sect_sp.get() == NULL; ++sect_iter) {
502       Section *child_section = sect_iter->get();
503       if (child_section) {
504         if (child_section->GetName() == section_dstr) {
505           sect_sp = *sect_iter;
506         } else {
507           sect_sp =
508               child_section->GetChildren().FindSectionByName(section_dstr);
509         }
510       }
511     }
512   }
513   return sect_sp;
514 }
515 
516 SectionSP SectionList::FindSectionByID(user_id_t sect_id) const {
517   SectionSP sect_sp;
518   if (sect_id) {
519     const_iterator sect_iter;
520     const_iterator end = m_sections.end();
521     for (sect_iter = m_sections.begin();
522          sect_iter != end && sect_sp.get() == NULL; ++sect_iter) {
523       if ((*sect_iter)->GetID() == sect_id) {
524         sect_sp = *sect_iter;
525         break;
526       } else {
527         sect_sp = (*sect_iter)->GetChildren().FindSectionByID(sect_id);
528       }
529     }
530   }
531   return sect_sp;
532 }
533 
534 SectionSP SectionList::FindSectionByType(SectionType sect_type,
535                                          bool check_children,
536                                          size_t start_idx) const {
537   SectionSP sect_sp;
538   size_t num_sections = m_sections.size();
539   for (size_t idx = start_idx; idx < num_sections; ++idx) {
540     if (m_sections[idx]->GetType() == sect_type) {
541       sect_sp = m_sections[idx];
542       break;
543     } else if (check_children) {
544       sect_sp = m_sections[idx]->GetChildren().FindSectionByType(
545           sect_type, check_children, 0);
546       if (sect_sp)
547         break;
548     }
549   }
550   return sect_sp;
551 }
552 
553 SectionSP SectionList::FindSectionContainingFileAddress(addr_t vm_addr,
554                                                         uint32_t depth) const {
555   SectionSP sect_sp;
556   const_iterator sect_iter;
557   const_iterator end = m_sections.end();
558   for (sect_iter = m_sections.begin();
559        sect_iter != end && sect_sp.get() == NULL; ++sect_iter) {
560     Section *sect = sect_iter->get();
561     if (sect->ContainsFileAddress(vm_addr)) {
562       // The file address is in this section. We need to make sure one of our
563       // child sections doesn't contain this address as well as obeying the
564       // depth limit that was passed in.
565       if (depth > 0)
566         sect_sp = sect->GetChildren().FindSectionContainingFileAddress(
567             vm_addr, depth - 1);
568 
569       if (sect_sp.get() == NULL && !sect->IsFake())
570         sect_sp = *sect_iter;
571     }
572   }
573   return sect_sp;
574 }
575 
576 bool SectionList::ContainsSection(user_id_t sect_id) const {
577   return FindSectionByID(sect_id).get() != NULL;
578 }
579 
580 void SectionList::Dump(Stream *s, Target *target, bool show_header,
581                        uint32_t depth) const {
582   bool target_has_loaded_sections =
583       target && !target->GetSectionLoadList().IsEmpty();
584   if (show_header && !m_sections.empty()) {
585     s->Indent();
586     s->Printf("SectID     Type             %s Address                          "
587               "   Perm File Off.  File Size  Flags "
588               "     Section Name\n",
589               target_has_loaded_sections ? "Load" : "File");
590     s->Indent();
591     s->PutCString("---------- ---------------- "
592                   "---------------------------------------  ---- ---------- "
593                   "---------- "
594                   "---------- ----------------------------\n");
595   }
596 
597   const_iterator sect_iter;
598   const_iterator end = m_sections.end();
599   for (sect_iter = m_sections.begin(); sect_iter != end; ++sect_iter) {
600     (*sect_iter)->Dump(s, target_has_loaded_sections ? target : NULL, depth);
601   }
602 
603   if (show_header && !m_sections.empty())
604     s->IndentLess();
605 }
606 
607 size_t SectionList::Slide(addr_t slide_amount, bool slide_children) {
608   size_t count = 0;
609   const_iterator pos, end = m_sections.end();
610   for (pos = m_sections.begin(); pos != end; ++pos) {
611     if ((*pos)->Slide(slide_amount, slide_children))
612       ++count;
613   }
614   return count;
615 }
616