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 #ifdef LLDB_CONFIGURATION_DEBUG
271   // For debug builds, ensure that there are no orphaned (i.e., moduleless)
272   // sections.
273   assert(GetModule().get());
274 #endif
275   return true;
276 }
277 
278 bool Section::ContainsFileAddress(addr_t vm_addr) const {
279   const addr_t file_addr = GetFileAddress();
280   if (file_addr != LLDB_INVALID_ADDRESS && !IsThreadSpecific()) {
281     if (file_addr <= vm_addr) {
282       const addr_t offset = (vm_addr - file_addr) * m_target_byte_size;
283       return offset < GetByteSize();
284     }
285   }
286   return false;
287 }
288 
289 void Section::Dump(Stream *s, Target *target, uint32_t depth) const {
290   //    s->Printf("%.*p: ", (int)sizeof(void*) * 2, this);
291   s->Indent();
292   s->Printf("0x%8.8" PRIx64 " %-16s ", GetID(), GetTypeAsCString());
293   bool resolved = true;
294   addr_t addr = LLDB_INVALID_ADDRESS;
295 
296   if (GetByteSize() == 0)
297     s->Printf("%39s", "");
298   else {
299     if (target)
300       addr = GetLoadBaseAddress(target);
301 
302     if (addr == LLDB_INVALID_ADDRESS) {
303       if (target)
304         resolved = false;
305       addr = GetFileAddress();
306     }
307 
308     VMRange range(addr, addr + m_byte_size);
309     range.Dump(s->AsRawOstream(), 0);
310   }
311 
312   s->Printf("%c %c%c%c  0x%8.8" PRIx64 " 0x%8.8" PRIx64 " 0x%8.8x ",
313             resolved ? ' ' : '*', m_readable ? 'r' : '-',
314             m_writable ? 'w' : '-', m_executable ? 'x' : '-', m_file_offset,
315             m_file_size, Get());
316 
317   DumpName(s);
318 
319   s->EOL();
320 
321   if (depth > 0)
322     m_children.Dump(s, target, false, depth - 1);
323 }
324 
325 void Section::DumpName(Stream *s) const {
326   SectionSP parent_sp(GetParent());
327   if (parent_sp) {
328     parent_sp->DumpName(s);
329     s->PutChar('.');
330   } else {
331     // The top most section prints the module basename
332     const char *name = nullptr;
333     ModuleSP module_sp(GetModule());
334 
335     if (m_obj_file) {
336       const FileSpec &file_spec = m_obj_file->GetFileSpec();
337       name = file_spec.GetFilename().AsCString();
338     }
339     if ((!name || !name[0]) && module_sp)
340       name = module_sp->GetFileSpec().GetFilename().AsCString();
341     if (name && name[0])
342       s->Printf("%s.", name);
343   }
344   m_name.Dump(s);
345 }
346 
347 bool Section::IsDescendant(const Section *section) {
348   if (this == section)
349     return true;
350   SectionSP parent_sp(GetParent());
351   if (parent_sp)
352     return parent_sp->IsDescendant(section);
353   return false;
354 }
355 
356 bool Section::Slide(addr_t slide_amount, bool slide_children) {
357   if (m_file_addr != LLDB_INVALID_ADDRESS) {
358     if (slide_amount == 0)
359       return true;
360 
361     m_file_addr += slide_amount;
362 
363     if (slide_children)
364       m_children.Slide(slide_amount, slide_children);
365 
366     return true;
367   }
368   return false;
369 }
370 
371 /// Get the permissions as OR'ed bits from lldb::Permissions
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 /// Set the permissions using bits OR'ed from lldb::Permissions
384 void Section::SetPermissions(uint32_t permissions) {
385   m_readable = (permissions & ePermissionsReadable) != 0;
386   m_writable = (permissions & ePermissionsWritable) != 0;
387   m_executable = (permissions & ePermissionsExecutable) != 0;
388 }
389 
390 lldb::offset_t Section::GetSectionData(void *dst, lldb::offset_t dst_len,
391                                        lldb::offset_t offset) {
392   if (m_obj_file)
393     return m_obj_file->ReadSectionData(this, offset, dst, dst_len);
394   return 0;
395 }
396 
397 lldb::offset_t Section::GetSectionData(DataExtractor &section_data) {
398   if (m_obj_file)
399     return m_obj_file->ReadSectionData(this, section_data);
400   return 0;
401 }
402 
403 #pragma mark SectionList
404 
405 SectionList &SectionList::operator=(const SectionList &rhs) {
406   if (this != &rhs)
407     m_sections = rhs.m_sections;
408   return *this;
409 }
410 
411 size_t SectionList::AddSection(const lldb::SectionSP &section_sp) {
412   if (section_sp) {
413     size_t section_index = m_sections.size();
414     m_sections.push_back(section_sp);
415     return section_index;
416   }
417 
418   return std::numeric_limits<size_t>::max();
419 }
420 
421 // Warning, this can be slow as it's removing items from a std::vector.
422 bool SectionList::DeleteSection(size_t idx) {
423   if (idx < m_sections.size()) {
424     m_sections.erase(m_sections.begin() + idx);
425     return true;
426   }
427   return false;
428 }
429 
430 size_t SectionList::FindSectionIndex(const Section *sect) {
431   iterator sect_iter;
432   iterator begin = m_sections.begin();
433   iterator end = m_sections.end();
434   for (sect_iter = begin; sect_iter != end; ++sect_iter) {
435     if (sect_iter->get() == sect) {
436       // The secton was already in this section list
437       return std::distance(begin, sect_iter);
438     }
439   }
440   return UINT32_MAX;
441 }
442 
443 size_t SectionList::AddUniqueSection(const lldb::SectionSP &sect_sp) {
444   size_t sect_idx = FindSectionIndex(sect_sp.get());
445   if (sect_idx == UINT32_MAX) {
446     sect_idx = AddSection(sect_sp);
447   }
448   return sect_idx;
449 }
450 
451 bool SectionList::ReplaceSection(user_id_t sect_id,
452                                  const lldb::SectionSP &sect_sp,
453                                  uint32_t depth) {
454   iterator sect_iter, end = m_sections.end();
455   for (sect_iter = m_sections.begin(); sect_iter != end; ++sect_iter) {
456     if ((*sect_iter)->GetID() == sect_id) {
457       *sect_iter = sect_sp;
458       return true;
459     } else if (depth > 0) {
460       if ((*sect_iter)
461               ->GetChildren()
462               .ReplaceSection(sect_id, sect_sp, depth - 1))
463         return true;
464     }
465   }
466   return false;
467 }
468 
469 size_t SectionList::GetNumSections(uint32_t depth) const {
470   size_t count = m_sections.size();
471   if (depth > 0) {
472     const_iterator sect_iter, end = m_sections.end();
473     for (sect_iter = m_sections.begin(); sect_iter != end; ++sect_iter) {
474       count += (*sect_iter)->GetChildren().GetNumSections(depth - 1);
475     }
476   }
477   return count;
478 }
479 
480 SectionSP SectionList::GetSectionAtIndex(size_t idx) const {
481   SectionSP sect_sp;
482   if (idx < m_sections.size())
483     sect_sp = m_sections[idx];
484   return sect_sp;
485 }
486 
487 SectionSP
488 SectionList::FindSectionByName(ConstString section_dstr) const {
489   SectionSP sect_sp;
490   // Check if we have a valid section string
491   if (section_dstr && !m_sections.empty()) {
492     const_iterator sect_iter;
493     const_iterator end = m_sections.end();
494     for (sect_iter = m_sections.begin();
495          sect_iter != end && sect_sp.get() == nullptr; ++sect_iter) {
496       Section *child_section = sect_iter->get();
497       if (child_section) {
498         if (child_section->GetName() == section_dstr) {
499           sect_sp = *sect_iter;
500         } else {
501           sect_sp =
502               child_section->GetChildren().FindSectionByName(section_dstr);
503         }
504       }
505     }
506   }
507   return sect_sp;
508 }
509 
510 SectionSP SectionList::FindSectionByID(user_id_t sect_id) const {
511   SectionSP sect_sp;
512   if (sect_id) {
513     const_iterator sect_iter;
514     const_iterator end = m_sections.end();
515     for (sect_iter = m_sections.begin();
516          sect_iter != end && sect_sp.get() == nullptr; ++sect_iter) {
517       if ((*sect_iter)->GetID() == sect_id) {
518         sect_sp = *sect_iter;
519         break;
520       } else {
521         sect_sp = (*sect_iter)->GetChildren().FindSectionByID(sect_id);
522       }
523     }
524   }
525   return sect_sp;
526 }
527 
528 SectionSP SectionList::FindSectionByType(SectionType sect_type,
529                                          bool check_children,
530                                          size_t start_idx) const {
531   SectionSP sect_sp;
532   size_t num_sections = m_sections.size();
533   for (size_t idx = start_idx; idx < num_sections; ++idx) {
534     if (m_sections[idx]->GetType() == sect_type) {
535       sect_sp = m_sections[idx];
536       break;
537     } else if (check_children) {
538       sect_sp = m_sections[idx]->GetChildren().FindSectionByType(
539           sect_type, check_children, 0);
540       if (sect_sp)
541         break;
542     }
543   }
544   return sect_sp;
545 }
546 
547 SectionSP SectionList::FindSectionContainingFileAddress(addr_t vm_addr,
548                                                         uint32_t depth) const {
549   SectionSP sect_sp;
550   const_iterator sect_iter;
551   const_iterator end = m_sections.end();
552   for (sect_iter = m_sections.begin();
553        sect_iter != end && sect_sp.get() == nullptr; ++sect_iter) {
554     Section *sect = sect_iter->get();
555     if (sect->ContainsFileAddress(vm_addr)) {
556       // The file address is in this section. We need to make sure one of our
557       // child sections doesn't contain this address as well as obeying the
558       // depth limit that was passed in.
559       if (depth > 0)
560         sect_sp = sect->GetChildren().FindSectionContainingFileAddress(
561             vm_addr, depth - 1);
562 
563       if (sect_sp.get() == nullptr && !sect->IsFake())
564         sect_sp = *sect_iter;
565     }
566   }
567   return sect_sp;
568 }
569 
570 bool SectionList::ContainsSection(user_id_t sect_id) const {
571   return FindSectionByID(sect_id).get() != nullptr;
572 }
573 
574 void SectionList::Dump(Stream *s, Target *target, bool show_header,
575                        uint32_t depth) const {
576   bool target_has_loaded_sections =
577       target && !target->GetSectionLoadList().IsEmpty();
578   if (show_header && !m_sections.empty()) {
579     s->Indent();
580     s->Printf("SectID     Type             %s Address                          "
581               "   Perm File Off.  File Size  Flags "
582               "     Section Name\n",
583               target_has_loaded_sections ? "Load" : "File");
584     s->Indent();
585     s->PutCString("---------- ---------------- "
586                   "---------------------------------------  ---- ---------- "
587                   "---------- "
588                   "---------- ----------------------------\n");
589   }
590 
591   const_iterator sect_iter;
592   const_iterator end = m_sections.end();
593   for (sect_iter = m_sections.begin(); sect_iter != end; ++sect_iter) {
594     (*sect_iter)->Dump(s, target_has_loaded_sections ? target : nullptr, depth);
595   }
596 
597   if (show_header && !m_sections.empty())
598     s->IndentLess();
599 }
600 
601 size_t SectionList::Slide(addr_t slide_amount, bool slide_children) {
602   size_t count = 0;
603   const_iterator pos, end = m_sections.end();
604   for (pos = m_sections.begin(); pos != end; ++pos) {
605     if ((*pos)->Slide(slide_amount, slide_children))
606       ++count;
607   }
608   return count;
609 }
610