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 "Sections.h"
15#include "Symbols.h"
16#include "SyntheticSections.h"
17#include "Target.h"
18#include "Writer.h"
19
20#include "lld/Common/ErrorHandler.h"
21#include "lld/Common/Memory.h"
22#include "llvm/Support/xxhash.h"
23
24using namespace llvm;
25using namespace llvm::MachO;
26using namespace llvm::support;
27using namespace lld;
28using namespace lld::macho;
29
30// Verify ConcatInputSection's size on 64-bit builds. The size of std::vector
31// can differ based on STL debug levels (e.g. iterator debugging on MSVC's STL),
32// so account for that.
33static_assert(sizeof(void *) != 8 || sizeof(ConcatInputSection) ==
34 sizeof(std::vector<Relocation>) + 88,
35 "Try to minimize ConcatInputSection's size, we create many "
36 "instances of it");
37
38std::vector<ConcatInputSection *> macho::inputSections;
39int macho::inputSectionsOrder = 0;
40
41// Call this function to add a new InputSection and have it routed to the
42// appropriate container. Depending on its type and current config, it will
43// either be added to 'inputSections' vector or to a synthetic section.
44void lld::macho::addInputSection(InputSection *inputSection) {
45 if (auto *isec = dyn_cast<ConcatInputSection>(Val: inputSection)) {
46 if (isec->isCoalescedWeak())
47 return;
48 if (config->emitRelativeMethodLists &&
49 ObjCMethListSection::isMethodList(isec)) {
50 if (in.objcMethList->inputOrder == UnspecifiedInputOrder)
51 in.objcMethList->inputOrder = inputSectionsOrder++;
52 in.objcMethList->addInput(isec);
53 isec->parent = in.objcMethList;
54 return;
55 }
56 if (config->emitInitOffsets &&
57 sectionType(flags: isec->getFlags()) == S_MOD_INIT_FUNC_POINTERS) {
58 in.initOffsets->addInput(isec);
59 return;
60 }
61 isec->outSecOff = inputSectionsOrder++;
62 auto *osec = ConcatOutputSection::getOrCreateForInput(isec);
63 isec->parent = osec;
64 inputSections.push_back(x: isec);
65 } else if (auto *isec = dyn_cast<CStringInputSection>(Val: inputSection)) {
66 bool useSectionName = config->separateCstringLiteralSections ||
67 isec->getName() == section_names::objcMethname;
68 auto *osec = in.getOrCreateCStringSection(
69 name: useSectionName ? isec->getName() : section_names::cString);
70 if (osec->inputOrder == UnspecifiedInputOrder)
71 osec->inputOrder = inputSectionsOrder++;
72 osec->addInput(isec);
73 } else if (auto *isec = dyn_cast<WordLiteralInputSection>(Val: inputSection)) {
74 if (in.wordLiteralSection->inputOrder == UnspecifiedInputOrder)
75 in.wordLiteralSection->inputOrder = inputSectionsOrder++;
76 in.wordLiteralSection->addInput(isec);
77 } else {
78 llvm_unreachable("unexpected input section kind");
79 }
80
81 assert(inputSectionsOrder <= UnspecifiedInputOrder);
82}
83
84uint64_t InputSection::getFileSize() const {
85 return isZeroFill(flags: getFlags()) ? 0 : getSize();
86}
87
88uint64_t InputSection::getVA(uint64_t off) const {
89 return parent->addr + getOffset(off);
90}
91
92uint64_t macho::resolveSymbolOffsetVA(const Symbol *sym, uint8_t type,
93 int64_t offset) {
94 const RelocAttrs &relocAttrs = target->getRelocAttrs(type);
95 uint64_t symVA;
96 if (relocAttrs.hasAttr(b: RelocAttrBits::BRANCH)) {
97 // For branch relocations with non-zero offsets, use the actual function
98 // address rather than the stub address. Branching to an interior point
99 // of a function (e.g., _func+16) implies reliance on the original
100 // function's layout, which an interposed replacement wouldn't preserve.
101 // There's no meaningful way to "interpose" an interior offset.
102 symVA = (offset != 0) ? sym->getVA() : sym->resolveBranchVA();
103 } else if (relocAttrs.hasAttr(b: RelocAttrBits::GOT) ||
104 relocAttrs.hasAttr(b: RelocAttrBits::TLV)) {
105 // Both kinds read the symbol's single non-lazy pointer slot; for a
106 // thread-local that slot holds the address of its TLV descriptor.
107 symVA = sym->resolveNonLazyPtrVA();
108 } else {
109 symVA = sym->getVA();
110 }
111 return symVA + offset;
112}
113
114const Defined *InputSection::getContainingSymbol(uint64_t off) const {
115 auto *nextSym = llvm::upper_bound(
116 Range: symbols, Value&: off, C: [](uint64_t a, const Defined *b) { return a < b->value; });
117 if (nextSym == symbols.begin())
118 return nullptr;
119 return *std::prev(x: nextSym);
120}
121
122std::string InputSection::getLocation(uint64_t off) const {
123 // First, try to find a symbol that's near the offset. Use it as a reference
124 // point.
125 if (auto *sym = getContainingSymbol(off))
126 return (toString(file: getFile()) + ":(symbol " + toString(*sym) + "+0x" +
127 Twine::utohexstr(Val: off - sym->value) + ")")
128 .str();
129
130 // If that fails, use the section itself as a reference point.
131 for (const Subsection &subsec : section.subsections) {
132 if (subsec.isec == this) {
133 off += subsec.offset;
134 break;
135 }
136 }
137
138 return (toString(file: getFile()) + ":(" + getName() + "+0x" +
139 Twine::utohexstr(Val: off) + ")")
140 .str();
141}
142
143std::string InputSection::getSourceLocation(uint64_t off) const {
144 auto *obj = dyn_cast_or_null<ObjFile>(Val: getFile());
145 if (!obj)
146 return {};
147
148 DWARFCache *dwarf = obj->getDwarf();
149 if (!dwarf)
150 return std::string();
151
152 for (const Subsection &subsec : section.subsections) {
153 if (subsec.isec == this) {
154 off += subsec.offset;
155 break;
156 }
157 }
158
159 auto createMsg = [&](StringRef path, unsigned line) {
160 std::string filename = sys::path::filename(path).str();
161 std::string lineStr = (":" + Twine(line)).str();
162 if (filename == path)
163 return filename + lineStr;
164 return (filename + lineStr + " (" + path + lineStr + ")").str();
165 };
166
167 // First, look up a function for a given offset.
168 if (std::optional<DILineInfo> li = dwarf->getDILineInfo(
169 offset: section.addr + off, sectionIndex: object::SectionedAddress::UndefSection))
170 return createMsg(li->FileName, li->Line);
171
172 // If it failed, look up again as a variable.
173 if (const Defined *sym = getContainingSymbol(off)) {
174 // Symbols are generally prefixed with an underscore, which is not included
175 // in the debug information.
176 StringRef symName = sym->getName();
177 symName.consume_front(Prefix: "_");
178
179 if (std::optional<std::pair<std::string, unsigned>> fileLine =
180 dwarf->getVariableLoc(name: symName))
181 return createMsg(fileLine->first, fileLine->second);
182 }
183
184 // Try to get the source file's name from the DWARF information.
185 if (obj->compileUnit)
186 return obj->sourceFile();
187
188 return {};
189}
190
191const Relocation *InputSection::getRelocAt(uint32_t off) const {
192 auto it = llvm::find_if(Range: relocs,
193 P: [=](const Relocation &r) { return r.offset == off; });
194 if (it == relocs.end())
195 return nullptr;
196 return &*it;
197}
198
199void ConcatInputSection::foldIdentical(ConcatInputSection *copy,
200 Symbol::ICFFoldKind foldKind) {
201 align = std::max(a: align, b: copy->align);
202 copy->live = false;
203 copy->wasCoalesced = true;
204 copy->replacement = this;
205 for (auto &copySym : copy->symbols)
206 copySym->identicalCodeFoldingKind = foldKind;
207
208 if (copy->symbols.empty())
209 return;
210 auto *it = copy->symbols.begin();
211 // The first symbol in the merged section (symbols.front()) must keep its
212 // unwind entry. If this section is empty, the copy's first symbol becomes the
213 // new front, so we skip clearing it.
214 if (symbols.empty())
215 ++it;
216 for (; it != copy->symbols.end(); ++it) {
217 assert((*it)->value == 0);
218 (*it)->originalUnwindEntry = nullptr;
219 }
220 symbols.insert(I: symbols.end(), From: copy->symbols.begin(), To: copy->symbols.end());
221 copy->symbols.clear();
222}
223
224void ConcatInputSection::writeTo(uint8_t *buf) {
225 assert(!shouldOmitFromOutput());
226
227 if (getFileSize() == 0)
228 return;
229
230 memcpy(dest: buf, src: data.data(), n: data.size());
231
232 for (size_t i = 0; i < relocs.size(); i++) {
233 const Relocation &r = relocs[i];
234 uint8_t *loc = buf + r.offset;
235 uint64_t referentVA = 0;
236
237 const bool needsFixup = config->emitChainedFixups &&
238 target->hasAttr(type: r.type, bit: RelocAttrBits::UNSIGNED);
239 if (target->hasAttr(type: r.type, bit: RelocAttrBits::SUBTRAHEND)) {
240 const Symbol *fromSym = cast<Symbol *>(Val: r.referent);
241 const Relocation &minuend = relocs[++i];
242 uint64_t minuendVA;
243 if (const Symbol *toSym = dyn_cast<Symbol *>(Val: minuend.referent))
244 minuendVA = toSym->getVA() + minuend.addend;
245 else {
246 auto *referentIsec = cast<InputSection *>(Val: minuend.referent);
247 assert(!::shouldOmitFromOutput(referentIsec));
248 minuendVA = referentIsec->getVA(off: minuend.addend);
249 }
250 referentVA = minuendVA - fromSym->getVA();
251 } else if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) {
252 if (target->hasAttr(type: r.type, bit: RelocAttrBits::LOAD) &&
253 !referentSym->isInGot())
254 target->relaxGotLoad(loc, type: r.type);
255 // For dtrace symbols, do not handle them as normal undefined symbols
256 if (referentSym->getName().starts_with(Prefix: "___dtrace_")) {
257 // Change dtrace call site to pre-defined instructions
258 target->handleDtraceReloc(sym: referentSym, r, loc);
259 continue;
260 }
261 referentVA = resolveSymbolOffsetVA(sym: referentSym, type: r.type, offset: r.addend);
262
263 if (isThreadLocalVariables(flags: getFlags()) && isa<Defined>(Val: referentSym)) {
264 // References from thread-local variable sections are treated as offsets
265 // relative to the start of the thread-local data memory area, which
266 // is initialized via copying all the TLV data sections (which are all
267 // contiguous).
268 referentVA -= firstTLVDataSection->addr;
269 } else if (needsFixup) {
270 writeChainedFixup(buf: loc, sym: referentSym, addend: r.addend);
271 continue;
272 }
273 } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
274 assert(!::shouldOmitFromOutput(referentIsec));
275 referentVA = referentIsec->getVA(off: r.addend);
276
277 if (needsFixup) {
278 writeChainedRebase(buf: loc, targetVA: referentVA);
279 continue;
280 }
281 }
282 target->relocateOne(loc, r, va: referentVA, relocVA: getVA() + r.offset);
283 }
284}
285
286ConcatInputSection *macho::makeSyntheticInputSection(StringRef segName,
287 StringRef sectName,
288 uint32_t flags,
289 ArrayRef<uint8_t> data,
290 uint32_t align) {
291 Section &section =
292 *make<Section>(/*file=*/args: nullptr, args&: segName, args&: sectName, args&: flags, /*addr=*/args: 0);
293 auto isec = make<ConcatInputSection>(args&: section, args&: data, args&: align);
294 // Since this is an explicitly created 'fake' input section,
295 // it should not be dead stripped.
296 isec->live = true;
297 section.subsections.push_back(x: {.offset: 0, .isec: isec});
298 return isec;
299}
300
301void CStringInputSection::splitIntoPieces() {
302 size_t off = 0;
303 StringRef s = toStringRef(Input: data);
304 while (!s.empty()) {
305 size_t end = s.find(C: 0);
306 if (end == StringRef::npos)
307 fatal(msg: getLocation(off) + ": string is not null terminated");
308 uint32_t hash = deduplicateLiterals ? xxh3_64bits(data: s.take_front(N: end)) : 0;
309 pieces.emplace_back(args&: off, args&: hash);
310 size_t size = end + 1; // include null terminator
311 s = s.substr(Start: size);
312 off += size;
313 }
314}
315
316StringPiece &CStringInputSection::getStringPiece(uint64_t off) {
317 if (off >= data.size())
318 fatal(msg: toString(this) + ": offset is outside the section");
319
320 auto it =
321 partition_point(Range&: pieces, P: [=](StringPiece p) { return p.inSecOff <= off; });
322 return it[-1];
323}
324
325const StringPiece &CStringInputSection::getStringPiece(uint64_t off) const {
326 return const_cast<CStringInputSection *>(this)->getStringPiece(off);
327}
328
329size_t CStringInputSection::getStringPieceIndex(uint64_t off) const {
330 if (off >= data.size())
331 fatal(msg: toString(this) + ": offset is outside the section");
332
333 auto it =
334 partition_point(Range: pieces, P: [=](StringPiece p) { return p.inSecOff <= off; });
335 return std::distance(first: pieces.begin(), last: it) - 1;
336}
337
338uint64_t CStringInputSection::getOffset(uint64_t off) const {
339 const StringPiece &piece = getStringPiece(off);
340 uint64_t addend = off - piece.inSecOff;
341 return piece.outSecOff + addend;
342}
343
344WordLiteralInputSection::WordLiteralInputSection(const Section &section,
345 ArrayRef<uint8_t> data,
346 uint32_t align)
347 : InputSection(WordLiteralKind, section, data, align) {
348 switch (sectionType(flags: getFlags())) {
349 case S_4BYTE_LITERALS:
350 power2LiteralSize = 2;
351 break;
352 case S_8BYTE_LITERALS:
353 power2LiteralSize = 3;
354 break;
355 case S_16BYTE_LITERALS:
356 power2LiteralSize = 4;
357 break;
358 default:
359 llvm_unreachable("invalid literal section type");
360 }
361
362 live.resize(N: data.size() >> power2LiteralSize, t: !config->deadStrip);
363}
364
365uint64_t WordLiteralInputSection::getOffset(uint64_t off) const {
366 if (off >= data.size())
367 fatal(msg: toString(this) + ": offset is outside the section");
368
369 auto *osec = cast<WordLiteralSection>(Val: parent);
370 const uintptr_t buf = reinterpret_cast<uintptr_t>(data.data());
371 switch (sectionType(flags: getFlags())) {
372 case S_4BYTE_LITERALS:
373 return osec->getLiteral4Offset(buf: buf + (off & ~3LLU)) | (off & 3);
374 case S_8BYTE_LITERALS:
375 return osec->getLiteral8Offset(buf: buf + (off & ~7LLU)) | (off & 7);
376 case S_16BYTE_LITERALS:
377 return osec->getLiteral16Offset(buf: buf + (off & ~15LLU)) | (off & 15);
378 default:
379 llvm_unreachable("invalid literal section type");
380 }
381}
382
383bool macho::isCodeSection(const InputSection *isec) {
384 return sections::isCodeSection(name: isec->getName(), segName: isec->getSegName(),
385 flags: isec->getFlags());
386}
387
388bool macho::isCfStringSection(const InputSection *isec) {
389 return isec->getName() == section_names::cfString &&
390 isec->getSegName() == segment_names::data;
391}
392
393bool macho::isClassRefsSection(const InputSection *isec) {
394 return isec->getName() == section_names::objcClassRefs &&
395 isec->getSegName() == segment_names::data;
396}
397
398bool macho::isSelRefsSection(const InputSection *isec) {
399 return isec->getName() == section_names::objcSelrefs &&
400 isec->getSegName() == segment_names::data;
401}
402
403bool macho::isEhFrameSection(const InputSection *isec) {
404 return isec->getName() == section_names::ehFrame &&
405 isec->getSegName() == segment_names::text;
406}
407
408bool macho::isGccExceptTabSection(const InputSection *isec) {
409 return isec->getName() == section_names::gccExceptTab &&
410 isec->getSegName() == segment_names::text;
411}
412
413std::string lld::toString(const InputSection *isec) {
414 return (toString(file: isec->getFile()) + ":(" + isec->getName() + ")").str();
415}
416