1 //===- LinkerScript.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_ELF_LINKER_SCRIPT_H
10 #define LLD_ELF_LINKER_SCRIPT_H
11 
12 #include "Config.h"
13 #include "Writer.h"
14 #include "lld/Common/LLVM.h"
15 #include "lld/Common/Strings.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/MapVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include <cstddef>
21 #include <cstdint>
22 #include <functional>
23 #include <memory>
24 
25 namespace lld {
26 namespace elf {
27 
28 class Defined;
29 class InputFile;
30 class InputSection;
31 class InputSectionBase;
32 class OutputSection;
33 class SectionBase;
34 class ThunkSection;
35 
36 // This represents an r-value in the linker script.
37 struct ExprValue {
38   ExprValue(SectionBase *sec, bool forceAbsolute, uint64_t val,
39             const Twine &loc)
40       : sec(sec), val(val), forceAbsolute(forceAbsolute), loc(loc.str()) {}
41 
42   ExprValue(uint64_t val) : ExprValue(nullptr, false, val, "") {}
43 
44   bool isAbsolute() const { return forceAbsolute || sec == nullptr; }
45   uint64_t getValue() const;
46   uint64_t getSecAddr() const;
47   uint64_t getSectionOffset() const;
48 
49   // If a value is relative to a section, it has a non-null Sec.
50   SectionBase *sec;
51 
52   uint64_t val;
53   uint64_t alignment = 1;
54 
55   // The original st_type if the expression represents a symbol. Any operation
56   // resets type to STT_NOTYPE.
57   uint8_t type = llvm::ELF::STT_NOTYPE;
58 
59   // True if this expression is enclosed in ABSOLUTE().
60   // This flag affects the return value of getValue().
61   bool forceAbsolute;
62 
63   // Original source location. Used for error messages.
64   std::string loc;
65 };
66 
67 // This represents an expression in the linker script.
68 // ScriptParser::readExpr reads an expression and returns an Expr.
69 // Later, we evaluate the expression by calling the function.
70 using Expr = std::function<ExprValue()>;
71 
72 // This enum is used to implement linker script SECTIONS command.
73 // https://sourceware.org/binutils/docs/ld/SECTIONS.html#SECTIONS
74 enum SectionsCommandKind {
75   AssignmentKind, // . = expr or <sym> = expr
76   OutputSectionKind,
77   InputSectionKind,
78   ByteKind    // BYTE(expr), SHORT(expr), LONG(expr) or QUAD(expr)
79 };
80 
81 struct SectionCommand {
82   SectionCommand(int k) : kind(k) {}
83   int kind;
84 };
85 
86 // This represents ". = <expr>" or "<symbol> = <expr>".
87 struct SymbolAssignment : SectionCommand {
88   SymbolAssignment(StringRef name, Expr e, std::string loc)
89       : SectionCommand(AssignmentKind), name(name), expression(e),
90         location(loc) {}
91 
92   static bool classof(const SectionCommand *c) {
93     return c->kind == AssignmentKind;
94   }
95 
96   // The LHS of an expression. Name is either a symbol name or ".".
97   StringRef name;
98   Defined *sym = nullptr;
99 
100   // The RHS of an expression.
101   Expr expression;
102 
103   // Command attributes for PROVIDE, HIDDEN and PROVIDE_HIDDEN.
104   bool provide = false;
105   bool hidden = false;
106 
107   // Holds file name and line number for error reporting.
108   std::string location;
109 
110   // A string representation of this command. We use this for -Map.
111   std::string commandString;
112 
113   // Address of this assignment command.
114   uint64_t addr;
115 
116   // Size of this assignment command. This is usually 0, but if
117   // you move '.' this may be greater than 0.
118   uint64_t size;
119 };
120 
121 // Linker scripts allow additional constraints to be put on output sections.
122 // If an output section is marked as ONLY_IF_RO, the section is created
123 // only if its input sections are read-only. Likewise, an output section
124 // with ONLY_IF_RW is created if all input sections are RW.
125 enum class ConstraintKind { NoConstraint, ReadOnly, ReadWrite };
126 
127 // This struct is used to represent the location and size of regions of
128 // target memory. Instances of the struct are created by parsing the
129 // MEMORY command.
130 struct MemoryRegion {
131   MemoryRegion(StringRef name, Expr origin, Expr length, uint32_t flags,
132                uint32_t invFlags, uint32_t negFlags, uint32_t negInvFlags)
133       : name(std::string(name)), origin(origin), length(length), flags(flags),
134         invFlags(invFlags), negFlags(negFlags), negInvFlags(negInvFlags) {}
135 
136   std::string name;
137   Expr origin;
138   Expr length;
139   // A section can be assigned to the region if any of these ELF section flags
140   // are set...
141   uint32_t flags;
142   // ... or any of these flags are not set.
143   // For example, the memory region attribute "r" maps to SHF_WRITE.
144   uint32_t invFlags;
145   // A section cannot be assigned to the region if any of these ELF section
146   // flags are set...
147   uint32_t negFlags;
148   // ... or any of these flags are not set.
149   // For example, the memory region attribute "!r" maps to SHF_WRITE.
150   uint32_t negInvFlags;
151   uint64_t curPos = 0;
152 
153   bool compatibleWith(uint32_t secFlags) const {
154     if ((secFlags & negFlags) || (~secFlags & negInvFlags))
155       return false;
156     return (secFlags & flags) || (~secFlags & invFlags);
157   }
158 };
159 
160 // This struct represents one section match pattern in SECTIONS() command.
161 // It can optionally have negative match pattern for EXCLUDED_FILE command.
162 // Also it may be surrounded with SORT() command, so contains sorting rules.
163 class SectionPattern {
164   StringMatcher excludedFilePat;
165 
166   // Cache of the most recent input argument and result of excludesFile().
167   mutable llvm::Optional<std::pair<const InputFile *, bool>> excludesFileCache;
168 
169 public:
170   SectionPattern(StringMatcher &&pat1, StringMatcher &&pat2)
171       : excludedFilePat(pat1), sectionPat(pat2),
172         sortOuter(SortSectionPolicy::Default),
173         sortInner(SortSectionPolicy::Default) {}
174 
175   bool excludesFile(const InputFile *file) const;
176 
177   StringMatcher sectionPat;
178   SortSectionPolicy sortOuter;
179   SortSectionPolicy sortInner;
180 };
181 
182 class InputSectionDescription : public SectionCommand {
183   SingleStringMatcher filePat;
184 
185   // Cache of the most recent input argument and result of matchesFile().
186   mutable llvm::Optional<std::pair<const InputFile *, bool>> matchesFileCache;
187 
188 public:
189   InputSectionDescription(StringRef filePattern, uint64_t withFlags = 0,
190                           uint64_t withoutFlags = 0)
191       : SectionCommand(InputSectionKind), filePat(filePattern),
192         withFlags(withFlags), withoutFlags(withoutFlags) {}
193 
194   static bool classof(const SectionCommand *c) {
195     return c->kind == InputSectionKind;
196   }
197 
198   bool matchesFile(const InputFile *file) const;
199 
200   // Input sections that matches at least one of SectionPatterns
201   // will be associated with this InputSectionDescription.
202   SmallVector<SectionPattern, 0> sectionPatterns;
203 
204   // Includes InputSections and MergeInputSections. Used temporarily during
205   // assignment of input sections to output sections.
206   SmallVector<InputSectionBase *, 0> sectionBases;
207 
208   // Used after the finalizeInputSections() pass. MergeInputSections have been
209   // merged into MergeSyntheticSections.
210   SmallVector<InputSection *, 0> sections;
211 
212   // Temporary record of synthetic ThunkSection instances and the pass that
213   // they were created in. This is used to insert newly created ThunkSections
214   // into Sections at the end of a createThunks() pass.
215   SmallVector<std::pair<ThunkSection *, uint32_t>, 0> thunkSections;
216 
217   // SectionPatterns can be filtered with the INPUT_SECTION_FLAGS command.
218   uint64_t withFlags;
219   uint64_t withoutFlags;
220 };
221 
222 // Represents BYTE(), SHORT(), LONG(), or QUAD().
223 struct ByteCommand : SectionCommand {
224   ByteCommand(Expr e, unsigned size, std::string commandString)
225       : SectionCommand(ByteKind), commandString(commandString), expression(e),
226         size(size) {}
227 
228   static bool classof(const SectionCommand *c) { return c->kind == ByteKind; }
229 
230   // Keeps string representing the command. Used for -Map" is perhaps better.
231   std::string commandString;
232 
233   Expr expression;
234 
235   // This is just an offset of this assignment command in the output section.
236   unsigned offset;
237 
238   // Size of this data command.
239   unsigned size;
240 };
241 
242 struct InsertCommand {
243   SmallVector<StringRef, 0> names;
244   bool isAfter;
245   StringRef where;
246 };
247 
248 struct PhdrsCommand {
249   StringRef name;
250   unsigned type = llvm::ELF::PT_NULL;
251   bool hasFilehdr = false;
252   bool hasPhdrs = false;
253   llvm::Optional<unsigned> flags;
254   Expr lmaExpr = nullptr;
255 };
256 
257 class LinkerScript final {
258   // Temporary state used in processSectionCommands() and assignAddresses()
259   // that must be reinitialized for each call to the above functions, and must
260   // not be used outside of the scope of a call to the above functions.
261   struct AddressState {
262     AddressState();
263     OutputSection *outSec = nullptr;
264     MemoryRegion *memRegion = nullptr;
265     MemoryRegion *lmaRegion = nullptr;
266     uint64_t lmaOffset = 0;
267     uint64_t tbssAddr = 0;
268   };
269 
270   llvm::DenseMap<llvm::CachedHashStringRef, OutputSection *>
271       nameToOutputSection;
272 
273   void addSymbol(SymbolAssignment *cmd);
274   void assignSymbol(SymbolAssignment *cmd, bool inSec);
275   void setDot(Expr e, const Twine &loc, bool inSec);
276   void expandOutputSection(uint64_t size);
277   void expandMemoryRegions(uint64_t size);
278 
279   SmallVector<InputSectionBase *, 0>
280   computeInputSections(const InputSectionDescription *,
281                        ArrayRef<InputSectionBase *>);
282 
283   SmallVector<InputSectionBase *, 0> createInputSectionList(OutputSection &cmd);
284 
285   void discardSynthetic(OutputSection &);
286 
287   SmallVector<size_t, 0> getPhdrIndices(OutputSection *sec);
288 
289   std::pair<MemoryRegion *, MemoryRegion *>
290   findMemoryRegion(OutputSection *sec, MemoryRegion *hint);
291 
292   void assignOffsets(OutputSection *sec);
293 
294   // Ctx captures the local AddressState and makes it accessible
295   // deliberately. This is needed as there are some cases where we cannot just
296   // thread the current state through to a lambda function created by the
297   // script parser.
298   // This should remain a plain pointer as its lifetime is smaller than
299   // LinkerScript.
300   AddressState *ctx = nullptr;
301 
302   OutputSection *aether;
303 
304   uint64_t dot;
305 
306 public:
307   OutputSection *createOutputSection(StringRef name, StringRef location);
308   OutputSection *getOrCreateOutputSection(StringRef name);
309 
310   bool hasPhdrsCommands() { return !phdrsCommands.empty(); }
311   uint64_t getDot() { return dot; }
312   void discard(InputSectionBase &s);
313 
314   ExprValue getSymbolValue(StringRef name, const Twine &loc);
315 
316   void addOrphanSections();
317   void diagnoseOrphanHandling() const;
318   void adjustOutputSections();
319   void adjustSectionsAfterSorting();
320 
321   SmallVector<PhdrEntry *, 0> createPhdrs();
322   bool needsInterpSection();
323 
324   bool shouldKeep(InputSectionBase *s);
325   const Defined *assignAddresses();
326   void allocateHeaders(SmallVector<PhdrEntry *, 0> &phdrs);
327   void processSectionCommands();
328   void processSymbolAssignments();
329   void declareSymbols();
330 
331   bool isDiscarded(const OutputSection *sec) const;
332 
333   // Used to handle INSERT AFTER statements.
334   void processInsertCommands();
335 
336   // SECTIONS command list.
337   SmallVector<SectionCommand *, 0> sectionCommands;
338 
339   // PHDRS command list.
340   SmallVector<PhdrsCommand, 0> phdrsCommands;
341 
342   bool hasSectionsCommand = false;
343   bool errorOnMissingSection = false;
344 
345   // List of section patterns specified with KEEP commands. They will
346   // be kept even if they are unused and --gc-sections is specified.
347   SmallVector<InputSectionDescription *, 0> keptSections;
348 
349   // A map from memory region name to a memory region descriptor.
350   llvm::MapVector<llvm::StringRef, MemoryRegion *> memoryRegions;
351 
352   // A list of symbols referenced by the script.
353   SmallVector<llvm::StringRef, 0> referencedSymbols;
354 
355   // Used to implement INSERT [AFTER|BEFORE]. Contains output sections that need
356   // to be reordered.
357   SmallVector<InsertCommand, 0> insertCommands;
358 
359   // OutputSections specified by OVERWRITE_SECTIONS.
360   SmallVector<OutputSection *, 0> overwriteSections;
361 
362   // Sections that will be warned/errored by --orphan-handling.
363   SmallVector<const InputSectionBase *, 0> orphanSections;
364 };
365 
366 extern std::unique_ptr<LinkerScript> script;
367 
368 } // end namespace elf
369 } // end namespace lld
370 
371 #endif // LLD_ELF_LINKER_SCRIPT_H
372