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 "ConcatOutputSection.h"
11 #include "Config.h"
12 #include "InputFiles.h"
13 #include "OutputSegment.h"
14 #include "Symbols.h"
15 #include "SyntheticSections.h"
16 #include "Target.h"
17 #include "UnwindInfoSection.h"
18 #include "Writer.h"
19 #include "lld/Common/Memory.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/xxhash.h"
22 
23 using namespace llvm;
24 using namespace llvm::MachO;
25 using namespace llvm::support;
26 using namespace lld;
27 using namespace lld::macho;
28 
29 // Verify ConcatInputSection's size on 64-bit builds. The size of std::vector
30 // can differ based on STL debug levels (e.g. iterator debugging on MSVC's STL),
31 // so account for that.
32 static_assert(sizeof(void *) != 8 ||
33                   sizeof(ConcatInputSection) == sizeof(std::vector<Reloc>) + 96,
34               "Try to minimize ConcatInputSection's size, we create many "
35               "instances of it");
36 
37 std::vector<ConcatInputSection *> macho::inputSections;
38 
39 uint64_t InputSection::getFileSize() const {
40   return isZeroFill(getFlags()) ? 0 : getSize();
41 }
42 
43 uint64_t InputSection::getVA(uint64_t off) const {
44   return parent->addr + getOffset(off);
45 }
46 
47 static uint64_t resolveSymbolVA(const Symbol *sym, uint8_t type) {
48   const RelocAttrs &relocAttrs = target->getRelocAttrs(type);
49   if (relocAttrs.hasAttr(RelocAttrBits::BRANCH))
50     return sym->resolveBranchVA();
51   if (relocAttrs.hasAttr(RelocAttrBits::GOT))
52     return sym->resolveGotVA();
53   if (relocAttrs.hasAttr(RelocAttrBits::TLV))
54     return sym->resolveTlvVA();
55   return sym->getVA();
56 }
57 
58 std::string InputSection::getLocation(uint64_t off) const {
59   // First, try to find a symbol that's near the offset. Use it as a reference
60   // point.
61   for (size_t i = 0; i < symbols.size(); ++i)
62     if (symbols[i]->value <= off &&
63         (i + 1 == symbols.size() || symbols[i + 1]->value > off))
64       return (toString(getFile()) + ":(symbol " + symbols.front()->getName() +
65               "+0x" + Twine::utohexstr(off - symbols[i]->value) + ")")
66           .str();
67 
68   // If that fails, use the section itself as a reference point.
69   for (const Subsection &subsec : section.subsections) {
70     if (subsec.isec == this) {
71       off += subsec.offset;
72       break;
73     }
74   }
75   return (toString(getFile()) + ":(" + getName() + "+0x" +
76           Twine::utohexstr(off) + ")")
77       .str();
78 }
79 
80 void ConcatInputSection::foldIdentical(ConcatInputSection *copy) {
81   align = std::max(align, copy->align);
82   copy->live = false;
83   copy->wasCoalesced = true;
84   copy->replacement = this;
85 
86   // Merge the sorted vectors of symbols together.
87   auto it = symbols.begin();
88   for (auto copyIt = copy->symbols.begin(); copyIt != copy->symbols.end();) {
89     if (it == symbols.end()) {
90       symbols.push_back(*copyIt++);
91       it = symbols.end();
92     } else if ((*it)->value > (*copyIt)->value) {
93       std::swap(*it++, *copyIt);
94     } else {
95       ++it;
96     }
97   }
98   copy->symbols.clear();
99 
100   // Remove duplicate compact unwind info for symbols at the same address.
101   if (symbols.empty())
102     return;
103   it = symbols.begin();
104   uint64_t v = (*it)->value;
105   for (++it; it != symbols.end(); ++it) {
106     Defined *d = *it;
107     if (d->value == v)
108       d->unwindEntry = nullptr;
109     else
110       v = d->value;
111   }
112 }
113 
114 void ConcatInputSection::writeTo(uint8_t *buf) {
115   assert(!shouldOmitFromOutput());
116 
117   if (getFileSize() == 0)
118     return;
119 
120   memcpy(buf, data.data(), data.size());
121 
122   for (size_t i = 0; i < relocs.size(); i++) {
123     const Reloc &r = relocs[i];
124     uint8_t *loc = buf + r.offset;
125     uint64_t referentVA = 0;
126     if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
127       const Symbol *fromSym = r.referent.get<Symbol *>();
128       const Reloc &minuend = relocs[++i];
129       uint64_t minuendVA;
130       if (const Symbol *toSym = minuend.referent.dyn_cast<Symbol *>())
131         minuendVA = toSym->getVA() + minuend.addend;
132       else {
133         auto *referentIsec = minuend.referent.get<InputSection *>();
134         assert(!::shouldOmitFromOutput(referentIsec));
135         minuendVA = referentIsec->getVA(minuend.addend);
136       }
137       referentVA = minuendVA - fromSym->getVA();
138     } else if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) {
139       if (target->hasAttr(r.type, RelocAttrBits::LOAD) &&
140           !referentSym->isInGot())
141         target->relaxGotLoad(loc, r.type);
142       referentVA = resolveSymbolVA(referentSym, r.type) + r.addend;
143 
144       if (isThreadLocalVariables(getFlags())) {
145         // References from thread-local variable sections are treated as offsets
146         // relative to the start of the thread-local data memory area, which
147         // is initialized via copying all the TLV data sections (which are all
148         // contiguous).
149         if (isa<Defined>(referentSym))
150           referentVA -= firstTLVDataSection->addr;
151       }
152     } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
153       assert(!::shouldOmitFromOutput(referentIsec));
154       referentVA = referentIsec->getVA(r.addend);
155     }
156     target->relocateOne(loc, r, referentVA, getVA() + r.offset);
157   }
158 }
159 
160 ConcatInputSection *macho::makeSyntheticInputSection(StringRef segName,
161                                                      StringRef sectName,
162                                                      uint32_t flags,
163                                                      ArrayRef<uint8_t> data,
164                                                      uint32_t align) {
165   Section &section =
166       *make<Section>(/*file=*/nullptr, segName, sectName, flags, /*addr=*/0);
167   auto isec = make<ConcatInputSection>(section, data, align);
168   section.subsections.push_back({0, isec});
169   return isec;
170 }
171 
172 void CStringInputSection::splitIntoPieces() {
173   size_t off = 0;
174   StringRef s = toStringRef(data);
175   while (!s.empty()) {
176     size_t end = s.find(0);
177     if (end == StringRef::npos)
178       fatal(getLocation(off) + ": string is not null terminated");
179     size_t size = end + 1;
180     uint32_t hash = config->dedupLiterals ? xxHash64(s.substr(0, size)) : 0;
181     pieces.emplace_back(off, hash);
182     s = s.substr(size);
183     off += size;
184   }
185 }
186 
187 StringPiece &CStringInputSection::getStringPiece(uint64_t off) {
188   if (off >= data.size())
189     fatal(toString(this) + ": offset is outside the section");
190 
191   auto it =
192       partition_point(pieces, [=](StringPiece p) { return p.inSecOff <= off; });
193   return it[-1];
194 }
195 
196 const StringPiece &CStringInputSection::getStringPiece(uint64_t off) const {
197   return const_cast<CStringInputSection *>(this)->getStringPiece(off);
198 }
199 
200 uint64_t CStringInputSection::getOffset(uint64_t off) const {
201   const StringPiece &piece = getStringPiece(off);
202   uint64_t addend = off - piece.inSecOff;
203   return piece.outSecOff + addend;
204 }
205 
206 WordLiteralInputSection::WordLiteralInputSection(const Section &section,
207                                                  ArrayRef<uint8_t> data,
208                                                  uint32_t align)
209     : InputSection(WordLiteralKind, section, data, align) {
210   switch (sectionType(getFlags())) {
211   case S_4BYTE_LITERALS:
212     power2LiteralSize = 2;
213     break;
214   case S_8BYTE_LITERALS:
215     power2LiteralSize = 3;
216     break;
217   case S_16BYTE_LITERALS:
218     power2LiteralSize = 4;
219     break;
220   default:
221     llvm_unreachable("invalid literal section type");
222   }
223 
224   live.resize(data.size() >> power2LiteralSize, !config->deadStrip);
225 }
226 
227 uint64_t WordLiteralInputSection::getOffset(uint64_t off) const {
228   auto *osec = cast<WordLiteralSection>(parent);
229   const uintptr_t buf = reinterpret_cast<uintptr_t>(data.data());
230   switch (sectionType(getFlags())) {
231   case S_4BYTE_LITERALS:
232     return osec->getLiteral4Offset(buf + (off & ~3LLU)) | (off & 3);
233   case S_8BYTE_LITERALS:
234     return osec->getLiteral8Offset(buf + (off & ~7LLU)) | (off & 7);
235   case S_16BYTE_LITERALS:
236     return osec->getLiteral16Offset(buf + (off & ~15LLU)) | (off & 15);
237   default:
238     llvm_unreachable("invalid literal section type");
239   }
240 }
241 
242 bool macho::isCodeSection(const InputSection *isec) {
243   uint32_t type = sectionType(isec->getFlags());
244   if (type != S_REGULAR && type != S_COALESCED)
245     return false;
246 
247   uint32_t attr = isec->getFlags() & SECTION_ATTRIBUTES_USR;
248   if (attr == S_ATTR_PURE_INSTRUCTIONS)
249     return true;
250 
251   if (isec->getSegName() == segment_names::text)
252     return StringSwitch<bool>(isec->getName())
253         .Cases(section_names::textCoalNt, section_names::staticInit, true)
254         .Default(false);
255 
256   return false;
257 }
258 
259 bool macho::isCfStringSection(const InputSection *isec) {
260   return isec->getName() == section_names::cfString &&
261          isec->getSegName() == segment_names::data;
262 }
263 
264 std::string lld::toString(const InputSection *isec) {
265   return (toString(isec->getFile()) + ":(" + isec->getName() + ")").str();
266 }
267