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