blob: cfc6f293e1252b480e2322ef2a8dd44b958b0932 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
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// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
George Rimar076fe152016-07-21 06:43:01 +000046bool SymbolAssignment::classof(const BaseCommand *C) {
47 return C->Kind == AssignmentKind;
48}
49
50bool OutputSectionCommand::classof(const BaseCommand *C) {
51 return C->Kind == OutputSectionKind;
52}
53
George Rimareea31142016-07-21 14:26:59 +000054bool InputSectionDescription::classof(const BaseCommand *C) {
55 return C->Kind == InputSectionKind;
56}
57
Rui Ueyama36a153c2016-07-23 14:09:58 +000058template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000059 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000060}
61
Rui Ueyama07320e42016-04-20 20:13:41 +000062template <class ELFT>
63bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000064 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000065 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000066 return true;
67 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000068}
69
George Rimareea31142016-07-21 14:26:59 +000070static bool match(StringRef Pattern, ArrayRef<StringRef> Arr) {
71 for (StringRef S : Arr)
72 if (globMatch(S, Pattern))
73 return true;
74 return false;
75}
76
George Rimar652852c2016-04-16 10:10:32 +000077template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +000078std::vector<OutputSectionBase<ELFT> *>
Eugene Leviante63d81b2016-07-20 14:43:20 +000079LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
George Rimareea31142016-07-21 14:26:59 +000080 typedef const std::unique_ptr<ObjectFile<ELFT>> ObjectFile;
Rui Ueyamaa7f78842016-07-20 17:19:03 +000081 std::vector<OutputSectionBase<ELFT> *> Result;
Rui Ueyama8a9bb7b2016-07-24 02:05:09 +000082 DenseSet<OutputSectionBase<ELFT> *> Removed;
Rui Ueyamaa7f78842016-07-20 17:19:03 +000083
Eugene Leviante63d81b2016-07-20 14:43:20 +000084 // Add input section to output section. If there is no output section yet,
85 // then create it and add to output section list.
Rui Ueyama8a9bb7b2016-07-24 02:05:09 +000086 auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name,
87 ConstraintKind Constraint) {
Eugene Leviante63d81b2016-07-20 14:43:20 +000088 OutputSectionBase<ELFT> *Sec;
89 bool IsNew;
90 std::tie(Sec, IsNew) = Factory.create(C, Name);
91 if (IsNew)
Rui Ueyamaa7f78842016-07-20 17:19:03 +000092 Result.push_back(Sec);
Rui Ueyama8a9bb7b2016-07-24 02:05:09 +000093 if ((!(C->getSectionHdr()->sh_flags & SHF_WRITE)) &&
94 Constraint == ReadWrite) {
95 Removed.insert(Sec);
96 return;
97 }
98 if ((C->getSectionHdr()->sh_flags & SHF_WRITE) && Constraint == ReadOnly) {
99 Removed.insert(Sec);
100 return;
101 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000102 Sec->addSection(C);
103 };
104
105 // Select input sections matching rule and add them to corresponding
106 // output section. Section rules are processed in order they're listed
107 // in script, so correct input section order is maintained by design.
George Rimareea31142016-07-21 14:26:59 +0000108 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
109 auto *OutCmd = dyn_cast<OutputSectionCommand>(Base.get());
110 if (!OutCmd)
111 continue;
112
113 for (const std::unique_ptr<BaseCommand> &Cmd : OutCmd->Commands) {
114 auto *InCmd = dyn_cast<InputSectionDescription>(Cmd.get());
115 if (!InCmd)
116 continue;
117
118 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles()) {
119 for (InputSectionBase<ELFT> *S : F->getSections()) {
120 if (isDiscarded(S) || S->OutSec)
121 continue;
122
123 if (match(S->getSectionName(), InCmd->Patterns)) {
124 if (OutCmd->Name == "/DISCARD/")
125 S->Live = false;
126 else
Rui Ueyama8a9bb7b2016-07-24 02:05:09 +0000127 AddInputSec(S, OutCmd->Name, OutCmd->Constraint);
George Rimareea31142016-07-21 14:26:59 +0000128 }
129 }
130 }
131 }
132 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000133
134 // Add all other input sections, which are not listed in script.
George Rimareea31142016-07-21 14:26:59 +0000135 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles())
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000136 for (InputSectionBase<ELFT> *S : F->getSections()) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000137 if (!isDiscarded(S)) {
138 if (!S->OutSec)
Rui Ueyama8a9bb7b2016-07-24 02:05:09 +0000139 AddInputSec(S, getOutputSectionName(S), NoConstraint);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000140 } else
141 reportDiscarded(S, F);
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000142 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000143
Rui Ueyama8a9bb7b2016-07-24 02:05:09 +0000144 // Remove from the output all the sections which did not met the constraints.
145 Result.erase(std::remove_if(Result.begin(), Result.end(),
146 [&](OutputSectionBase<ELFT> *Sec) {
147 return Removed.count(Sec);
148 }),
149 Result.end());
150 return Result;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000151}
152
153template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000154void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
Rui Ueyama708019c2016-07-24 18:19:40 +0000155 uint64_t Val = Cmd->Expression(Dot);
George Rimar10e576e2016-07-21 16:07:40 +0000156 if (Cmd->Name == ".") {
157 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000158 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000159 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
160 D->Value = Val;
161 }
162}
163
164template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000165void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000166 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000167 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000168 // are not explicitly placed into the output file by the linker script.
169 // We place orphan sections at end of file.
170 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000171 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000172 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000173 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000174 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000175 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000176 }
George Rimar652852c2016-04-16 10:10:32 +0000177
Rui Ueyama7c18c282016-04-18 21:00:40 +0000178 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000179 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000180 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000181 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000182
George Rimar076fe152016-07-21 06:43:01 +0000183 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
184 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000185 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000186 continue;
187 }
188
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000189 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000190 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000191 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000192 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000193 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000194 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000195 continue;
George Rimar652852c2016-04-16 10:10:32 +0000196
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000197 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
198 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000199 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000200 Sec->setVA(TVA);
201 ThreadBssOffset = TVA - Dot + Sec->getSize();
202 continue;
203 }
George Rimar652852c2016-04-16 10:10:32 +0000204
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000205 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000206 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000207 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000208 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000209 Dot += Sec->getSize();
210 continue;
211 }
George Rimar652852c2016-04-16 10:10:32 +0000212 }
213 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000214
Rafael Espindola64c32d62016-07-07 14:28:47 +0000215 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000216 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000217 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
218 Out<ELFT>::ProgramHeaders->getSize(),
219 Target->PageSize);
220 Out<ELFT>::ElfHeader->setVA(MinVA);
221 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000222}
223
Rui Ueyama07320e42016-04-20 20:13:41 +0000224template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000225std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000226LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
227 int TlsNum = -1;
228 int NoteNum = -1;
229 int RelroNum = -1;
Rui Ueyamaadca2452016-07-23 14:18:48 +0000230 PhdrEntry<ELFT> *Load = nullptr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000231 uintX_t Flags = PF_R;
Rui Ueyamaadca2452016-07-23 14:18:48 +0000232 std::vector<PhdrEntry<ELFT>> Phdrs;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000233
234 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Eugene Leviant865bf862016-07-21 10:43:25 +0000235 Phdrs.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rui Ueyamaadca2452016-07-23 14:18:48 +0000236 PhdrEntry<ELFT> &Phdr = Phdrs.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000237
238 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000239 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000240 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000241 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000242
243 switch (Cmd.Type) {
244 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000245 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000246 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000247 break;
248 case PT_DYNAMIC:
249 if (isOutputDynamic<ELFT>()) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000250 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
251 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000252 }
253 break;
254 case PT_TLS:
255 TlsNum = Phdrs.size() - 1;
256 break;
257 case PT_NOTE:
258 NoteNum = Phdrs.size() - 1;
259 break;
260 case PT_GNU_RELRO:
261 RelroNum = Phdrs.size() - 1;
262 break;
263 case PT_GNU_EH_FRAME:
264 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000265 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
266 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000267 }
268 break;
269 }
270 }
271
272 for (OutputSectionBase<ELFT> *Sec : Sections) {
273 if (!(Sec->getFlags() & SHF_ALLOC))
274 break;
275
276 if (TlsNum != -1 && (Sec->getFlags() & SHF_TLS))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000277 Phdrs[TlsNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000278
279 if (!needsPtLoad<ELFT>(Sec))
280 continue;
281
282 const std::vector<size_t> &PhdrIds =
283 getPhdrIndicesForSection(Sec->getName());
284 if (!PhdrIds.empty()) {
285 // Assign headers specified by linker script
286 for (size_t Id : PhdrIds) {
Rui Ueyama18f084f2016-07-20 19:36:41 +0000287 Phdrs[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000288 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
289 Phdrs[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000290 }
291 } else {
292 // If we have no load segment or flags've changed then we want new load
293 // segment.
294 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
295 if (Load == nullptr || Flags != NewFlags) {
296 Load = &*Phdrs.emplace(Phdrs.end(), PT_LOAD, NewFlags);
297 Flags = NewFlags;
298 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000299 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000300 }
301
302 if (RelroNum != -1 && isRelroSection(Sec))
Rui Ueyama18f084f2016-07-20 19:36:41 +0000303 Phdrs[RelroNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000304 if (NoteNum != -1 && Sec->getType() == SHT_NOTE)
Rui Ueyama18f084f2016-07-20 19:36:41 +0000305 Phdrs[NoteNum].add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000306 }
307 return Phdrs;
308}
309
310template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000311ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000312 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
313 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
314 if (Cmd->Name == Name)
315 return Cmd->Filler;
316 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000317}
318
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000319// Returns the index of the given section name in linker script
320// SECTIONS commands. Sections are laid out as the same order as they
321// were in the script. If a given name did not appear in the script,
322// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000323template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000324 auto Begin = Opt.Commands.begin();
325 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000326 auto I =
327 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
328 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
329 if (Cmd->Name == Name)
330 return true;
331 return false;
332 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000333 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000334}
335
336// A compartor to sort output sections. Returns -1 or 1 if
337// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000338template <class ELFT>
339int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000340 int I = getSectionIndex(A);
341 int J = getSectionIndex(B);
342 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000343 return 0;
344 return I < J ? -1 : 1;
345}
346
George Rimar076fe152016-07-21 06:43:01 +0000347template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000348 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
349 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
350 if (!Cmd || Cmd->Name == ".")
351 continue;
352
Davide Italiano8ab41082016-07-23 22:09:04 +0000353 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
354 if (!B || B->isUndefined())
Eugene Levianta31c91b2016-07-22 07:38:40 +0000355 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
356 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
357 else
358 // Symbol already exists in symbol table. If it is provided
359 // then we can't override its value.
360 Cmd->Ignore = Cmd->Provide;
361 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000362}
363
Eugene Leviantbbe38602016-07-19 09:25:43 +0000364template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
365 return !Opt.PhdrsCommands.empty();
366}
367
368// Returns indices of ELF headers containing specific section, identified
369// by Name. Each index is a zero based number of ELF header listed within
370// PHDRS {} script block.
371template <class ELFT>
372std::vector<size_t>
373LinkerScript<ELFT>::getPhdrIndicesForSection(StringRef Name) {
George Rimar076fe152016-07-21 06:43:01 +0000374 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
375 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
376 if (!Cmd || Cmd->Name != Name)
George Rimar31d842f2016-07-20 16:43:03 +0000377 continue;
378
379 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000380 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000381 auto ItPhdr =
382 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000383 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000384 if (ItPhdr == Opt.PhdrsCommands.rend())
385 error("section header '" + PhdrName + "' is not listed in PHDRS");
386 else
387 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
388 }
George Rimar31d842f2016-07-20 16:43:03 +0000389 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000390 }
George Rimar31d842f2016-07-20 16:43:03 +0000391 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000392}
393
Rui Ueyama07320e42016-04-20 20:13:41 +0000394class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000395 typedef void (ScriptParser::*Handler)();
396
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000397public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000398 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000399
Rui Ueyama4a465392016-04-22 22:59:24 +0000400 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000401
402private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000403 void addFile(StringRef Path);
404
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000405 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000406 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000407 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000408 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000409 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000410 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000411 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000412 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000413 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000414 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000415 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000416 void readSections();
417
Rui Ueyama113cdec2016-07-24 23:05:57 +0000418 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000419 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000420 std::vector<StringRef> readOutputSectionPhdrs();
421 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000422 void readProvide(bool Hidden);
Rui Ueyama708019c2016-07-24 18:19:40 +0000423
424 Expr readExpr();
425 Expr readExpr1(Expr Lhs, int MinPrec);
426 Expr readPrimary();
427 Expr readTernary(Expr Cond);
428 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000429
George Rimarc3794e52016-02-24 09:21:47 +0000430 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000431 ScriptConfiguration &Opt = *ScriptConfig;
432 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000433 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000434};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000435
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000436const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000437 {"ENTRY", &ScriptParser::readEntry},
438 {"EXTERN", &ScriptParser::readExtern},
439 {"GROUP", &ScriptParser::readGroup},
440 {"INCLUDE", &ScriptParser::readInclude},
441 {"INPUT", &ScriptParser::readGroup},
442 {"OUTPUT", &ScriptParser::readOutput},
443 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
444 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000445 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000446 {"SEARCH_DIR", &ScriptParser::readSearchDir},
447 {"SECTIONS", &ScriptParser::readSections},
448 {";", &ScriptParser::readNothing}};
449
Rui Ueyama717677a2016-02-11 21:17:59 +0000450void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000451 while (!atEOF()) {
452 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000453 if (Handler Fn = Cmd.lookup(Tok))
454 (this->*Fn)();
455 else
George Rimar57610422016-03-11 14:43:02 +0000456 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000457 }
458}
459
Rui Ueyama717677a2016-02-11 21:17:59 +0000460void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000461 if (IsUnderSysroot && S.startswith("/")) {
462 SmallString<128> Path;
463 (Config->Sysroot + S).toStringRef(Path);
464 if (sys::fs::exists(Path)) {
465 Driver->addFile(Saver.save(Path.str()));
466 return;
467 }
468 }
469
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000470 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000471 Driver->addFile(S);
472 } else if (S.startswith("=")) {
473 if (Config->Sysroot.empty())
474 Driver->addFile(S.substr(1));
475 else
476 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
477 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000478 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000479 } else if (sys::fs::exists(S)) {
480 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000481 } else {
482 std::string Path = findFromSearchPaths(S);
483 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000484 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000485 else
486 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000487 }
488}
489
Rui Ueyama717677a2016-02-11 21:17:59 +0000490void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000491 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000492 bool Orig = Config->AsNeeded;
493 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000494 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000495 StringRef Tok = next();
496 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000497 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000498 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000499 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000500 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000501}
502
Rui Ueyama717677a2016-02-11 21:17:59 +0000503void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000504 // -e <symbol> takes predecence over ENTRY(<symbol>).
505 expect("(");
506 StringRef Tok = next();
507 if (Config->Entry.empty())
508 Config->Entry = Tok;
509 expect(")");
510}
511
Rui Ueyama717677a2016-02-11 21:17:59 +0000512void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000513 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000514 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000515 StringRef Tok = next();
516 if (Tok == ")")
517 return;
518 Config->Undefined.push_back(Tok);
519 }
520}
521
Rui Ueyama717677a2016-02-11 21:17:59 +0000522void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000523 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000524 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000525 StringRef Tok = next();
526 if (Tok == ")")
527 return;
528 if (Tok == "AS_NEEDED") {
529 readAsNeeded();
530 continue;
531 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000532 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000533 }
534}
535
Rui Ueyama717677a2016-02-11 21:17:59 +0000536void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000537 StringRef Tok = next();
538 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000539 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000540 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000541 return;
542 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000543 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000544 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
545 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000546 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000547}
548
Rui Ueyama717677a2016-02-11 21:17:59 +0000549void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000550 // -o <file> takes predecence over OUTPUT(<file>).
551 expect("(");
552 StringRef Tok = next();
553 if (Config->OutputFile.empty())
554 Config->OutputFile = Tok;
555 expect(")");
556}
557
Rui Ueyama717677a2016-02-11 21:17:59 +0000558void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000559 // Error checking only for now.
560 expect("(");
561 next();
562 expect(")");
563}
564
Rui Ueyama717677a2016-02-11 21:17:59 +0000565void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000566 // Error checking only for now.
567 expect("(");
568 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000569 StringRef Tok = next();
570 if (Tok == ")")
571 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000572 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000573 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000574 return;
575 }
Davide Italiano6836c612015-10-12 21:08:41 +0000576 next();
577 expect(",");
578 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000579 expect(")");
580}
581
Eugene Leviantbbe38602016-07-19 09:25:43 +0000582void ScriptParser::readPhdrs() {
583 expect("{");
584 while (!Error && !skip("}")) {
585 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000586 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000587 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
588
589 PhdrCmd.Type = readPhdrType();
590 do {
591 Tok = next();
592 if (Tok == ";")
593 break;
594 if (Tok == "FILEHDR")
595 PhdrCmd.HasFilehdr = true;
596 else if (Tok == "PHDRS")
597 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000598 else if (Tok == "FLAGS") {
599 expect("(");
600 next().getAsInteger(0, PhdrCmd.Flags);
601 expect(")");
602 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000603 setError("unexpected header attribute: " + Tok);
604 } while (!Error);
605 }
606}
607
Rui Ueyama717677a2016-02-11 21:17:59 +0000608void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000609 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000610 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000611 expect(")");
612}
613
Rui Ueyama717677a2016-02-11 21:17:59 +0000614void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000615 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000616 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000617 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000618 StringRef Tok = next();
619 if (peek() == "=") {
620 readAssignment(Tok);
621 expect(";");
622 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000623 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000624 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000625 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000626 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000627 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000628 }
George Rimar652852c2016-04-16 10:10:32 +0000629 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000630}
631
Rui Ueyama708019c2016-07-24 18:19:40 +0000632static int precedence(StringRef Op) {
633 return StringSwitch<int>(Op)
634 .Case("*", 4)
635 .Case("/", 4)
636 .Case("+", 3)
637 .Case("-", 3)
638 .Case("<", 2)
639 .Case(">", 2)
640 .Case(">=", 2)
641 .Case("<=", 2)
642 .Case("==", 2)
643 .Case("!=", 2)
644 .Case("&", 1)
645 .Default(-1);
646}
647
Eugene Levianteda81a12016-07-12 06:39:48 +0000648void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000649 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
650 Opt.Commands.emplace_back(Cmd);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000651 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000652
653 // Parse constraints.
654 if (skip("ONLY_IF_RO"))
655 Cmd->Constraint = ReadOnly;
656 if (skip("ONLY_IF_RW"))
657 Cmd->Constraint = ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000658 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000659
Rui Ueyama025d59b2016-02-02 20:27:59 +0000660 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000661 StringRef Tok = next();
662 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000663 auto *InCmd = new InputSectionDescription();
664 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000665 expect("(");
666 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000667 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000668 } else if (Tok == "KEEP") {
669 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000670 expect("*");
671 expect("(");
George Rimareea31142016-07-21 14:26:59 +0000672 auto *InCmd = new InputSectionDescription();
673 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000674 while (!Error && !skip(")")) {
George Rimareea31142016-07-21 14:26:59 +0000675 Opt.KeptSections.push_back(peek());
676 InCmd->Patterns.push_back(next());
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000677 }
George Rimar481c2ce2016-02-23 07:47:54 +0000678 expect(")");
679 } else {
George Rimar777f9632016-03-12 08:31:34 +0000680 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000681 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000682 }
George Rimar076fe152016-07-21 06:43:01 +0000683 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000684
George Rimare2ee72b2016-02-26 14:48:31 +0000685 StringRef Tok = peek();
686 if (Tok.startswith("=")) {
687 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000688 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000689 return;
690 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000691 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000692 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000693 next();
694 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000695}
696
Eugene Levianta31c91b2016-07-22 07:38:40 +0000697void ScriptParser::readProvide(bool Hidden) {
698 expect("(");
Rui Ueyama113cdec2016-07-24 23:05:57 +0000699 if (SymbolAssignment *Assignment = readAssignment(next())) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000700 Assignment->Provide = true;
701 Assignment->Hidden = Hidden;
702 }
703 expect(")");
704 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000705}
706
Rui Ueyama113cdec2016-07-24 23:05:57 +0000707SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000708 expect("=");
Rui Ueyama708019c2016-07-24 18:19:40 +0000709 Expr E = readExpr();
Rui Ueyama113cdec2016-07-24 23:05:57 +0000710 auto *Cmd = new SymbolAssignment(Name, E);
711 Opt.Commands.emplace_back(Cmd);
712 return Cmd;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000713}
714
Rui Ueyama708019c2016-07-24 18:19:40 +0000715// This is an operator-precedence parser to parse a linker
716// script expression.
717Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
Eugene Levianta31c91b2016-07-22 07:38:40 +0000718
Rui Ueyama708019c2016-07-24 18:19:40 +0000719// This is a part of the operator-precedence parser. This function
720// assumes that the remaining token stream starts with an operator.
721Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
722 while (!atEOF() && !Error) {
723 // Read an operator and an expression.
724 StringRef Op1 = peek();
725 if (Op1 == "?")
726 return readTernary(Lhs);
727 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000728 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000729 next();
730 Expr Rhs = readPrimary();
731
732 // Evaluate the remaining part of the expression first if the
733 // next operator has greater precedence than the previous one.
734 // For example, if we have read "+" and "3", and if the next
735 // operator is "*", then we'll evaluate 3 * ... part first.
736 while (!atEOF()) {
737 StringRef Op2 = peek();
738 if (precedence(Op2) <= precedence(Op1))
739 break;
740 Rhs = readExpr1(Rhs, precedence(Op2));
741 }
742
743 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000744 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000745 return Lhs;
746}
747
748uint64_t static getConstant(StringRef S) {
749 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
750 return Target->PageSize;
751 error("unknown constant: " + S);
752 return 0;
753}
754
755Expr ScriptParser::readPrimary() {
756 StringRef Tok = next();
757
758 if (Tok == ".")
759 return [](uint64_t Dot) { return Dot; };
760
761 if (Tok == "(") {
762 Expr E = readExpr();
763 expect(")");
764 return E;
765 }
766
767 // Built-in functions are parsed here.
768 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
769 if (Tok == "ALIGN") {
770 expect("(");
771 Expr E = readExpr();
772 expect(")");
773 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
774 }
775 if (Tok == "CONSTANT") {
776 expect("(");
777 StringRef Tok = next();
778 expect(")");
779 return [=](uint64_t Dot) { return getConstant(Tok); };
780 }
781 if (Tok == "DATA_SEGMENT_ALIGN") {
782 expect("(");
783 Expr E = readExpr();
784 expect(",");
785 readExpr();
786 expect(")");
787 return [=](uint64_t Dot) -> uint64_t {
788 uint64_t Val = E(Dot);
789 return alignTo(Dot, Val) + (Dot & (Val - 1));
790 };
791 }
792 if (Tok == "DATA_SEGMENT_END") {
793 expect("(");
794 expect(".");
795 expect(")");
796 return [](uint64_t Dot) { return Dot; };
797 }
798
799 // Parse a number literal
800 uint64_t V = 0;
801 if (Tok.getAsInteger(0, V))
802 setError("malformed number: " + Tok);
803 return [=](uint64_t Dot) { return V; };
804}
805
806Expr ScriptParser::readTernary(Expr Cond) {
807 next();
808 Expr L = readExpr();
809 expect(":");
810 Expr R = readExpr();
811 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
812}
813
814Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
815 if (Op == "*")
816 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
817 if (Op == "/") {
818 return [=](uint64_t Dot) -> uint64_t {
819 uint64_t RHS = R(Dot);
820 if (RHS == 0) {
821 error("division by zero");
822 return 0;
823 }
824 return L(Dot) / RHS;
825 };
826 }
827 if (Op == "+")
828 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
829 if (Op == "-")
830 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
831 if (Op == "<")
832 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
833 if (Op == ">")
834 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
835 if (Op == ">=")
836 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
837 if (Op == "<=")
838 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
839 if (Op == "==")
840 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
841 if (Op == "!=")
842 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
843 if (Op == "&")
844 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
845 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000846}
847
Eugene Leviantbbe38602016-07-19 09:25:43 +0000848std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
849 std::vector<StringRef> Phdrs;
850 while (!Error && peek().startswith(":")) {
851 StringRef Tok = next();
852 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
853 if (Tok.empty()) {
854 setError("section header name is empty");
855 break;
856 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000857 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000858 }
859 return Phdrs;
860}
861
862unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000863 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000864 unsigned Ret = StringSwitch<unsigned>(Tok)
865 .Case("PT_NULL", PT_NULL)
866 .Case("PT_LOAD", PT_LOAD)
867 .Case("PT_DYNAMIC", PT_DYNAMIC)
868 .Case("PT_INTERP", PT_INTERP)
869 .Case("PT_NOTE", PT_NOTE)
870 .Case("PT_SHLIB", PT_SHLIB)
871 .Case("PT_PHDR", PT_PHDR)
872 .Case("PT_TLS", PT_TLS)
873 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
874 .Case("PT_GNU_STACK", PT_GNU_STACK)
875 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
876 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000877
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000878 if (Ret == (unsigned)-1) {
879 setError("invalid program header type: " + Tok);
880 return PT_NULL;
881 }
882 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000883}
884
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000885static bool isUnderSysroot(StringRef Path) {
886 if (Config->Sysroot == "")
887 return false;
888 for (; !Path.empty(); Path = sys::path::parent_path(Path))
889 if (sys::fs::equivalent(Config->Sysroot, Path))
890 return true;
891 return false;
892}
893
Rui Ueyama07320e42016-04-20 20:13:41 +0000894// Entry point.
895void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000896 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000897 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000898}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000899
Rui Ueyama07320e42016-04-20 20:13:41 +0000900template class elf::LinkerScript<ELF32LE>;
901template class elf::LinkerScript<ELF32BE>;
902template class elf::LinkerScript<ELF64LE>;
903template class elf::LinkerScript<ELF64BE>;