1 //===- InputSection.h -------------------------------------------*- C++ -*-===//
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 #ifndef LLD_MACHO_INPUT_SECTION_H
10 #define LLD_MACHO_INPUT_SECTION_H
11 
12 #include "Config.h"
13 #include "Relocations.h"
14 #include "Symbols.h"
15 
16 #include "lld/Common/LLVM.h"
17 #include "lld/Common/Memory.h"
18 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/BitVector.h"
20 #include "llvm/ADT/CachedHashString.h"
21 #include "llvm/ADT/TinyPtrVector.h"
22 #include "llvm/BinaryFormat/MachO.h"
23 
24 namespace lld {
25 namespace macho {
26 
27 class InputFile;
28 class OutputSection;
29 
30 class InputSection {
31 public:
32   enum Kind : uint8_t {
33     ConcatKind,
34     CStringLiteralKind,
35     WordLiteralKind,
36   };
37 
38   Kind kind() const { return sectionKind; }
39   virtual ~InputSection() = default;
40   virtual uint64_t getSize() const { return data.size(); }
41   virtual bool empty() const { return data.empty(); }
42   InputFile *getFile() const { return section.file; }
43   StringRef getName() const { return section.name; }
44   StringRef getSegName() const { return section.segname; }
45   uint32_t getFlags() const { return section.flags; }
46   uint64_t getFileSize() const;
47   // Translates \p off -- an offset relative to this InputSection -- into an
48   // offset from the beginning of its parent OutputSection.
49   virtual uint64_t getOffset(uint64_t off) const = 0;
50   // The offset from the beginning of the file.
51   uint64_t getVA(uint64_t off) const;
52   // Return a user-friendly string for use in diagnostics.
53   std::string getLocation(uint64_t off) const;
54   // Whether the data at \p off in this InputSection is live.
55   virtual bool isLive(uint64_t off) const = 0;
56   virtual void markLive(uint64_t off) = 0;
57   virtual InputSection *canonical() { return this; }
58   virtual const InputSection *canonical() const { return this; }
59 
60 protected:
61   InputSection(Kind kind, const Section &section, ArrayRef<uint8_t> data,
62                uint32_t align)
63       : sectionKind(kind), align(align), data(data), section(section) {}
64 
65   InputSection(const InputSection &rhs)
66       : sectionKind(rhs.sectionKind), align(rhs.align), data(rhs.data),
67         section(rhs.section) {}
68 
69   Kind sectionKind;
70 
71 public:
72   // is address assigned?
73   bool isFinal = false;
74   // keep the address of the symbol(s) in this section unique in the final
75   // binary ?
76   bool keepUnique = false;
77   uint32_t align = 1;
78 
79   OutputSection *parent = nullptr;
80   ArrayRef<uint8_t> data;
81   std::vector<Reloc> relocs;
82   // The symbols that belong to this InputSection, sorted by value. With
83   // .subsections_via_symbols, there is typically only one element here.
84   llvm::TinyPtrVector<Defined *> symbols;
85 
86 protected:
87   const Section &section;
88 };
89 
90 // ConcatInputSections are combined into (Concat)OutputSections through simple
91 // concatenation, in contrast with literal sections which may have their
92 // contents merged before output.
93 class ConcatInputSection final : public InputSection {
94 public:
95   ConcatInputSection(const Section &section, ArrayRef<uint8_t> data,
96                      uint32_t align = 1)
97       : InputSection(ConcatKind, section, data, align) {}
98 
99   uint64_t getOffset(uint64_t off) const override { return outSecOff + off; }
100   uint64_t getVA() const { return InputSection::getVA(0); }
101   // ConcatInputSections are entirely live or dead, so the offset is irrelevant.
102   bool isLive(uint64_t off) const override { return live; }
103   void markLive(uint64_t off) override { live = true; }
104   bool isCoalescedWeak() const { return wasCoalesced && symbols.empty(); }
105   bool shouldOmitFromOutput() const { return !live || isCoalescedWeak(); }
106   void writeTo(uint8_t *buf);
107 
108   void foldIdentical(ConcatInputSection *redundant);
109   ConcatInputSection *canonical() override {
110     return replacement ? replacement : this;
111   }
112   const InputSection *canonical() const override {
113     return replacement ? replacement : this;
114   }
115 
116   static bool classof(const InputSection *isec) {
117     return isec->kind() == ConcatKind;
118   }
119 
120   // Points to the surviving section after this one is folded by ICF
121   ConcatInputSection *replacement = nullptr;
122   // Equivalence-class ID for ICF
123   uint32_t icfEqClass[2] = {0, 0};
124 
125   // With subsections_via_symbols, most symbols have their own InputSection,
126   // and for weak symbols (e.g. from inline functions), only the
127   // InputSection from one translation unit will make it to the output,
128   // while all copies in other translation units are coalesced into the
129   // first and not copied to the output.
130   bool wasCoalesced = false;
131   bool live = !config->deadStrip;
132   bool hasCallSites = false;
133   // This variable has two usages. Initially, it represents the input order.
134   // After assignAddresses is called, it represents the offset from the
135   // beginning of the output section this section was assigned to.
136   uint64_t outSecOff = 0;
137 };
138 
139 // Initialize a fake InputSection that does not belong to any InputFile.
140 ConcatInputSection *makeSyntheticInputSection(StringRef segName,
141                                               StringRef sectName,
142                                               uint32_t flags = 0,
143                                               ArrayRef<uint8_t> data = {},
144                                               uint32_t align = 1);
145 
146 // Helper functions to make it easy to sprinkle asserts.
147 
148 inline bool shouldOmitFromOutput(InputSection *isec) {
149   return isa<ConcatInputSection>(isec) &&
150          cast<ConcatInputSection>(isec)->shouldOmitFromOutput();
151 }
152 
153 inline bool isCoalescedWeak(InputSection *isec) {
154   return isa<ConcatInputSection>(isec) &&
155          cast<ConcatInputSection>(isec)->isCoalescedWeak();
156 }
157 
158 // We allocate a lot of these and binary search on them, so they should be as
159 // compact as possible. Hence the use of 31 rather than 64 bits for the hash.
160 struct StringPiece {
161   // Offset from the start of the containing input section.
162   uint32_t inSecOff;
163   uint32_t live : 1;
164   // Only set if deduplicating literals
165   uint32_t hash : 31;
166   // Offset from the start of the containing output section.
167   uint64_t outSecOff = 0;
168 
169   StringPiece(uint64_t off, uint32_t hash)
170       : inSecOff(off), live(!config->deadStrip), hash(hash) {}
171 };
172 
173 static_assert(sizeof(StringPiece) == 16, "StringPiece is too big!");
174 
175 // CStringInputSections are composed of multiple null-terminated string
176 // literals, which we represent using StringPieces. These literals can be
177 // deduplicated and tail-merged, so translating offsets between the input and
178 // outputs sections is more complicated.
179 //
180 // NOTE: One significant difference between LLD and ld64 is that we merge all
181 // cstring literals, even those referenced directly by non-private symbols.
182 // ld64 is more conservative and does not do that. This was mostly done for
183 // implementation simplicity; if we find programs that need the more
184 // conservative behavior we can certainly implement that.
185 class CStringInputSection final : public InputSection {
186 public:
187   CStringInputSection(const Section &section, ArrayRef<uint8_t> data,
188                       uint32_t align)
189       : InputSection(CStringLiteralKind, section, data, align) {}
190   uint64_t getOffset(uint64_t off) const override;
191   bool isLive(uint64_t off) const override { return getStringPiece(off).live; }
192   void markLive(uint64_t off) override { getStringPiece(off).live = true; }
193   // Find the StringPiece that contains this offset.
194   StringPiece &getStringPiece(uint64_t off);
195   const StringPiece &getStringPiece(uint64_t off) const;
196   // Split at each null byte.
197   void splitIntoPieces();
198 
199   LLVM_ATTRIBUTE_ALWAYS_INLINE
200   StringRef getStringRef(size_t i) const {
201     size_t begin = pieces[i].inSecOff;
202     size_t end =
203         (pieces.size() - 1 == i) ? data.size() : pieces[i + 1].inSecOff;
204     return toStringRef(data.slice(begin, end - begin));
205   }
206 
207   // Returns i'th piece as a CachedHashStringRef. This function is very hot when
208   // string merging is enabled, so we want to inline.
209   LLVM_ATTRIBUTE_ALWAYS_INLINE
210   llvm::CachedHashStringRef getCachedHashStringRef(size_t i) const {
211     assert(config->dedupLiterals);
212     return {getStringRef(i), pieces[i].hash};
213   }
214 
215   static bool classof(const InputSection *isec) {
216     return isec->kind() == CStringLiteralKind;
217   }
218 
219   std::vector<StringPiece> pieces;
220 };
221 
222 class WordLiteralInputSection final : public InputSection {
223 public:
224   WordLiteralInputSection(const Section &section, ArrayRef<uint8_t> data,
225                           uint32_t align);
226   uint64_t getOffset(uint64_t off) const override;
227   bool isLive(uint64_t off) const override {
228     return live[off >> power2LiteralSize];
229   }
230   void markLive(uint64_t off) override {
231     live[off >> power2LiteralSize] = true;
232   }
233 
234   static bool classof(const InputSection *isec) {
235     return isec->kind() == WordLiteralKind;
236   }
237 
238 private:
239   unsigned power2LiteralSize;
240   // The liveness of data[off] is tracked by live[off >> power2LiteralSize].
241   llvm::BitVector live;
242 };
243 
244 inline uint8_t sectionType(uint32_t flags) {
245   return flags & llvm::MachO::SECTION_TYPE;
246 }
247 
248 inline bool isZeroFill(uint32_t flags) {
249   return llvm::MachO::isVirtualSection(sectionType(flags));
250 }
251 
252 inline bool isThreadLocalVariables(uint32_t flags) {
253   return sectionType(flags) == llvm::MachO::S_THREAD_LOCAL_VARIABLES;
254 }
255 
256 // These sections contain the data for initializing thread-local variables.
257 inline bool isThreadLocalData(uint32_t flags) {
258   return sectionType(flags) == llvm::MachO::S_THREAD_LOCAL_REGULAR ||
259          sectionType(flags) == llvm::MachO::S_THREAD_LOCAL_ZEROFILL;
260 }
261 
262 inline bool isDebugSection(uint32_t flags) {
263   return (flags & llvm::MachO::SECTION_ATTRIBUTES_USR) ==
264          llvm::MachO::S_ATTR_DEBUG;
265 }
266 
267 inline bool isWordLiteralSection(uint32_t flags) {
268   return sectionType(flags) == llvm::MachO::S_4BYTE_LITERALS ||
269          sectionType(flags) == llvm::MachO::S_8BYTE_LITERALS ||
270          sectionType(flags) == llvm::MachO::S_16BYTE_LITERALS;
271 }
272 
273 bool isCodeSection(const InputSection *);
274 bool isCfStringSection(const InputSection *);
275 bool isClassRefsSection(const InputSection *);
276 bool isEhFrameSection(const InputSection *);
277 
278 extern std::vector<ConcatInputSection *> inputSections;
279 
280 namespace section_names {
281 
282 constexpr const char authGot[] = "__auth_got";
283 constexpr const char authPtr[] = "__auth_ptr";
284 constexpr const char binding[] = "__binding";
285 constexpr const char bitcodeBundle[] = "__bundle";
286 constexpr const char cString[] = "__cstring";
287 constexpr const char cfString[] = "__cfstring";
288 constexpr const char cgProfile[] = "__cg_profile";
289 constexpr const char codeSignature[] = "__code_signature";
290 constexpr const char common[] = "__common";
291 constexpr const char compactUnwind[] = "__compact_unwind";
292 constexpr const char data[] = "__data";
293 constexpr const char debugAbbrev[] = "__debug_abbrev";
294 constexpr const char debugInfo[] = "__debug_info";
295 constexpr const char debugStr[] = "__debug_str";
296 constexpr const char ehFrame[] = "__eh_frame";
297 constexpr const char gccExceptTab[] = "__gcc_except_tab";
298 constexpr const char export_[] = "__export";
299 constexpr const char dataInCode[] = "__data_in_code";
300 constexpr const char functionStarts[] = "__func_starts";
301 constexpr const char got[] = "__got";
302 constexpr const char header[] = "__mach_header";
303 constexpr const char indirectSymbolTable[] = "__ind_sym_tab";
304 constexpr const char const_[] = "__const";
305 constexpr const char lazySymbolPtr[] = "__la_symbol_ptr";
306 constexpr const char lazyBinding[] = "__lazy_binding";
307 constexpr const char literals[] = "__literals";
308 constexpr const char moduleInitFunc[] = "__mod_init_func";
309 constexpr const char moduleTermFunc[] = "__mod_term_func";
310 constexpr const char nonLazySymbolPtr[] = "__nl_symbol_ptr";
311 constexpr const char objcCatList[] = "__objc_catlist";
312 constexpr const char objcClassList[] = "__objc_classlist";
313 constexpr const char objcClassRefs[] = "__objc_classrefs";
314 constexpr const char objcConst[] = "__objc_const";
315 constexpr const char objcImageInfo[] = "__objc_imageinfo";
316 constexpr const char objcNonLazyCatList[] = "__objc_nlcatlist";
317 constexpr const char objcNonLazyClassList[] = "__objc_nlclslist";
318 constexpr const char objcProtoList[] = "__objc_protolist";
319 constexpr const char pageZero[] = "__pagezero";
320 constexpr const char pointers[] = "__pointers";
321 constexpr const char rebase[] = "__rebase";
322 constexpr const char staticInit[] = "__StaticInit";
323 constexpr const char stringTable[] = "__string_table";
324 constexpr const char stubHelper[] = "__stub_helper";
325 constexpr const char stubs[] = "__stubs";
326 constexpr const char swift[] = "__swift";
327 constexpr const char symbolTable[] = "__symbol_table";
328 constexpr const char textCoalNt[] = "__textcoal_nt";
329 constexpr const char text[] = "__text";
330 constexpr const char threadPtrs[] = "__thread_ptrs";
331 constexpr const char threadVars[] = "__thread_vars";
332 constexpr const char unwindInfo[] = "__unwind_info";
333 constexpr const char weakBinding[] = "__weak_binding";
334 constexpr const char zeroFill[] = "__zerofill";
335 constexpr const char addrSig[] = "__llvm_addrsig";
336 
337 } // namespace section_names
338 
339 } // namespace macho
340 
341 std::string toString(const macho::InputSection *);
342 
343 } // namespace lld
344 
345 #endif
346