1 //===- LinkerScript.h -------------------------------------------*- C++ -*-===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #ifndef LLD_ELF_LINKER_SCRIPT_H
11 #define LLD_ELF_LINKER_SCRIPT_H
12 
13 #include "Config.h"
14 #include "Strings.h"
15 #include "Writer.h"
16 #include "lld/Common/LLVM.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/DenseSet.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/Support/MemoryBuffer.h"
22 #include <cstddef>
23 #include <cstdint>
24 #include <functional>
25 #include <memory>
26 #include <vector>
27 
28 namespace lld {
29 namespace elf {
30 
31 class DefinedRegular;
32 class SymbolBody;
33 class InputSectionBase;
34 class InputSection;
35 class OutputSection;
36 class OutputSectionFactory;
37 class InputSectionBase;
38 class SectionBase;
39 
40 // This represents an r-value in the linker script.
41 struct ExprValue {
42   ExprValue(SectionBase *Sec, bool ForceAbsolute, uint64_t Val,
43             const Twine &Loc)
44       : Sec(Sec), ForceAbsolute(ForceAbsolute), Val(Val), Loc(Loc.str()) {}
45 
46   ExprValue(uint64_t Val) : ExprValue(nullptr, false, Val, "") {}
47 
48   bool isAbsolute() const { return ForceAbsolute || Sec == nullptr; }
49   uint64_t getValue() const;
50   uint64_t getSecAddr() const;
51   uint64_t getSectionOffset() const;
52 
53   // If a value is relative to a section, it has a non-null Sec.
54   SectionBase *Sec;
55 
56   // True if this expression is enclosed in ABSOLUTE().
57   // This flag affects the return value of getValue().
58   bool ForceAbsolute;
59 
60   uint64_t Val;
61   uint64_t Alignment = 1;
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 typedef std::function<ExprValue()> Expr;
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   AssertKind, // ASSERT(expr)
79   ByteKind    // BYTE(expr), SHORT(expr), LONG(expr) or QUAD(expr)
80 };
81 
82 struct BaseCommand {
83   BaseCommand(int K) : Kind(K) {}
84   int Kind;
85 };
86 
87 // This represents ". = <expr>" or "<symbol> = <expr>".
88 struct SymbolAssignment : BaseCommand {
89   SymbolAssignment(StringRef Name, Expr E, std::string Loc)
90       : BaseCommand(AssignmentKind), Name(Name), Expression(E), Location(Loc) {}
91 
92   static bool classof(const BaseCommand *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   DefinedRegular *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 
111 // Linker scripts allow additional constraints to be put on ouput sections.
112 // If an output section is marked as ONLY_IF_RO, the section is created
113 // only if its input sections are read-only. Likewise, an output section
114 // with ONLY_IF_RW is created if all input sections are RW.
115 enum class ConstraintKind { NoConstraint, ReadOnly, ReadWrite };
116 
117 // This struct is used to represent the location and size of regions of
118 // target memory. Instances of the struct are created by parsing the
119 // MEMORY command.
120 struct MemoryRegion {
121   std::string Name;
122   uint64_t Origin;
123   uint64_t Length;
124   uint32_t Flags;
125   uint32_t NegFlags;
126 };
127 
128 // This struct represents one section match pattern in SECTIONS() command.
129 // It can optionally have negative match pattern for EXCLUDED_FILE command.
130 // Also it may be surrounded with SORT() command, so contains sorting rules.
131 struct SectionPattern {
132   SectionPattern(StringMatcher &&Pat1, StringMatcher &&Pat2)
133       : ExcludedFilePat(Pat1), SectionPat(Pat2) {}
134 
135   StringMatcher ExcludedFilePat;
136   StringMatcher SectionPat;
137   SortSectionPolicy SortOuter;
138   SortSectionPolicy SortInner;
139 };
140 
141 struct InputSectionDescription : BaseCommand {
142   InputSectionDescription(StringRef FilePattern)
143       : BaseCommand(InputSectionKind), FilePat(FilePattern) {}
144 
145   static bool classof(const BaseCommand *C) {
146     return C->Kind == InputSectionKind;
147   }
148 
149   StringMatcher FilePat;
150 
151   // Input sections that matches at least one of SectionPatterns
152   // will be associated with this InputSectionDescription.
153   std::vector<SectionPattern> SectionPatterns;
154 
155   std::vector<InputSection *> Sections;
156 };
157 
158 // Represents an ASSERT().
159 struct AssertCommand : BaseCommand {
160   AssertCommand(Expr E) : BaseCommand(AssertKind), Expression(E) {}
161 
162   static bool classof(const BaseCommand *C) { return C->Kind == AssertKind; }
163 
164   Expr Expression;
165 };
166 
167 // Represents BYTE(), SHORT(), LONG(), or QUAD().
168 struct ByteCommand : BaseCommand {
169   ByteCommand(Expr E, unsigned Size)
170       : BaseCommand(ByteKind), Expression(E), Size(Size) {}
171 
172   static bool classof(const BaseCommand *C) { return C->Kind == ByteKind; }
173 
174   Expr Expression;
175   unsigned Offset;
176   unsigned Size;
177 };
178 
179 struct PhdrsCommand {
180   StringRef Name;
181   unsigned Type = llvm::ELF::PT_NULL;
182   bool HasFilehdr = false;
183   bool HasPhdrs = false;
184   llvm::Optional<unsigned> Flags;
185   Expr LMAExpr = nullptr;
186 };
187 
188 class LinkerScript final {
189   // Temporary state used in processSectionCommands() and assignAddresses()
190   // that must be reinitialized for each call to the above functions, and must
191   // not be used outside of the scope of a call to the above functions.
192   struct AddressState {
193     AddressState();
194     uint64_t ThreadBssOffset = 0;
195     OutputSection *OutSec = nullptr;
196     MemoryRegion *MemRegion = nullptr;
197     llvm::DenseMap<const MemoryRegion *, uint64_t> MemRegionOffset;
198     std::function<uint64_t()> LMAOffset;
199   };
200 
201   llvm::DenseMap<StringRef, OutputSection *> NameToOutputSection;
202 
203   void addSymbol(SymbolAssignment *Cmd);
204   void assignSymbol(SymbolAssignment *Cmd, bool InSec);
205   void setDot(Expr E, const Twine &Loc, bool InSec);
206 
207   std::vector<InputSection *>
208   computeInputSections(const InputSectionDescription *);
209 
210   std::vector<InputSection *> createInputSectionList(OutputSection &Cmd);
211 
212   std::vector<size_t> getPhdrIndices(OutputSection *Sec);
213 
214   MemoryRegion *findMemoryRegion(OutputSection *Sec);
215 
216   void switchTo(OutputSection *Sec);
217   uint64_t advance(uint64_t Size, unsigned Align);
218   void output(InputSection *Sec);
219 
220   std::unique_ptr<AddressState> Ctx;
221   OutputSection *Aether;
222 
223   uint64_t Dot;
224 
225 public:
226   OutputSection *createOutputSection(StringRef Name, StringRef Location);
227   OutputSection *getOrCreateOutputSection(StringRef Name);
228 
229   bool hasPhdrsCommands() { return !PhdrsCommands.empty(); }
230   uint64_t getDot() { return Dot; }
231   void discard(ArrayRef<InputSection *> V);
232 
233   ExprValue getSymbolValue(StringRef Name, const Twine &Loc);
234 
235   void fabricateDefaultCommands();
236   void addOrphanSections(OutputSectionFactory &Factory);
237   void removeEmptyCommands();
238   void adjustSectionsBeforeSorting();
239   void adjustSectionsAfterSorting();
240 
241   std::vector<PhdrEntry *> createPhdrs();
242   bool needsInterpSection();
243 
244   bool shouldKeep(InputSectionBase *S);
245   void assignOffsets(OutputSection *Sec);
246   void assignAddresses();
247   void allocateHeaders(std::vector<PhdrEntry *> &Phdrs);
248   void processSectionCommands(OutputSectionFactory &Factory);
249 
250   // SECTIONS command list.
251   std::vector<BaseCommand *> SectionCommands;
252 
253   // PHDRS command list.
254   std::vector<PhdrsCommand> PhdrsCommands;
255 
256   bool HasSectionsCommand = false;
257   bool ErrorOnMissingSection = false;
258 
259   // List of section patterns specified with KEEP commands. They will
260   // be kept even if they are unused and --gc-sections is specified.
261   std::vector<InputSectionDescription *> KeptSections;
262 
263   // A map from memory region name to a memory region descriptor.
264   llvm::DenseMap<llvm::StringRef, MemoryRegion *> MemoryRegions;
265 
266   // A list of symbols referenced by the script.
267   std::vector<llvm::StringRef> ReferencedSymbols;
268 };
269 
270 extern LinkerScript *Script;
271 
272 } // end namespace elf
273 } // end namespace lld
274 
275 #endif // LLD_ELF_LINKER_SCRIPT_H
276