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>) + 88,
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   for (auto &copySym : copy->symbols)
86     copySym->wasIdenticalCodeFolded = true;
87 
88   // Merge the sorted vectors of symbols together.
89   auto it = symbols.begin();
90   for (auto copyIt = copy->symbols.begin(); copyIt != copy->symbols.end();) {
91     if (it == symbols.end()) {
92       symbols.push_back(*copyIt++);
93       it = symbols.end();
94     } else if ((*it)->value > (*copyIt)->value) {
95       std::swap(*it++, *copyIt);
96     } else {
97       ++it;
98     }
99   }
100   copy->symbols.clear();
101 
102   // Remove duplicate compact unwind info for symbols at the same address.
103   if (symbols.empty())
104     return;
105   it = symbols.begin();
106   uint64_t v = (*it)->value;
107   for (++it; it != symbols.end(); ++it) {
108     Defined *d = *it;
109     if (d->value == v)
110       d->unwindEntry = nullptr;
111     else
112       v = d->value;
113   }
114 }
115 
116 void ConcatInputSection::writeTo(uint8_t *buf) {
117   assert(!shouldOmitFromOutput());
118 
119   if (getFileSize() == 0)
120     return;
121 
122   memcpy(buf, data.data(), data.size());
123 
124   for (size_t i = 0; i < relocs.size(); i++) {
125     const Reloc &r = relocs[i];
126     uint8_t *loc = buf + r.offset;
127     uint64_t referentVA = 0;
128     if (target->hasAttr(r.type, RelocAttrBits::SUBTRAHEND)) {
129       const Symbol *fromSym = r.referent.get<Symbol *>();
130       const Reloc &minuend = relocs[++i];
131       uint64_t minuendVA;
132       if (const Symbol *toSym = minuend.referent.dyn_cast<Symbol *>())
133         minuendVA = toSym->getVA() + minuend.addend;
134       else {
135         auto *referentIsec = minuend.referent.get<InputSection *>();
136         assert(!::shouldOmitFromOutput(referentIsec));
137         minuendVA = referentIsec->getVA(minuend.addend);
138       }
139       referentVA = minuendVA - fromSym->getVA();
140     } else if (auto *referentSym = r.referent.dyn_cast<Symbol *>()) {
141       if (target->hasAttr(r.type, RelocAttrBits::LOAD) &&
142           !referentSym->isInGot())
143         target->relaxGotLoad(loc, r.type);
144       referentVA = resolveSymbolVA(referentSym, r.type) + r.addend;
145 
146       if (isThreadLocalVariables(getFlags())) {
147         // References from thread-local variable sections are treated as offsets
148         // relative to the start of the thread-local data memory area, which
149         // is initialized via copying all the TLV data sections (which are all
150         // contiguous).
151         if (isa<Defined>(referentSym))
152           referentVA -= firstTLVDataSection->addr;
153       }
154     } else if (auto *referentIsec = r.referent.dyn_cast<InputSection *>()) {
155       assert(!::shouldOmitFromOutput(referentIsec));
156       referentVA = referentIsec->getVA(r.addend);
157     }
158     target->relocateOne(loc, r, referentVA, getVA() + r.offset);
159   }
160 }
161 
162 ConcatInputSection *macho::makeSyntheticInputSection(StringRef segName,
163                                                      StringRef sectName,
164                                                      uint32_t flags,
165                                                      ArrayRef<uint8_t> data,
166                                                      uint32_t align) {
167   Section &section =
168       *make<Section>(/*file=*/nullptr, segName, sectName, flags, /*addr=*/0);
169   auto isec = make<ConcatInputSection>(section, data, align);
170   section.subsections.push_back({0, isec});
171   return isec;
172 }
173 
174 void CStringInputSection::splitIntoPieces() {
175   size_t off = 0;
176   StringRef s = toStringRef(data);
177   while (!s.empty()) {
178     size_t end = s.find(0);
179     if (end == StringRef::npos)
180       fatal(getLocation(off) + ": string is not null terminated");
181     size_t size = end + 1;
182     uint32_t hash = config->dedupLiterals ? xxHash64(s.substr(0, size)) : 0;
183     pieces.emplace_back(off, hash);
184     s = s.substr(size);
185     off += size;
186   }
187 }
188 
189 StringPiece &CStringInputSection::getStringPiece(uint64_t off) {
190   if (off >= data.size())
191     fatal(toString(this) + ": offset is outside the section");
192 
193   auto it =
194       partition_point(pieces, [=](StringPiece p) { return p.inSecOff <= off; });
195   return it[-1];
196 }
197 
198 const StringPiece &CStringInputSection::getStringPiece(uint64_t off) const {
199   return const_cast<CStringInputSection *>(this)->getStringPiece(off);
200 }
201 
202 uint64_t CStringInputSection::getOffset(uint64_t off) const {
203   const StringPiece &piece = getStringPiece(off);
204   uint64_t addend = off - piece.inSecOff;
205   return piece.outSecOff + addend;
206 }
207 
208 WordLiteralInputSection::WordLiteralInputSection(const Section &section,
209                                                  ArrayRef<uint8_t> data,
210                                                  uint32_t align)
211     : InputSection(WordLiteralKind, section, data, align) {
212   switch (sectionType(getFlags())) {
213   case S_4BYTE_LITERALS:
214     power2LiteralSize = 2;
215     break;
216   case S_8BYTE_LITERALS:
217     power2LiteralSize = 3;
218     break;
219   case S_16BYTE_LITERALS:
220     power2LiteralSize = 4;
221     break;
222   default:
223     llvm_unreachable("invalid literal section type");
224   }
225 
226   live.resize(data.size() >> power2LiteralSize, !config->deadStrip);
227 }
228 
229 uint64_t WordLiteralInputSection::getOffset(uint64_t off) const {
230   auto *osec = cast<WordLiteralSection>(parent);
231   const uintptr_t buf = reinterpret_cast<uintptr_t>(data.data());
232   switch (sectionType(getFlags())) {
233   case S_4BYTE_LITERALS:
234     return osec->getLiteral4Offset(buf + (off & ~3LLU)) | (off & 3);
235   case S_8BYTE_LITERALS:
236     return osec->getLiteral8Offset(buf + (off & ~7LLU)) | (off & 7);
237   case S_16BYTE_LITERALS:
238     return osec->getLiteral16Offset(buf + (off & ~15LLU)) | (off & 15);
239   default:
240     llvm_unreachable("invalid literal section type");
241   }
242 }
243 
244 bool macho::isCodeSection(const InputSection *isec) {
245   uint32_t type = sectionType(isec->getFlags());
246   if (type != S_REGULAR && type != S_COALESCED)
247     return false;
248 
249   uint32_t attr = isec->getFlags() & SECTION_ATTRIBUTES_USR;
250   if (attr == S_ATTR_PURE_INSTRUCTIONS)
251     return true;
252 
253   if (isec->getSegName() == segment_names::text)
254     return StringSwitch<bool>(isec->getName())
255         .Cases(section_names::textCoalNt, section_names::staticInit, true)
256         .Default(false);
257 
258   return false;
259 }
260 
261 bool macho::isCfStringSection(const InputSection *isec) {
262   return isec->getName() == section_names::cfString &&
263          isec->getSegName() == segment_names::data;
264 }
265 
266 bool macho::isClassRefsSection(const InputSection *isec) {
267   return isec->getName() == section_names::objcClassRefs &&
268          isec->getSegName() == segment_names::data;
269 }
270 
271 std::string lld::toString(const InputSection *isec) {
272   return (toString(isec->getFile()) + ":(" + isec->getName() + ")").str();
273 }
274