blob: 9ccc27ddcdcf7e95b4a7a695e54db3eee11182ef [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;
82
Eugene Leviante63d81b2016-07-20 14:43:20 +000083 // Add input section to output section. If there is no output section yet,
84 // then create it and add to output section list.
Rui Ueyama3c291e12016-07-25 21:30:00 +000085 auto AddInputSec = [&](InputSectionBase<ELFT> *C, StringRef Name) {
Eugene Leviante63d81b2016-07-20 14:43:20 +000086 OutputSectionBase<ELFT> *Sec;
87 bool IsNew;
88 std::tie(Sec, IsNew) = Factory.create(C, Name);
89 if (IsNew)
Rui Ueyamaa7f78842016-07-20 17:19:03 +000090 Result.push_back(Sec);
Eugene Leviante63d81b2016-07-20 14:43:20 +000091 Sec->addSection(C);
92 };
93
94 // Select input sections matching rule and add them to corresponding
95 // output section. Section rules are processed in order they're listed
96 // in script, so correct input section order is maintained by design.
George Rimareea31142016-07-21 14:26:59 +000097 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
98 auto *OutCmd = dyn_cast<OutputSectionCommand>(Base.get());
99 if (!OutCmd)
100 continue;
101
102 for (const std::unique_ptr<BaseCommand> &Cmd : OutCmd->Commands) {
103 auto *InCmd = dyn_cast<InputSectionDescription>(Cmd.get());
104 if (!InCmd)
105 continue;
106
107 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles()) {
108 for (InputSectionBase<ELFT> *S : F->getSections()) {
109 if (isDiscarded(S) || S->OutSec)
110 continue;
111
112 if (match(S->getSectionName(), InCmd->Patterns)) {
113 if (OutCmd->Name == "/DISCARD/")
114 S->Live = false;
115 else
Rui Ueyama3c291e12016-07-25 21:30:00 +0000116 AddInputSec(S, OutCmd->Name);
George Rimareea31142016-07-21 14:26:59 +0000117 }
118 }
119 }
120 }
121 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000122
123 // Add all other input sections, which are not listed in script.
George Rimareea31142016-07-21 14:26:59 +0000124 for (ObjectFile &F : Symtab<ELFT>::X->getObjectFiles())
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000125 for (InputSectionBase<ELFT> *S : F->getSections()) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000126 if (!isDiscarded(S)) {
127 if (!S->OutSec)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000128 AddInputSec(S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000129 } else
130 reportDiscarded(S, F);
Reid Kleckner3c944ec2016-07-21 18:39:28 +0000131 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000132
Rui Ueyama3c291e12016-07-25 21:30:00 +0000133 // Remove from the output all the sections which did not meet
134 // the optional constraints.
135 return filter(Result);
136}
137
138// Process ONLY_IF_RO and ONLY_IF_RW.
139template <class ELFT>
140std::vector<OutputSectionBase<ELFT> *>
141LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
142 // Sections and OutputSectionCommands are parallel arrays.
143 // In this loop, we remove output sections if they don't satisfy
144 // requested properties.
145 auto It = Sections.begin();
146 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
147 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
148 if (!Cmd || Cmd->Name == "/DISCARD/")
149 continue;
150
151 if (Cmd->Constraint == ConstraintKind::NoConstraint) {
152 ++It;
153 continue;
154 }
155
156 OutputSectionBase<ELFT> *Sec = *It;
157 bool Writable = (Sec->getFlags() & SHF_WRITE);
158 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
159 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
160
161 if ((RO && Writable) || (RW && !Writable)) {
162 Sections.erase(It);
163 continue;
164 }
165 ++It;
166 }
167 return Sections;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000168}
169
170template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000171void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
Rui Ueyama708019c2016-07-24 18:19:40 +0000172 uint64_t Val = Cmd->Expression(Dot);
George Rimar10e576e2016-07-21 16:07:40 +0000173 if (Cmd->Name == ".") {
174 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000175 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000176 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
177 D->Value = Val;
178 }
179}
180
181template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000182void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000183 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000184 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000185 // are not explicitly placed into the output file by the linker script.
186 // We place orphan sections at end of file.
187 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000188 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000189 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000190 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000191 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000192 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000193 }
George Rimar652852c2016-04-16 10:10:32 +0000194
Rui Ueyama7c18c282016-04-18 21:00:40 +0000195 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000196 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000197 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000198 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000199
George Rimar076fe152016-07-21 06:43:01 +0000200 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
201 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000202 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000203 continue;
204 }
205
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000206 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000207 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000208 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000209 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000210 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000211 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000212 continue;
George Rimar652852c2016-04-16 10:10:32 +0000213
George Rimar58e5c4d2016-07-25 08:29:46 +0000214 if (Cmd->AddrExpr)
215 Dot = Cmd->AddrExpr(Dot);
216
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000217 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
218 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000219 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000220 Sec->setVA(TVA);
221 ThreadBssOffset = TVA - Dot + Sec->getSize();
222 continue;
223 }
George Rimar652852c2016-04-16 10:10:32 +0000224
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000225 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000226 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000227 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000228 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000229 Dot += Sec->getSize();
230 continue;
231 }
George Rimar652852c2016-04-16 10:10:32 +0000232 }
233 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000234
Rafael Espindola64c32d62016-07-07 14:28:47 +0000235 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000236 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000237 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
238 Out<ELFT>::ProgramHeaders->getSize(),
239 Target->PageSize);
240 Out<ELFT>::ElfHeader->setVA(MinVA);
241 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000242}
243
Rui Ueyama07320e42016-04-20 20:13:41 +0000244template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000245std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000246LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000247 std::vector<PhdrEntry<ELFT>> Ret;
248 PhdrEntry<ELFT> *TlsPhdr = nullptr;
249 PhdrEntry<ELFT> *NotePhdr = nullptr;
250 PhdrEntry<ELFT> *RelroPhdr = nullptr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000251
252 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000253 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
254 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000255
256 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000257 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000258 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000259 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000260
261 switch (Cmd.Type) {
262 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000263 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000264 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000265 break;
266 case PT_DYNAMIC:
267 if (isOutputDynamic<ELFT>()) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000268 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
269 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000270 }
271 break;
272 case PT_TLS:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000273 TlsPhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000274 break;
275 case PT_NOTE:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000276 NotePhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000277 break;
278 case PT_GNU_RELRO:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000279 RelroPhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000280 break;
281 case PT_GNU_EH_FRAME:
282 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000283 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
284 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000285 }
286 break;
287 }
288 }
289
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000290 PhdrEntry<ELFT> *Load = nullptr;
291 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000292 for (OutputSectionBase<ELFT> *Sec : Sections) {
293 if (!(Sec->getFlags() & SHF_ALLOC))
294 break;
295
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000296 if (TlsPhdr && (Sec->getFlags() & SHF_TLS))
297 TlsPhdr->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000298
299 if (!needsPtLoad<ELFT>(Sec))
300 continue;
301
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000302 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000303 if (!PhdrIds.empty()) {
304 // Assign headers specified by linker script
305 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000306 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000307 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000308 Ret[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000309 }
310 } else {
311 // If we have no load segment or flags've changed then we want new load
312 // segment.
313 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
314 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000315 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000316 Flags = NewFlags;
317 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000318 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000319 }
320
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000321 if (RelroPhdr && isRelroSection(Sec))
322 RelroPhdr->add(Sec);
323 if (NotePhdr && Sec->getType() == SHT_NOTE)
324 NotePhdr->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000325 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000326 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000327}
328
329template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000330ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000331 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
332 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
333 if (Cmd->Name == Name)
334 return Cmd->Filler;
335 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000336}
337
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000338// Returns the index of the given section name in linker script
339// SECTIONS commands. Sections are laid out as the same order as they
340// were in the script. If a given name did not appear in the script,
341// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000342template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000343 auto Begin = Opt.Commands.begin();
344 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000345 auto I =
346 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
347 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
348 if (Cmd->Name == Name)
349 return true;
350 return false;
351 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000352 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000353}
354
355// A compartor to sort output sections. Returns -1 or 1 if
356// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000357template <class ELFT>
358int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000359 int I = getSectionIndex(A);
360 int J = getSectionIndex(B);
361 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000362 return 0;
363 return I < J ? -1 : 1;
364}
365
George Rimar076fe152016-07-21 06:43:01 +0000366template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000367 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
368 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
369 if (!Cmd || Cmd->Name == ".")
370 continue;
371
Davide Italiano8ab41082016-07-23 22:09:04 +0000372 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Davide Italiano373a5332016-07-25 00:25:18 +0000373 // The semantic of PROVIDE is that of introducing a symbol only if
374 // it's not defined and there's at least a reference to it.
375 if ((!B && !Cmd->Provide) || (B && B->isUndefined()))
Eugene Levianta31c91b2016-07-22 07:38:40 +0000376 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
377 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
378 else
379 // Symbol already exists in symbol table. If it is provided
380 // then we can't override its value.
381 Cmd->Ignore = Cmd->Provide;
382 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000383}
384
Eugene Leviantbbe38602016-07-19 09:25:43 +0000385template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
386 return !Opt.PhdrsCommands.empty();
387}
388
389// Returns indices of ELF headers containing specific section, identified
390// by Name. Each index is a zero based number of ELF header listed within
391// PHDRS {} script block.
392template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000393std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000394 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
395 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000396 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000397 continue;
398
399 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000400 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000401 auto ItPhdr =
402 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000403 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000404 if (ItPhdr == Opt.PhdrsCommands.rend())
405 error("section header '" + PhdrName + "' is not listed in PHDRS");
406 else
407 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
408 }
George Rimar31d842f2016-07-20 16:43:03 +0000409 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000410 }
George Rimar31d842f2016-07-20 16:43:03 +0000411 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000412}
413
Rui Ueyama07320e42016-04-20 20:13:41 +0000414class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000415 typedef void (ScriptParser::*Handler)();
416
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000417public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000418 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000419
Rui Ueyama4a465392016-04-22 22:59:24 +0000420 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000421
422private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000423 void addFile(StringRef Path);
424
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000425 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000426 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000427 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000428 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000429 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000430 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000431 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000432 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000433 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000434 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000435 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000436 void readSections();
437
Rui Ueyama113cdec2016-07-24 23:05:57 +0000438 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000439 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000440 std::vector<StringRef> readOutputSectionPhdrs();
441 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000442 void readProvide(bool Hidden);
Rui Ueyama708019c2016-07-24 18:19:40 +0000443
444 Expr readExpr();
445 Expr readExpr1(Expr Lhs, int MinPrec);
446 Expr readPrimary();
447 Expr readTernary(Expr Cond);
448 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000449
George Rimarc3794e52016-02-24 09:21:47 +0000450 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000451 ScriptConfiguration &Opt = *ScriptConfig;
452 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000453 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000454};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000455
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000456const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000457 {"ENTRY", &ScriptParser::readEntry},
458 {"EXTERN", &ScriptParser::readExtern},
459 {"GROUP", &ScriptParser::readGroup},
460 {"INCLUDE", &ScriptParser::readInclude},
461 {"INPUT", &ScriptParser::readGroup},
462 {"OUTPUT", &ScriptParser::readOutput},
463 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
464 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000465 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000466 {"SEARCH_DIR", &ScriptParser::readSearchDir},
467 {"SECTIONS", &ScriptParser::readSections},
468 {";", &ScriptParser::readNothing}};
469
Rui Ueyama717677a2016-02-11 21:17:59 +0000470void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000471 while (!atEOF()) {
472 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000473 if (Handler Fn = Cmd.lookup(Tok))
474 (this->*Fn)();
475 else
George Rimar57610422016-03-11 14:43:02 +0000476 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000477 }
478}
479
Rui Ueyama717677a2016-02-11 21:17:59 +0000480void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000481 if (IsUnderSysroot && S.startswith("/")) {
482 SmallString<128> Path;
483 (Config->Sysroot + S).toStringRef(Path);
484 if (sys::fs::exists(Path)) {
485 Driver->addFile(Saver.save(Path.str()));
486 return;
487 }
488 }
489
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000490 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000491 Driver->addFile(S);
492 } else if (S.startswith("=")) {
493 if (Config->Sysroot.empty())
494 Driver->addFile(S.substr(1));
495 else
496 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
497 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000498 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000499 } else if (sys::fs::exists(S)) {
500 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000501 } else {
502 std::string Path = findFromSearchPaths(S);
503 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000504 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000505 else
506 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000507 }
508}
509
Rui Ueyama717677a2016-02-11 21:17:59 +0000510void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000511 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000512 bool Orig = Config->AsNeeded;
513 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000514 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000515 StringRef Tok = next();
516 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000517 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000518 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000519 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000520 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000521}
522
Rui Ueyama717677a2016-02-11 21:17:59 +0000523void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000524 // -e <symbol> takes predecence over ENTRY(<symbol>).
525 expect("(");
526 StringRef Tok = next();
527 if (Config->Entry.empty())
528 Config->Entry = Tok;
529 expect(")");
530}
531
Rui Ueyama717677a2016-02-11 21:17:59 +0000532void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000533 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000534 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000535 StringRef Tok = next();
536 if (Tok == ")")
537 return;
538 Config->Undefined.push_back(Tok);
539 }
540}
541
Rui Ueyama717677a2016-02-11 21:17:59 +0000542void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000543 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000544 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000545 StringRef Tok = next();
546 if (Tok == ")")
547 return;
548 if (Tok == "AS_NEEDED") {
549 readAsNeeded();
550 continue;
551 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000552 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000553 }
554}
555
Rui Ueyama717677a2016-02-11 21:17:59 +0000556void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000557 StringRef Tok = next();
558 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000559 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000560 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000561 return;
562 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000563 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000564 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
565 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000566 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000567}
568
Rui Ueyama717677a2016-02-11 21:17:59 +0000569void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000570 // -o <file> takes predecence over OUTPUT(<file>).
571 expect("(");
572 StringRef Tok = next();
573 if (Config->OutputFile.empty())
574 Config->OutputFile = Tok;
575 expect(")");
576}
577
Rui Ueyama717677a2016-02-11 21:17:59 +0000578void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000579 // Error checking only for now.
580 expect("(");
581 next();
582 expect(")");
583}
584
Rui Ueyama717677a2016-02-11 21:17:59 +0000585void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000586 // Error checking only for now.
587 expect("(");
588 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000589 StringRef Tok = next();
590 if (Tok == ")")
591 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000592 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000593 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000594 return;
595 }
Davide Italiano6836c612015-10-12 21:08:41 +0000596 next();
597 expect(",");
598 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000599 expect(")");
600}
601
Eugene Leviantbbe38602016-07-19 09:25:43 +0000602void ScriptParser::readPhdrs() {
603 expect("{");
604 while (!Error && !skip("}")) {
605 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000606 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000607 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
608
609 PhdrCmd.Type = readPhdrType();
610 do {
611 Tok = next();
612 if (Tok == ";")
613 break;
614 if (Tok == "FILEHDR")
615 PhdrCmd.HasFilehdr = true;
616 else if (Tok == "PHDRS")
617 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000618 else if (Tok == "FLAGS") {
619 expect("(");
620 next().getAsInteger(0, PhdrCmd.Flags);
621 expect(")");
622 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000623 setError("unexpected header attribute: " + Tok);
624 } while (!Error);
625 }
626}
627
Rui Ueyama717677a2016-02-11 21:17:59 +0000628void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000629 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000630 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000631 expect(")");
632}
633
Rui Ueyama717677a2016-02-11 21:17:59 +0000634void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000635 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000636 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000637 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000638 StringRef Tok = next();
639 if (peek() == "=") {
640 readAssignment(Tok);
641 expect(";");
642 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000643 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000644 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000645 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000646 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000647 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000648 }
George Rimar652852c2016-04-16 10:10:32 +0000649 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000650}
651
Rui Ueyama708019c2016-07-24 18:19:40 +0000652static int precedence(StringRef Op) {
653 return StringSwitch<int>(Op)
654 .Case("*", 4)
655 .Case("/", 4)
656 .Case("+", 3)
657 .Case("-", 3)
658 .Case("<", 2)
659 .Case(">", 2)
660 .Case(">=", 2)
661 .Case("<=", 2)
662 .Case("==", 2)
663 .Case("!=", 2)
664 .Case("&", 1)
665 .Default(-1);
666}
667
Eugene Levianteda81a12016-07-12 06:39:48 +0000668void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000669 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
670 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000671
672 // Read an address expression.
673 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
674 if (peek() != ":")
675 Cmd->AddrExpr = readExpr();
676
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000677 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000678
679 // Parse constraints.
680 if (skip("ONLY_IF_RO"))
681 Cmd->Constraint = ReadOnly;
682 if (skip("ONLY_IF_RW"))
683 Cmd->Constraint = ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000684 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000685
Rui Ueyama025d59b2016-02-02 20:27:59 +0000686 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000687 StringRef Tok = next();
688 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000689 auto *InCmd = new InputSectionDescription();
690 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000691 expect("(");
692 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000693 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000694 } else if (Tok == "KEEP") {
695 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000696 expect("*");
697 expect("(");
George Rimareea31142016-07-21 14:26:59 +0000698 auto *InCmd = new InputSectionDescription();
699 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000700 while (!Error && !skip(")")) {
George Rimareea31142016-07-21 14:26:59 +0000701 Opt.KeptSections.push_back(peek());
702 InCmd->Patterns.push_back(next());
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000703 }
George Rimar481c2ce2016-02-23 07:47:54 +0000704 expect(")");
Davide Italiano054a6792016-07-24 23:13:48 +0000705 } else if (Tok == "PROVIDE") {
706 readProvide(false);
707 } else if (Tok == "PROVIDE_HIDDEN") {
708 readProvide(true);
George Rimar481c2ce2016-02-23 07:47:54 +0000709 } else {
George Rimar777f9632016-03-12 08:31:34 +0000710 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000711 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000712 }
George Rimar076fe152016-07-21 06:43:01 +0000713 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000714
George Rimare2ee72b2016-02-26 14:48:31 +0000715 StringRef Tok = peek();
716 if (Tok.startswith("=")) {
717 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000718 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000719 return;
720 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000721 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000722 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000723 next();
724 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000725}
726
Eugene Levianta31c91b2016-07-22 07:38:40 +0000727void ScriptParser::readProvide(bool Hidden) {
728 expect("(");
Rui Ueyama113cdec2016-07-24 23:05:57 +0000729 if (SymbolAssignment *Assignment = readAssignment(next())) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000730 Assignment->Provide = true;
731 Assignment->Hidden = Hidden;
732 }
733 expect(")");
734 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000735}
736
Rui Ueyama113cdec2016-07-24 23:05:57 +0000737SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000738 expect("=");
Rui Ueyama708019c2016-07-24 18:19:40 +0000739 Expr E = readExpr();
Rui Ueyama113cdec2016-07-24 23:05:57 +0000740 auto *Cmd = new SymbolAssignment(Name, E);
741 Opt.Commands.emplace_back(Cmd);
742 return Cmd;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000743}
744
Rui Ueyama708019c2016-07-24 18:19:40 +0000745// This is an operator-precedence parser to parse a linker
746// script expression.
747Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
Eugene Levianta31c91b2016-07-22 07:38:40 +0000748
Rui Ueyama708019c2016-07-24 18:19:40 +0000749// This is a part of the operator-precedence parser. This function
750// assumes that the remaining token stream starts with an operator.
751Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
752 while (!atEOF() && !Error) {
753 // Read an operator and an expression.
754 StringRef Op1 = peek();
755 if (Op1 == "?")
756 return readTernary(Lhs);
757 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000758 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000759 next();
760 Expr Rhs = readPrimary();
761
762 // Evaluate the remaining part of the expression first if the
763 // next operator has greater precedence than the previous one.
764 // For example, if we have read "+" and "3", and if the next
765 // operator is "*", then we'll evaluate 3 * ... part first.
766 while (!atEOF()) {
767 StringRef Op2 = peek();
768 if (precedence(Op2) <= precedence(Op1))
769 break;
770 Rhs = readExpr1(Rhs, precedence(Op2));
771 }
772
773 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000774 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000775 return Lhs;
776}
777
778uint64_t static getConstant(StringRef S) {
779 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
780 return Target->PageSize;
781 error("unknown constant: " + S);
782 return 0;
783}
784
785Expr ScriptParser::readPrimary() {
786 StringRef Tok = next();
787
788 if (Tok == ".")
789 return [](uint64_t Dot) { return Dot; };
790
791 if (Tok == "(") {
792 Expr E = readExpr();
793 expect(")");
794 return E;
795 }
796
797 // Built-in functions are parsed here.
798 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
799 if (Tok == "ALIGN") {
800 expect("(");
801 Expr E = readExpr();
802 expect(")");
803 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
804 }
805 if (Tok == "CONSTANT") {
806 expect("(");
807 StringRef Tok = next();
808 expect(")");
809 return [=](uint64_t Dot) { return getConstant(Tok); };
810 }
811 if (Tok == "DATA_SEGMENT_ALIGN") {
812 expect("(");
813 Expr E = readExpr();
814 expect(",");
815 readExpr();
816 expect(")");
817 return [=](uint64_t Dot) -> uint64_t {
818 uint64_t Val = E(Dot);
819 return alignTo(Dot, Val) + (Dot & (Val - 1));
820 };
821 }
822 if (Tok == "DATA_SEGMENT_END") {
823 expect("(");
824 expect(".");
825 expect(")");
826 return [](uint64_t Dot) { return Dot; };
827 }
828
829 // Parse a number literal
830 uint64_t V = 0;
831 if (Tok.getAsInteger(0, V))
832 setError("malformed number: " + Tok);
833 return [=](uint64_t Dot) { return V; };
834}
835
836Expr ScriptParser::readTernary(Expr Cond) {
837 next();
838 Expr L = readExpr();
839 expect(":");
840 Expr R = readExpr();
841 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
842}
843
844Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
845 if (Op == "*")
846 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
847 if (Op == "/") {
848 return [=](uint64_t Dot) -> uint64_t {
849 uint64_t RHS = R(Dot);
850 if (RHS == 0) {
851 error("division by zero");
852 return 0;
853 }
854 return L(Dot) / RHS;
855 };
856 }
857 if (Op == "+")
858 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
859 if (Op == "-")
860 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
861 if (Op == "<")
862 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
863 if (Op == ">")
864 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
865 if (Op == ">=")
866 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
867 if (Op == "<=")
868 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
869 if (Op == "==")
870 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
871 if (Op == "!=")
872 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
873 if (Op == "&")
874 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
875 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000876}
877
Eugene Leviantbbe38602016-07-19 09:25:43 +0000878std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
879 std::vector<StringRef> Phdrs;
880 while (!Error && peek().startswith(":")) {
881 StringRef Tok = next();
882 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
883 if (Tok.empty()) {
884 setError("section header name is empty");
885 break;
886 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000887 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000888 }
889 return Phdrs;
890}
891
892unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000893 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000894 unsigned Ret = StringSwitch<unsigned>(Tok)
895 .Case("PT_NULL", PT_NULL)
896 .Case("PT_LOAD", PT_LOAD)
897 .Case("PT_DYNAMIC", PT_DYNAMIC)
898 .Case("PT_INTERP", PT_INTERP)
899 .Case("PT_NOTE", PT_NOTE)
900 .Case("PT_SHLIB", PT_SHLIB)
901 .Case("PT_PHDR", PT_PHDR)
902 .Case("PT_TLS", PT_TLS)
903 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
904 .Case("PT_GNU_STACK", PT_GNU_STACK)
905 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
906 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000907
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000908 if (Ret == (unsigned)-1) {
909 setError("invalid program header type: " + Tok);
910 return PT_NULL;
911 }
912 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000913}
914
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000915static bool isUnderSysroot(StringRef Path) {
916 if (Config->Sysroot == "")
917 return false;
918 for (; !Path.empty(); Path = sys::path::parent_path(Path))
919 if (sys::fs::equivalent(Config->Sysroot, Path))
920 return true;
921 return false;
922}
923
Rui Ueyama07320e42016-04-20 20:13:41 +0000924// Entry point.
925void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000926 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000927 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000928}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000929
Rui Ueyama07320e42016-04-20 20:13:41 +0000930template class elf::LinkerScript<ELF32LE>;
931template class elf::LinkerScript<ELF32BE>;
932template class elf::LinkerScript<ELF64LE>;
933template class elf::LinkerScript<ELF64BE>;