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