1 //===- InputSection.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 "InputSection.h"
10 #include "InputFiles.h"
11 #include "OutputSegment.h"
12 #include "Symbols.h"
13 #include "Target.h"
14 #include "lld/Common/Memory.h"
15 #include "llvm/Support/Endian.h"
16 
17 using namespace llvm;
18 using namespace llvm::MachO;
19 using namespace llvm::support;
20 using namespace lld;
21 using namespace lld::macho;
22 
23 std::vector<InputSection *> macho::inputSections;
24 
25 uint64_t InputSection::getFileOffset() const {
26   return parent->fileOff + outSecFileOff;
27 }
28 
29 uint64_t InputSection::getFileSize() const {
30   return isZeroFill(flags) ? 0 : getSize();
31 }
32 
33 uint64_t InputSection::getVA() const { return parent->addr + outSecOff; }
34 
35 void InputSection::writeTo(uint8_t *buf) {
36   if (getFileSize() == 0)
37     return;
38 
39   memcpy(buf, data.data(), data.size());
40 
41   for (Reloc &r : relocs) {
42     uint64_t referentVA = 0;
43     if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) {
44       referentVA =
45           target->resolveSymbolVA(buf + r.offset, *referentSym, r.type);
46 
47       if (isThreadLocalVariables(flags)) {
48         // References from thread-local variable sections are treated
49         // as offsets relative to the start of the referent section,
50         // instead of as absolute addresses.
51         if (auto *defined = dyn_cast<Defined>(referentSym))
52           referentVA -= defined->isec->parent->addr;
53       }
54     } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
55       referentVA = referentIsec->getVA();
56     }
57 
58     uint64_t referentVal = referentVA + r.addend;
59     if (r.pcrel)
60       referentVal -= getVA() + r.offset;
61     target->relocateOne(buf + r.offset, r, referentVal);
62   }
63 }
64 
65 bool macho::isCodeSection(InputSection *isec) {
66   uint32_t type = isec->flags & MachO::SECTION_TYPE;
67   if (type != S_REGULAR && type != S_COALESCED)
68     return false;
69 
70   uint32_t attr = isec->flags & MachO::SECTION_ATTRIBUTES_USR;
71   if (attr == S_ATTR_PURE_INSTRUCTIONS)
72     return true;
73 
74   if (isec->segname == segment_names::text)
75     return StringSwitch<bool>(isec->name)
76         .Cases("__textcoal_nt", "__StaticInit", true)
77         .Default(false);
78 
79   return false;
80 }
81 
82 std::string lld::toString(const InputSection *isec) {
83   return (toString(isec->file) + ":(" + isec->name + ")").str();
84 }
85