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