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