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 symVA = sym->resolveGotVA();
105 } else if (relocAttrs.hasAttr(b: RelocAttrBits::TLV)) {
106 symVA = sym->resolveTlvVA();
107 } else {
108 symVA = sym->getVA();
109 }
110 return symVA + offset;
111}
112
113const Defined *InputSection::getContainingSymbol(uint64_t off) const {
114 auto *nextSym = llvm::upper_bound(
115 Range: symbols, Value&: off, C: [](uint64_t a, const Defined *b) { return a < b->value; });
116 if (nextSym == symbols.begin())
117 return nullptr;
118 return *std::prev(x: nextSym);
119}
120
121std::string InputSection::getLocation(uint64_t off) const {
122 // First, try to find a symbol that's near the offset. Use it as a reference
123 // point.
124 if (auto *sym = getContainingSymbol(off))
125 return (toString(file: getFile()) + ":(symbol " + toString(*sym) + "+0x" +
126 Twine::utohexstr(Val: off - sym->value) + ")")
127 .str();
128
129 // If that fails, use the section itself as a reference point.
130 for (const Subsection &subsec : section.subsections) {
131 if (subsec.isec == this) {
132 off += subsec.offset;
133 break;
134 }
135 }
136
137 return (toString(file: getFile()) + ":(" + getName() + "+0x" +
138 Twine::utohexstr(Val: off) + ")")
139 .str();
140}
141
142std::string InputSection::getSourceLocation(uint64_t off) const {
143 auto *obj = dyn_cast_or_null<ObjFile>(Val: getFile());
144 if (!obj)
145 return {};
146
147 DWARFCache *dwarf = obj->getDwarf();
148 if (!dwarf)
149 return std::string();
150
151 for (const Subsection &subsec : section.subsections) {
152 if (subsec.isec == this) {
153 off += subsec.offset;
154 break;
155 }
156 }
157
158 auto createMsg = [&](StringRef path, unsigned line) {
159 std::string filename = sys::path::filename(path).str();
160 std::string lineStr = (":" + Twine(line)).str();
161 if (filename == path)
162 return filename + lineStr;
163 return (filename + lineStr + " (" + path + lineStr + ")").str();
164 };
165
166 // First, look up a function for a given offset.
167 if (std::optional<DILineInfo> li = dwarf->getDILineInfo(
168 offset: section.addr + off, sectionIndex: object::SectionedAddress::UndefSection))
169 return createMsg(li->FileName, li->Line);
170
171 // If it failed, look up again as a variable.
172 if (const Defined *sym = getContainingSymbol(off)) {
173 // Symbols are generally prefixed with an underscore, which is not included
174 // in the debug information.
175 StringRef symName = sym->getName();
176 symName.consume_front(Prefix: "_");
177
178 if (std::optional<std::pair<std::string, unsigned>> fileLine =
179 dwarf->getVariableLoc(name: symName))
180 return createMsg(fileLine->first, fileLine->second);
181 }
182
183 // Try to get the source file's name from the DWARF information.
184 if (obj->compileUnit)
185 return obj->sourceFile();
186
187 return {};
188}
189
190const Relocation *InputSection::getRelocAt(uint32_t off) const {
191 auto it = llvm::find_if(Range: relocs,
192 P: [=](const Relocation &r) { return r.offset == off; });
193 if (it == relocs.end())
194 return nullptr;
195 return &*it;
196}
197
198void ConcatInputSection::foldIdentical(ConcatInputSection *copy,
199 Symbol::ICFFoldKind foldKind) {
200 align = std::max(a: align, b: copy->align);
201 copy->live = false;
202 copy->wasCoalesced = true;
203 copy->replacement = this;
204 for (auto &copySym : copy->symbols)
205 copySym->identicalCodeFoldingKind = foldKind;
206
207 if (copy->symbols.empty())
208 return;
209 auto *it = copy->symbols.begin();
210 // The first symbol in the merged section (symbols.front()) must keep its
211 // unwind entry. If this section is empty, the copy's first symbol becomes the
212 // new front, so we skip clearing it.
213 if (symbols.empty())
214 ++it;
215 for (; it != copy->symbols.end(); ++it) {
216 assert((*it)->value == 0);
217 (*it)->originalUnwindEntry = nullptr;
218 }
219 symbols.insert(I: symbols.end(), From: copy->symbols.begin(), To: copy->symbols.end());
220 copy->symbols.clear();
221}
222
223void ConcatInputSection::writeTo(uint8_t *buf) {
224 assert(!shouldOmitFromOutput());
225
226 if (getFileSize() == 0)
227 return;
228
229 memcpy(dest: buf, src: data.data(), n: data.size());
230
231 for (size_t i = 0; i < relocs.size(); i++) {
232 const Relocation &r = relocs[i];
233 uint8_t *loc = buf + r.offset;
234 uint64_t referentVA = 0;
235
236 const bool needsFixup = config->emitChainedFixups &&
237 target->hasAttr(type: r.type, bit: RelocAttrBits::UNSIGNED);
238 if (target->hasAttr(type: r.type, bit: RelocAttrBits::SUBTRAHEND)) {
239 const Symbol *fromSym = cast<Symbol *>(Val: r.referent);
240 const Relocation &minuend = relocs[++i];
241 uint64_t minuendVA;
242 if (const Symbol *toSym = minuend.referent.dyn_cast<Symbol *>())
243 minuendVA = toSym->getVA() + minuend.addend;
244 else {
245 auto *referentIsec = cast<InputSection *>(Val: minuend.referent);
246 assert(!::shouldOmitFromOutput(referentIsec));
247 minuendVA = referentIsec->getVA(off: minuend.addend);
248 }
249 referentVA = minuendVA - fromSym->getVA();
250 } else if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) {
251 if (target->hasAttr(type: r.type, bit: RelocAttrBits::LOAD) &&
252 !referentSym->isInGot())
253 target->relaxGotLoad(loc, type: r.type);
254 // For dtrace symbols, do not handle them as normal undefined symbols
255 if (referentSym->getName().starts_with(Prefix: "___dtrace_")) {
256 // Change dtrace call site to pre-defined instructions
257 target->handleDtraceReloc(sym: referentSym, r, loc);
258 continue;
259 }
260 referentVA = resolveSymbolOffsetVA(sym: referentSym, type: r.type, offset: r.addend);
261
262 if (isThreadLocalVariables(flags: getFlags()) && isa<Defined>(Val: referentSym)) {
263 // References from thread-local variable sections are treated as offsets
264 // relative to the start of the thread-local data memory area, which
265 // is initialized via copying all the TLV data sections (which are all
266 // contiguous).
267 referentVA -= firstTLVDataSection->addr;
268 } else if (needsFixup) {
269 writeChainedFixup(buf: loc, sym: referentSym, addend: r.addend);
270 continue;
271 }
272 } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
273 assert(!::shouldOmitFromOutput(referentIsec));
274 referentVA = referentIsec->getVA(off: r.addend);
275
276 if (needsFixup) {
277 writeChainedRebase(buf: loc, targetVA: referentVA);
278 continue;
279 }
280 }
281 target->relocateOne(loc, r, va: referentVA, relocVA: getVA() + r.offset);
282 }
283}
284
285ConcatInputSection *macho::makeSyntheticInputSection(StringRef segName,
286 StringRef sectName,
287 uint32_t flags,
288 ArrayRef<uint8_t> data,
289 uint32_t align) {
290 Section &section =
291 *make<Section>(/*file=*/args: nullptr, args&: segName, args&: sectName, args&: flags, /*addr=*/args: 0);
292 auto isec = make<ConcatInputSection>(args&: section, args&: data, args&: align);
293 // Since this is an explicitly created 'fake' input section,
294 // it should not be dead stripped.
295 isec->live = true;
296 section.subsections.push_back(x: {.offset: 0, .isec: isec});
297 return isec;
298}
299
300void CStringInputSection::splitIntoPieces() {
301 size_t off = 0;
302 StringRef s = toStringRef(Input: data);
303 while (!s.empty()) {
304 size_t end = s.find(C: 0);
305 if (end == StringRef::npos)
306 fatal(msg: getLocation(off) + ": string is not null terminated");
307 uint32_t hash = deduplicateLiterals ? xxh3_64bits(data: s.take_front(N: end)) : 0;
308 pieces.emplace_back(args&: off, args&: hash);
309 size_t size = end + 1; // include null terminator
310 s = s.substr(Start: size);
311 off += size;
312 }
313}
314
315StringPiece &CStringInputSection::getStringPiece(uint64_t off) {
316 if (off >= data.size())
317 fatal(msg: toString(this) + ": offset is outside the section");
318
319 auto it =
320 partition_point(Range&: pieces, P: [=](StringPiece p) { return p.inSecOff <= off; });
321 return it[-1];
322}
323
324const StringPiece &CStringInputSection::getStringPiece(uint64_t off) const {
325 return const_cast<CStringInputSection *>(this)->getStringPiece(off);
326}
327
328size_t CStringInputSection::getStringPieceIndex(uint64_t off) const {
329 if (off >= data.size())
330 fatal(msg: toString(this) + ": offset is outside the section");
331
332 auto it =
333 partition_point(Range: pieces, P: [=](StringPiece p) { return p.inSecOff <= off; });
334 return std::distance(first: pieces.begin(), last: it) - 1;
335}
336
337uint64_t CStringInputSection::getOffset(uint64_t off) const {
338 const StringPiece &piece = getStringPiece(off);
339 uint64_t addend = off - piece.inSecOff;
340 return piece.outSecOff + addend;
341}
342
343WordLiteralInputSection::WordLiteralInputSection(const Section &section,
344 ArrayRef<uint8_t> data,
345 uint32_t align)
346 : InputSection(WordLiteralKind, section, data, align) {
347 switch (sectionType(flags: getFlags())) {
348 case S_4BYTE_LITERALS:
349 power2LiteralSize = 2;
350 break;
351 case S_8BYTE_LITERALS:
352 power2LiteralSize = 3;
353 break;
354 case S_16BYTE_LITERALS:
355 power2LiteralSize = 4;
356 break;
357 default:
358 llvm_unreachable("invalid literal section type");
359 }
360
361 live.resize(N: data.size() >> power2LiteralSize, t: !config->deadStrip);
362}
363
364uint64_t WordLiteralInputSection::getOffset(uint64_t off) const {
365 if (off >= data.size())
366 fatal(msg: toString(this) + ": offset is outside the section");
367
368 auto *osec = cast<WordLiteralSection>(Val: parent);
369 const uintptr_t buf = reinterpret_cast<uintptr_t>(data.data());
370 switch (sectionType(flags: getFlags())) {
371 case S_4BYTE_LITERALS:
372 return osec->getLiteral4Offset(buf: buf + (off & ~3LLU)) | (off & 3);
373 case S_8BYTE_LITERALS:
374 return osec->getLiteral8Offset(buf: buf + (off & ~7LLU)) | (off & 7);
375 case S_16BYTE_LITERALS:
376 return osec->getLiteral16Offset(buf: buf + (off & ~15LLU)) | (off & 15);
377 default:
378 llvm_unreachable("invalid literal section type");
379 }
380}
381
382bool macho::isCodeSection(const InputSection *isec) {
383 return sections::isCodeSection(name: isec->getName(), segName: isec->getSegName(),
384 flags: isec->getFlags());
385}
386
387bool macho::isCfStringSection(const InputSection *isec) {
388 return isec->getName() == section_names::cfString &&
389 isec->getSegName() == segment_names::data;
390}
391
392bool macho::isClassRefsSection(const InputSection *isec) {
393 return isec->getName() == section_names::objcClassRefs &&
394 isec->getSegName() == segment_names::data;
395}
396
397bool macho::isSelRefsSection(const InputSection *isec) {
398 return isec->getName() == section_names::objcSelrefs &&
399 isec->getSegName() == segment_names::data;
400}
401
402bool macho::isEhFrameSection(const InputSection *isec) {
403 return isec->getName() == section_names::ehFrame &&
404 isec->getSegName() == segment_names::text;
405}
406
407bool macho::isGccExceptTabSection(const InputSection *isec) {
408 return isec->getName() == section_names::gccExceptTab &&
409 isec->getSegName() == segment_names::text;
410}
411
412std::string lld::toString(const InputSection *isec) {
413 return (toString(file: isec->getFile()) + ":(" + isec->getName() + ")").str();
414}
415