blob: 1d51a70819f9266db279b8eb14dc0a6b18fdf0c6 [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
Rui Ueyama63dc6502016-07-25 22:41:42 +000070static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
71 for (StringRef Pat : Patterns)
72 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +000073 return true;
74 return false;
75}
76
Rui Ueyama6b274812016-07-25 22:51:07 +000077// Create a vector of (<output section name>, <input section name patterns>).
78// For example, if a returned vector contains (".text" (".foo.*" ".bar.*")),
79// input sections start with ".foo." or ".bar." should be added to
80// ".text" section.
81template <class ELFT>
82std::vector<std::pair<StringRef, ArrayRef<StringRef>>>
83LinkerScript<ELFT>::getSectionMap() {
84 std::vector<std::pair<StringRef, ArrayRef<StringRef>>> Ret;
85
86 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
87 if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get()))
88 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands)
89 if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get()))
90 Ret.emplace_back(Cmd1->Name, Cmd2->Patterns);
91
92 return Ret;
93}
94
95// Returns input sections filtered by given glob patterns.
96template <class ELFT>
97std::vector<InputSectionBase<ELFT> *>
98LinkerScript<ELFT>::getInputSections(ArrayRef<StringRef> Patterns) {
99 std::vector<InputSectionBase<ELFT> *> Ret;
100 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
101 Symtab<ELFT>::X->getObjectFiles())
102 for (InputSectionBase<ELFT> *S : F->getSections())
103 if (!isDiscarded(S) && !S->OutSec && match(Patterns, S->getSectionName()))
104 Ret.push_back(S);
105 return Ret;
106}
107
George Rimar652852c2016-04-16 10:10:32 +0000108template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000109std::vector<OutputSectionBase<ELFT> *>
Eugene Leviante63d81b2016-07-20 14:43:20 +0000110LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000111 std::vector<OutputSectionBase<ELFT> *> Ret;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000112
Eugene Leviante63d81b2016-07-20 14:43:20 +0000113 // Add input section to output section. If there is no output section yet,
114 // then create it and add to output section list.
Rui Ueyama6b274812016-07-25 22:51:07 +0000115 auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000116 OutputSectionBase<ELFT> *Sec;
117 bool IsNew;
118 std::tie(Sec, IsNew) = Factory.create(C, Name);
119 if (IsNew)
Rui Ueyama6b274812016-07-25 22:51:07 +0000120 Ret.push_back(Sec);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000121 Sec->addSection(C);
122 };
123
Rui Ueyama6b274812016-07-25 22:51:07 +0000124 for (auto &P : getSectionMap()) {
125 StringRef OutputName = P.first;
126 ArrayRef<StringRef> InputPatterns = P.second;
127 for (InputSectionBase<ELFT> *S : getInputSections(InputPatterns)) {
128 if (OutputName == "/DISCARD/") {
129 S->Live = false;
130 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000131 continue;
George Rimareea31142016-07-21 14:26:59 +0000132 }
Rui Ueyama6b274812016-07-25 22:51:07 +0000133 Add(S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000134 }
135 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000136
137 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000138 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
139 Symtab<ELFT>::X->getObjectFiles())
140 for (InputSectionBase<ELFT> *S : F->getSections())
141 if (!isDiscarded(S) && !S->OutSec)
142 Add(S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000143
Rui Ueyama3c291e12016-07-25 21:30:00 +0000144 // Remove from the output all the sections which did not meet
145 // the optional constraints.
Rui Ueyama6b274812016-07-25 22:51:07 +0000146 return filter(Ret);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000147}
148
149// Process ONLY_IF_RO and ONLY_IF_RW.
150template <class ELFT>
151std::vector<OutputSectionBase<ELFT> *>
152LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
153 // Sections and OutputSectionCommands are parallel arrays.
154 // In this loop, we remove output sections if they don't satisfy
155 // requested properties.
156 auto It = Sections.begin();
157 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
158 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
159 if (!Cmd || Cmd->Name == "/DISCARD/")
160 continue;
161
162 if (Cmd->Constraint == ConstraintKind::NoConstraint) {
163 ++It;
164 continue;
165 }
166
167 OutputSectionBase<ELFT> *Sec = *It;
168 bool Writable = (Sec->getFlags() & SHF_WRITE);
169 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
170 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
171
172 if ((RO && Writable) || (RW && !Writable)) {
173 Sections.erase(It);
174 continue;
175 }
176 ++It;
177 }
178 return Sections;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000179}
180
181template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000182void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
Rui Ueyama708019c2016-07-24 18:19:40 +0000183 uint64_t Val = Cmd->Expression(Dot);
George Rimar10e576e2016-07-21 16:07:40 +0000184 if (Cmd->Name == ".") {
185 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000186 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000187 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
188 D->Value = Val;
189 }
190}
191
192template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000193void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000194 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000195 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000196 // are not explicitly placed into the output file by the linker script.
197 // We place orphan sections at end of file.
198 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000199 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000200 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000201 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000202 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000203 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000204 }
George Rimar652852c2016-04-16 10:10:32 +0000205
Rui Ueyama7c18c282016-04-18 21:00:40 +0000206 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000207 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000208 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000209 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000210
George Rimar076fe152016-07-21 06:43:01 +0000211 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
212 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000213 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000214 continue;
215 }
216
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000217 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000218 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000219 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000220 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000221 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000222 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000223 continue;
George Rimar652852c2016-04-16 10:10:32 +0000224
George Rimar58e5c4d2016-07-25 08:29:46 +0000225 if (Cmd->AddrExpr)
226 Dot = Cmd->AddrExpr(Dot);
227
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000228 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
229 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000230 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000231 Sec->setVA(TVA);
232 ThreadBssOffset = TVA - Dot + Sec->getSize();
233 continue;
234 }
George Rimar652852c2016-04-16 10:10:32 +0000235
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000236 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000237 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000238 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000239 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000240 Dot += Sec->getSize();
241 continue;
242 }
George Rimar652852c2016-04-16 10:10:32 +0000243 }
244 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000245
Rafael Espindola64c32d62016-07-07 14:28:47 +0000246 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000247 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000248 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
249 Out<ELFT>::ProgramHeaders->getSize(),
250 Target->PageSize);
251 Out<ELFT>::ElfHeader->setVA(MinVA);
252 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000253}
254
Rui Ueyama07320e42016-04-20 20:13:41 +0000255template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000256std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000257LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000258 std::vector<PhdrEntry<ELFT>> Ret;
259 PhdrEntry<ELFT> *TlsPhdr = nullptr;
260 PhdrEntry<ELFT> *NotePhdr = nullptr;
261 PhdrEntry<ELFT> *RelroPhdr = nullptr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000262
263 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000264 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
265 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000266
267 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000268 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000269 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000270 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000271
272 switch (Cmd.Type) {
273 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000274 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000275 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000276 break;
277 case PT_DYNAMIC:
278 if (isOutputDynamic<ELFT>()) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000279 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
280 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000281 }
282 break;
283 case PT_TLS:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000284 TlsPhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000285 break;
286 case PT_NOTE:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000287 NotePhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000288 break;
289 case PT_GNU_RELRO:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000290 RelroPhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000291 break;
292 case PT_GNU_EH_FRAME:
293 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000294 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
295 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000296 }
297 break;
298 }
299 }
300
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000301 PhdrEntry<ELFT> *Load = nullptr;
302 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000303 for (OutputSectionBase<ELFT> *Sec : Sections) {
304 if (!(Sec->getFlags() & SHF_ALLOC))
305 break;
306
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000307 if (TlsPhdr && (Sec->getFlags() & SHF_TLS))
308 TlsPhdr->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000309
310 if (!needsPtLoad<ELFT>(Sec))
311 continue;
312
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000313 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000314 if (!PhdrIds.empty()) {
315 // Assign headers specified by linker script
316 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000317 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000318 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000319 Ret[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000320 }
321 } else {
322 // If we have no load segment or flags've changed then we want new load
323 // segment.
324 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
325 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000326 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000327 Flags = NewFlags;
328 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000329 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000330 }
331
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000332 if (RelroPhdr && isRelroSection(Sec))
333 RelroPhdr->add(Sec);
334 if (NotePhdr && Sec->getType() == SHT_NOTE)
335 NotePhdr->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000336 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000337 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000338}
339
340template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000341ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000342 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
343 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
344 if (Cmd->Name == Name)
345 return Cmd->Filler;
346 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000347}
348
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000349// Returns the index of the given section name in linker script
350// SECTIONS commands. Sections are laid out as the same order as they
351// were in the script. If a given name did not appear in the script,
352// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000353template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000354 auto Begin = Opt.Commands.begin();
355 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000356 auto I =
357 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
358 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
359 if (Cmd->Name == Name)
360 return true;
361 return false;
362 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000363 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000364}
365
366// A compartor to sort output sections. Returns -1 or 1 if
367// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000368template <class ELFT>
369int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000370 int I = getSectionIndex(A);
371 int J = getSectionIndex(B);
372 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000373 return 0;
374 return I < J ? -1 : 1;
375}
376
George Rimar076fe152016-07-21 06:43:01 +0000377template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000378 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
379 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
380 if (!Cmd || Cmd->Name == ".")
381 continue;
382
Davide Italiano8ab41082016-07-23 22:09:04 +0000383 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Davide Italiano373a5332016-07-25 00:25:18 +0000384 // The semantic of PROVIDE is that of introducing a symbol only if
385 // it's not defined and there's at least a reference to it.
386 if ((!B && !Cmd->Provide) || (B && B->isUndefined()))
Eugene Levianta31c91b2016-07-22 07:38:40 +0000387 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
388 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
389 else
390 // Symbol already exists in symbol table. If it is provided
391 // then we can't override its value.
392 Cmd->Ignore = Cmd->Provide;
393 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000394}
395
Eugene Leviantbbe38602016-07-19 09:25:43 +0000396template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
397 return !Opt.PhdrsCommands.empty();
398}
399
400// Returns indices of ELF headers containing specific section, identified
401// by Name. Each index is a zero based number of ELF header listed within
402// PHDRS {} script block.
403template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000404std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000405 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
406 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000407 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000408 continue;
409
410 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000411 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000412 auto ItPhdr =
413 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000414 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000415 if (ItPhdr == Opt.PhdrsCommands.rend())
416 error("section header '" + PhdrName + "' is not listed in PHDRS");
417 else
418 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
419 }
George Rimar31d842f2016-07-20 16:43:03 +0000420 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000421 }
George Rimar31d842f2016-07-20 16:43:03 +0000422 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000423}
424
Rui Ueyama07320e42016-04-20 20:13:41 +0000425class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000426 typedef void (ScriptParser::*Handler)();
427
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000428public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000429 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000430
Rui Ueyama4a465392016-04-22 22:59:24 +0000431 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000432
433private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000434 void addFile(StringRef Path);
435
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000436 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000437 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000438 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000439 void readGroup();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000440 void readKeep(OutputSectionCommand *Cmd);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000441 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000442 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000443 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000444 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000445 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000446 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000447 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000448 void readSections();
449
Rui Ueyama113cdec2016-07-24 23:05:57 +0000450 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000451 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000452 std::vector<StringRef> readOutputSectionPhdrs();
453 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000454 void readProvide(bool Hidden);
Rui Ueyama708019c2016-07-24 18:19:40 +0000455
456 Expr readExpr();
457 Expr readExpr1(Expr Lhs, int MinPrec);
458 Expr readPrimary();
459 Expr readTernary(Expr Cond);
460 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000461
George Rimarc3794e52016-02-24 09:21:47 +0000462 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000463 ScriptConfiguration &Opt = *ScriptConfig;
464 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000465 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000466};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000467
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000468const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000469 {"ENTRY", &ScriptParser::readEntry},
470 {"EXTERN", &ScriptParser::readExtern},
471 {"GROUP", &ScriptParser::readGroup},
472 {"INCLUDE", &ScriptParser::readInclude},
473 {"INPUT", &ScriptParser::readGroup},
474 {"OUTPUT", &ScriptParser::readOutput},
475 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
476 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000477 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000478 {"SEARCH_DIR", &ScriptParser::readSearchDir},
479 {"SECTIONS", &ScriptParser::readSections},
480 {";", &ScriptParser::readNothing}};
481
Rui Ueyama717677a2016-02-11 21:17:59 +0000482void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000483 while (!atEOF()) {
484 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000485 if (Handler Fn = Cmd.lookup(Tok))
486 (this->*Fn)();
487 else
George Rimar57610422016-03-11 14:43:02 +0000488 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000489 }
490}
491
Rui Ueyama717677a2016-02-11 21:17:59 +0000492void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000493 if (IsUnderSysroot && S.startswith("/")) {
494 SmallString<128> Path;
495 (Config->Sysroot + S).toStringRef(Path);
496 if (sys::fs::exists(Path)) {
497 Driver->addFile(Saver.save(Path.str()));
498 return;
499 }
500 }
501
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000502 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000503 Driver->addFile(S);
504 } else if (S.startswith("=")) {
505 if (Config->Sysroot.empty())
506 Driver->addFile(S.substr(1));
507 else
508 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
509 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000510 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000511 } else if (sys::fs::exists(S)) {
512 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000513 } else {
514 std::string Path = findFromSearchPaths(S);
515 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000516 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000517 else
518 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000519 }
520}
521
Rui Ueyama717677a2016-02-11 21:17:59 +0000522void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000523 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000524 bool Orig = Config->AsNeeded;
525 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000526 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000527 StringRef Tok = next();
528 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000529 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000530 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000531 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000532 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000533}
534
Rui Ueyama717677a2016-02-11 21:17:59 +0000535void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000536 // -e <symbol> takes predecence over ENTRY(<symbol>).
537 expect("(");
538 StringRef Tok = next();
539 if (Config->Entry.empty())
540 Config->Entry = Tok;
541 expect(")");
542}
543
Rui Ueyama717677a2016-02-11 21:17:59 +0000544void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000545 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000546 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000547 StringRef Tok = next();
548 if (Tok == ")")
549 return;
550 Config->Undefined.push_back(Tok);
551 }
552}
553
Rui Ueyama717677a2016-02-11 21:17:59 +0000554void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000555 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000556 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000557 StringRef Tok = next();
558 if (Tok == ")")
559 return;
560 if (Tok == "AS_NEEDED") {
561 readAsNeeded();
562 continue;
563 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000564 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000565 }
566}
567
Rui Ueyama717677a2016-02-11 21:17:59 +0000568void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000569 StringRef Tok = next();
570 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000571 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000572 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000573 return;
574 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000575 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000576 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
577 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000578 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000579}
580
Rui Ueyama717677a2016-02-11 21:17:59 +0000581void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000582 // -o <file> takes predecence over OUTPUT(<file>).
583 expect("(");
584 StringRef Tok = next();
585 if (Config->OutputFile.empty())
586 Config->OutputFile = Tok;
587 expect(")");
588}
589
Rui Ueyama717677a2016-02-11 21:17:59 +0000590void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000591 // Error checking only for now.
592 expect("(");
593 next();
594 expect(")");
595}
596
Rui Ueyama717677a2016-02-11 21:17:59 +0000597void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000598 // Error checking only for now.
599 expect("(");
600 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000601 StringRef Tok = next();
602 if (Tok == ")")
603 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000604 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000605 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000606 return;
607 }
Davide Italiano6836c612015-10-12 21:08:41 +0000608 next();
609 expect(",");
610 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000611 expect(")");
612}
613
Eugene Leviantbbe38602016-07-19 09:25:43 +0000614void ScriptParser::readPhdrs() {
615 expect("{");
616 while (!Error && !skip("}")) {
617 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000618 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000619 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
620
621 PhdrCmd.Type = readPhdrType();
622 do {
623 Tok = next();
624 if (Tok == ";")
625 break;
626 if (Tok == "FILEHDR")
627 PhdrCmd.HasFilehdr = true;
628 else if (Tok == "PHDRS")
629 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000630 else if (Tok == "FLAGS") {
631 expect("(");
632 next().getAsInteger(0, PhdrCmd.Flags);
633 expect(")");
634 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000635 setError("unexpected header attribute: " + Tok);
636 } while (!Error);
637 }
638}
639
Rui Ueyama717677a2016-02-11 21:17:59 +0000640void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000641 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000642 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000643 expect(")");
644}
645
Rui Ueyama717677a2016-02-11 21:17:59 +0000646void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000647 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000648 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000649 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000650 StringRef Tok = next();
651 if (peek() == "=") {
652 readAssignment(Tok);
653 expect(";");
654 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000655 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000656 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000657 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000658 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000659 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000660 }
George Rimar652852c2016-04-16 10:10:32 +0000661 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000662}
663
Rui Ueyama708019c2016-07-24 18:19:40 +0000664static int precedence(StringRef Op) {
665 return StringSwitch<int>(Op)
666 .Case("*", 4)
667 .Case("/", 4)
668 .Case("+", 3)
669 .Case("-", 3)
670 .Case("<", 2)
671 .Case(">", 2)
672 .Case(">=", 2)
673 .Case("<=", 2)
674 .Case("==", 2)
675 .Case("!=", 2)
676 .Case("&", 1)
677 .Default(-1);
678}
679
Davide Italiano0ed42b02016-07-25 21:47:13 +0000680void ScriptParser::readKeep(OutputSectionCommand *Cmd) {
681 expect("(");
682 expect("*");
683 expect("(");
684 auto *InCmd = new InputSectionDescription();
685 Cmd->Commands.emplace_back(InCmd);
686 while (!Error && !skip(")")) {
687 Opt.KeptSections.push_back(peek());
688 InCmd->Patterns.push_back(next());
689 }
690 expect(")");
691}
692
Eugene Levianteda81a12016-07-12 06:39:48 +0000693void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000694 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
695 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000696
697 // Read an address expression.
698 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
699 if (peek() != ":")
700 Cmd->AddrExpr = readExpr();
701
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000702 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000703
704 // Parse constraints.
705 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000706 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000707 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000708 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000709 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000710
Rui Ueyama025d59b2016-02-02 20:27:59 +0000711 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000712 StringRef Tok = next();
713 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000714 auto *InCmd = new InputSectionDescription();
715 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000716 expect("(");
717 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000718 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000719 } else if (Tok == "KEEP") {
Davide Italiano0ed42b02016-07-25 21:47:13 +0000720 readKeep(Cmd);
Davide Italiano054a6792016-07-24 23:13:48 +0000721 } else if (Tok == "PROVIDE") {
722 readProvide(false);
723 } else if (Tok == "PROVIDE_HIDDEN") {
724 readProvide(true);
George Rimar481c2ce2016-02-23 07:47:54 +0000725 } else {
George Rimar777f9632016-03-12 08:31:34 +0000726 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000727 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000728 }
George Rimar076fe152016-07-21 06:43:01 +0000729 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000730
George Rimare2ee72b2016-02-26 14:48:31 +0000731 StringRef Tok = peek();
732 if (Tok.startswith("=")) {
733 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000734 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000735 return;
736 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000737 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000738 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000739 next();
740 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000741}
742
Eugene Levianta31c91b2016-07-22 07:38:40 +0000743void ScriptParser::readProvide(bool Hidden) {
744 expect("(");
Rui Ueyama113cdec2016-07-24 23:05:57 +0000745 if (SymbolAssignment *Assignment = readAssignment(next())) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000746 Assignment->Provide = true;
747 Assignment->Hidden = Hidden;
748 }
749 expect(")");
750 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000751}
752
Rui Ueyama113cdec2016-07-24 23:05:57 +0000753SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000754 expect("=");
Rui Ueyama708019c2016-07-24 18:19:40 +0000755 Expr E = readExpr();
Rui Ueyama113cdec2016-07-24 23:05:57 +0000756 auto *Cmd = new SymbolAssignment(Name, E);
757 Opt.Commands.emplace_back(Cmd);
758 return Cmd;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000759}
760
Rui Ueyama708019c2016-07-24 18:19:40 +0000761// This is an operator-precedence parser to parse a linker
762// script expression.
763Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
Eugene Levianta31c91b2016-07-22 07:38:40 +0000764
Rui Ueyama708019c2016-07-24 18:19:40 +0000765// This is a part of the operator-precedence parser. This function
766// assumes that the remaining token stream starts with an operator.
767Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
768 while (!atEOF() && !Error) {
769 // Read an operator and an expression.
770 StringRef Op1 = peek();
771 if (Op1 == "?")
772 return readTernary(Lhs);
773 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000774 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000775 next();
776 Expr Rhs = readPrimary();
777
778 // Evaluate the remaining part of the expression first if the
779 // next operator has greater precedence than the previous one.
780 // For example, if we have read "+" and "3", and if the next
781 // operator is "*", then we'll evaluate 3 * ... part first.
782 while (!atEOF()) {
783 StringRef Op2 = peek();
784 if (precedence(Op2) <= precedence(Op1))
785 break;
786 Rhs = readExpr1(Rhs, precedence(Op2));
787 }
788
789 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000790 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000791 return Lhs;
792}
793
794uint64_t static getConstant(StringRef S) {
795 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
796 return Target->PageSize;
797 error("unknown constant: " + S);
798 return 0;
799}
800
801Expr ScriptParser::readPrimary() {
802 StringRef Tok = next();
803
804 if (Tok == ".")
805 return [](uint64_t Dot) { return Dot; };
806
807 if (Tok == "(") {
808 Expr E = readExpr();
809 expect(")");
810 return E;
811 }
812
813 // Built-in functions are parsed here.
814 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
815 if (Tok == "ALIGN") {
816 expect("(");
817 Expr E = readExpr();
818 expect(")");
819 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
820 }
821 if (Tok == "CONSTANT") {
822 expect("(");
823 StringRef Tok = next();
824 expect(")");
825 return [=](uint64_t Dot) { return getConstant(Tok); };
826 }
827 if (Tok == "DATA_SEGMENT_ALIGN") {
828 expect("(");
829 Expr E = readExpr();
830 expect(",");
831 readExpr();
832 expect(")");
833 return [=](uint64_t Dot) -> uint64_t {
834 uint64_t Val = E(Dot);
835 return alignTo(Dot, Val) + (Dot & (Val - 1));
836 };
837 }
838 if (Tok == "DATA_SEGMENT_END") {
839 expect("(");
840 expect(".");
841 expect(")");
842 return [](uint64_t Dot) { return Dot; };
843 }
844
845 // Parse a number literal
846 uint64_t V = 0;
847 if (Tok.getAsInteger(0, V))
848 setError("malformed number: " + Tok);
849 return [=](uint64_t Dot) { return V; };
850}
851
852Expr ScriptParser::readTernary(Expr Cond) {
853 next();
854 Expr L = readExpr();
855 expect(":");
856 Expr R = readExpr();
857 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
858}
859
860Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
861 if (Op == "*")
862 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
863 if (Op == "/") {
864 return [=](uint64_t Dot) -> uint64_t {
865 uint64_t RHS = R(Dot);
866 if (RHS == 0) {
867 error("division by zero");
868 return 0;
869 }
870 return L(Dot) / RHS;
871 };
872 }
873 if (Op == "+")
874 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
875 if (Op == "-")
876 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
877 if (Op == "<")
878 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
879 if (Op == ">")
880 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
881 if (Op == ">=")
882 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
883 if (Op == "<=")
884 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
885 if (Op == "==")
886 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
887 if (Op == "!=")
888 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
889 if (Op == "&")
890 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
891 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000892}
893
Eugene Leviantbbe38602016-07-19 09:25:43 +0000894std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
895 std::vector<StringRef> Phdrs;
896 while (!Error && peek().startswith(":")) {
897 StringRef Tok = next();
898 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
899 if (Tok.empty()) {
900 setError("section header name is empty");
901 break;
902 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000903 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000904 }
905 return Phdrs;
906}
907
908unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000909 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000910 unsigned Ret = StringSwitch<unsigned>(Tok)
911 .Case("PT_NULL", PT_NULL)
912 .Case("PT_LOAD", PT_LOAD)
913 .Case("PT_DYNAMIC", PT_DYNAMIC)
914 .Case("PT_INTERP", PT_INTERP)
915 .Case("PT_NOTE", PT_NOTE)
916 .Case("PT_SHLIB", PT_SHLIB)
917 .Case("PT_PHDR", PT_PHDR)
918 .Case("PT_TLS", PT_TLS)
919 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
920 .Case("PT_GNU_STACK", PT_GNU_STACK)
921 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
922 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000923
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000924 if (Ret == (unsigned)-1) {
925 setError("invalid program header type: " + Tok);
926 return PT_NULL;
927 }
928 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000929}
930
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000931static bool isUnderSysroot(StringRef Path) {
932 if (Config->Sysroot == "")
933 return false;
934 for (; !Path.empty(); Path = sys::path::parent_path(Path))
935 if (sys::fs::equivalent(Config->Sysroot, Path))
936 return true;
937 return false;
938}
939
Rui Ueyama07320e42016-04-20 20:13:41 +0000940// Entry point.
941void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000942 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000943 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000944}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000945
Rui Ueyama07320e42016-04-20 20:13:41 +0000946template class elf::LinkerScript<ELF32LE>;
947template class elf::LinkerScript<ELF32BE>;
948template class elf::LinkerScript<ELF64LE>;
949template class elf::LinkerScript<ELF64BE>;