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