blob: aacb5d8d7fa3ec65ecf6346492a4a8b9ccb9b346 [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) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000227 std::vector<PhdrEntry<ELFT>> Ret;
228 PhdrEntry<ELFT> *TlsPhdr = nullptr;
229 PhdrEntry<ELFT> *NotePhdr = nullptr;
230 PhdrEntry<ELFT> *RelroPhdr = nullptr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000231
232 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000233 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
234 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000235
236 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000237 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000238 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000239 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000240
241 switch (Cmd.Type) {
242 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000243 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000244 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000245 break;
246 case PT_DYNAMIC:
247 if (isOutputDynamic<ELFT>()) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000248 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
249 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000250 }
251 break;
252 case PT_TLS:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000253 TlsPhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000254 break;
255 case PT_NOTE:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000256 NotePhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000257 break;
258 case PT_GNU_RELRO:
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000259 RelroPhdr = &Phdr;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000260 break;
261 case PT_GNU_EH_FRAME:
262 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000263 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
264 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000265 }
266 break;
267 }
268 }
269
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000270 PhdrEntry<ELFT> *Load = nullptr;
271 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000272 for (OutputSectionBase<ELFT> *Sec : Sections) {
273 if (!(Sec->getFlags() & SHF_ALLOC))
274 break;
275
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000276 if (TlsPhdr && (Sec->getFlags() & SHF_TLS))
277 TlsPhdr->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000278
279 if (!needsPtLoad<ELFT>(Sec))
280 continue;
281
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000282 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000283 if (!PhdrIds.empty()) {
284 // Assign headers specified by linker script
285 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000286 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000287 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000288 Ret[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000289 }
290 } else {
291 // If we have no load segment or flags've changed then we want new load
292 // segment.
293 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
294 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000295 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000296 Flags = NewFlags;
297 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000298 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000299 }
300
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000301 if (RelroPhdr && isRelroSection(Sec))
302 RelroPhdr->add(Sec);
303 if (NotePhdr && Sec->getType() == SHT_NOTE)
304 NotePhdr->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000305 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000306 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000307}
308
309template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000310ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000311 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
312 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
313 if (Cmd->Name == Name)
314 return Cmd->Filler;
315 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000316}
317
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000318// Returns the index of the given section name in linker script
319// SECTIONS commands. Sections are laid out as the same order as they
320// were in the script. If a given name did not appear in the script,
321// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000322template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
George Rimar71b26e92016-04-21 10:22:02 +0000323 auto Begin = Opt.Commands.begin();
324 auto End = Opt.Commands.end();
George Rimar076fe152016-07-21 06:43:01 +0000325 auto I =
326 std::find_if(Begin, End, [&](const std::unique_ptr<BaseCommand> &Base) {
327 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
328 if (Cmd->Name == Name)
329 return true;
330 return false;
331 });
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000332 return I == End ? INT_MAX : (I - Begin);
George Rimar71b26e92016-04-21 10:22:02 +0000333}
334
335// A compartor to sort output sections. Returns -1 or 1 if
336// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000337template <class ELFT>
338int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000339 int I = getSectionIndex(A);
340 int J = getSectionIndex(B);
341 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000342 return 0;
343 return I < J ? -1 : 1;
344}
345
George Rimar076fe152016-07-21 06:43:01 +0000346template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000347 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
348 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
349 if (!Cmd || Cmd->Name == ".")
350 continue;
351
Davide Italiano8ab41082016-07-23 22:09:04 +0000352 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
353 if (!B || B->isUndefined())
Eugene Levianta31c91b2016-07-22 07:38:40 +0000354 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
355 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
356 else
357 // Symbol already exists in symbol table. If it is provided
358 // then we can't override its value.
359 Cmd->Ignore = Cmd->Provide;
360 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000361}
362
Eugene Leviantbbe38602016-07-19 09:25:43 +0000363template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
364 return !Opt.PhdrsCommands.empty();
365}
366
367// Returns indices of ELF headers containing specific section, identified
368// by Name. Each index is a zero based number of ELF header listed within
369// PHDRS {} script block.
370template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000371std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000372 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
373 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000374 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000375 continue;
376
377 std::vector<size_t> Indices;
George Rimar076fe152016-07-21 06:43:01 +0000378 for (StringRef PhdrName : Cmd->Phdrs) {
George Rimar31d842f2016-07-20 16:43:03 +0000379 auto ItPhdr =
380 std::find_if(Opt.PhdrsCommands.rbegin(), Opt.PhdrsCommands.rend(),
George Rimar076fe152016-07-21 06:43:01 +0000381 [&](PhdrsCommand &P) { return P.Name == PhdrName; });
Eugene Leviantbbe38602016-07-19 09:25:43 +0000382 if (ItPhdr == Opt.PhdrsCommands.rend())
383 error("section header '" + PhdrName + "' is not listed in PHDRS");
384 else
385 Indices.push_back(std::distance(ItPhdr, Opt.PhdrsCommands.rend()) - 1);
386 }
George Rimar31d842f2016-07-20 16:43:03 +0000387 return Indices;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000388 }
George Rimar31d842f2016-07-20 16:43:03 +0000389 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000390}
391
Rui Ueyama07320e42016-04-20 20:13:41 +0000392class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000393 typedef void (ScriptParser::*Handler)();
394
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000395public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000396 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000397
Rui Ueyama4a465392016-04-22 22:59:24 +0000398 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000399
400private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000401 void addFile(StringRef Path);
402
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000403 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000404 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000405 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000406 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000407 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000408 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000409 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000410 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000411 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000412 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000413 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000414 void readSections();
415
Rui Ueyama113cdec2016-07-24 23:05:57 +0000416 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000417 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000418 std::vector<StringRef> readOutputSectionPhdrs();
419 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000420 void readProvide(bool Hidden);
Rui Ueyama708019c2016-07-24 18:19:40 +0000421
422 Expr readExpr();
423 Expr readExpr1(Expr Lhs, int MinPrec);
424 Expr readPrimary();
425 Expr readTernary(Expr Cond);
426 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000427
George Rimarc3794e52016-02-24 09:21:47 +0000428 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000429 ScriptConfiguration &Opt = *ScriptConfig;
430 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000431 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000432};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000433
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000434const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000435 {"ENTRY", &ScriptParser::readEntry},
436 {"EXTERN", &ScriptParser::readExtern},
437 {"GROUP", &ScriptParser::readGroup},
438 {"INCLUDE", &ScriptParser::readInclude},
439 {"INPUT", &ScriptParser::readGroup},
440 {"OUTPUT", &ScriptParser::readOutput},
441 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
442 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000443 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000444 {"SEARCH_DIR", &ScriptParser::readSearchDir},
445 {"SECTIONS", &ScriptParser::readSections},
446 {";", &ScriptParser::readNothing}};
447
Rui Ueyama717677a2016-02-11 21:17:59 +0000448void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000449 while (!atEOF()) {
450 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000451 if (Handler Fn = Cmd.lookup(Tok))
452 (this->*Fn)();
453 else
George Rimar57610422016-03-11 14:43:02 +0000454 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000455 }
456}
457
Rui Ueyama717677a2016-02-11 21:17:59 +0000458void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000459 if (IsUnderSysroot && S.startswith("/")) {
460 SmallString<128> Path;
461 (Config->Sysroot + S).toStringRef(Path);
462 if (sys::fs::exists(Path)) {
463 Driver->addFile(Saver.save(Path.str()));
464 return;
465 }
466 }
467
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000468 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000469 Driver->addFile(S);
470 } else if (S.startswith("=")) {
471 if (Config->Sysroot.empty())
472 Driver->addFile(S.substr(1));
473 else
474 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
475 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000476 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000477 } else if (sys::fs::exists(S)) {
478 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000479 } else {
480 std::string Path = findFromSearchPaths(S);
481 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000482 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000483 else
484 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000485 }
486}
487
Rui Ueyama717677a2016-02-11 21:17:59 +0000488void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000489 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000490 bool Orig = Config->AsNeeded;
491 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000492 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000493 StringRef Tok = next();
494 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000495 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000496 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000497 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000498 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000499}
500
Rui Ueyama717677a2016-02-11 21:17:59 +0000501void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000502 // -e <symbol> takes predecence over ENTRY(<symbol>).
503 expect("(");
504 StringRef Tok = next();
505 if (Config->Entry.empty())
506 Config->Entry = Tok;
507 expect(")");
508}
509
Rui Ueyama717677a2016-02-11 21:17:59 +0000510void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000511 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000512 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000513 StringRef Tok = next();
514 if (Tok == ")")
515 return;
516 Config->Undefined.push_back(Tok);
517 }
518}
519
Rui Ueyama717677a2016-02-11 21:17:59 +0000520void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000521 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000522 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000523 StringRef Tok = next();
524 if (Tok == ")")
525 return;
526 if (Tok == "AS_NEEDED") {
527 readAsNeeded();
528 continue;
529 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000530 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000531 }
532}
533
Rui Ueyama717677a2016-02-11 21:17:59 +0000534void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000535 StringRef Tok = next();
536 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000537 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000538 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000539 return;
540 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000541 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000542 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
543 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000544 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000545}
546
Rui Ueyama717677a2016-02-11 21:17:59 +0000547void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000548 // -o <file> takes predecence over OUTPUT(<file>).
549 expect("(");
550 StringRef Tok = next();
551 if (Config->OutputFile.empty())
552 Config->OutputFile = Tok;
553 expect(")");
554}
555
Rui Ueyama717677a2016-02-11 21:17:59 +0000556void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000557 // Error checking only for now.
558 expect("(");
559 next();
560 expect(")");
561}
562
Rui Ueyama717677a2016-02-11 21:17:59 +0000563void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000564 // Error checking only for now.
565 expect("(");
566 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000567 StringRef Tok = next();
568 if (Tok == ")")
569 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000570 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000571 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000572 return;
573 }
Davide Italiano6836c612015-10-12 21:08:41 +0000574 next();
575 expect(",");
576 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000577 expect(")");
578}
579
Eugene Leviantbbe38602016-07-19 09:25:43 +0000580void ScriptParser::readPhdrs() {
581 expect("{");
582 while (!Error && !skip("}")) {
583 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000584 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000585 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
586
587 PhdrCmd.Type = readPhdrType();
588 do {
589 Tok = next();
590 if (Tok == ";")
591 break;
592 if (Tok == "FILEHDR")
593 PhdrCmd.HasFilehdr = true;
594 else if (Tok == "PHDRS")
595 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000596 else if (Tok == "FLAGS") {
597 expect("(");
598 next().getAsInteger(0, PhdrCmd.Flags);
599 expect(")");
600 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000601 setError("unexpected header attribute: " + Tok);
602 } while (!Error);
603 }
604}
605
Rui Ueyama717677a2016-02-11 21:17:59 +0000606void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000607 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000608 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000609 expect(")");
610}
611
Rui Ueyama717677a2016-02-11 21:17:59 +0000612void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000613 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000614 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000615 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000616 StringRef Tok = next();
617 if (peek() == "=") {
618 readAssignment(Tok);
619 expect(";");
620 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000621 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000622 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000623 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000624 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000625 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000626 }
George Rimar652852c2016-04-16 10:10:32 +0000627 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000628}
629
Rui Ueyama708019c2016-07-24 18:19:40 +0000630static int precedence(StringRef Op) {
631 return StringSwitch<int>(Op)
632 .Case("*", 4)
633 .Case("/", 4)
634 .Case("+", 3)
635 .Case("-", 3)
636 .Case("<", 2)
637 .Case(">", 2)
638 .Case(">=", 2)
639 .Case("<=", 2)
640 .Case("==", 2)
641 .Case("!=", 2)
642 .Case("&", 1)
643 .Default(-1);
644}
645
Eugene Levianteda81a12016-07-12 06:39:48 +0000646void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000647 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
648 Opt.Commands.emplace_back(Cmd);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000649 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000650
651 // Parse constraints.
652 if (skip("ONLY_IF_RO"))
653 Cmd->Constraint = ReadOnly;
654 if (skip("ONLY_IF_RW"))
655 Cmd->Constraint = ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000656 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000657
Rui Ueyama025d59b2016-02-02 20:27:59 +0000658 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000659 StringRef Tok = next();
660 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000661 auto *InCmd = new InputSectionDescription();
662 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000663 expect("(");
664 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000665 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000666 } else if (Tok == "KEEP") {
667 expect("(");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000668 expect("*");
669 expect("(");
George Rimareea31142016-07-21 14:26:59 +0000670 auto *InCmd = new InputSectionDescription();
671 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000672 while (!Error && !skip(")")) {
George Rimareea31142016-07-21 14:26:59 +0000673 Opt.KeptSections.push_back(peek());
674 InCmd->Patterns.push_back(next());
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000675 }
George Rimar481c2ce2016-02-23 07:47:54 +0000676 expect(")");
Davide Italiano054a6792016-07-24 23:13:48 +0000677 } else if (Tok == "PROVIDE") {
678 readProvide(false);
679 } else if (Tok == "PROVIDE_HIDDEN") {
680 readProvide(true);
George Rimar481c2ce2016-02-23 07:47:54 +0000681 } else {
George Rimar777f9632016-03-12 08:31:34 +0000682 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000683 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000684 }
George Rimar076fe152016-07-21 06:43:01 +0000685 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000686
George Rimare2ee72b2016-02-26 14:48:31 +0000687 StringRef Tok = peek();
688 if (Tok.startswith("=")) {
689 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000690 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000691 return;
692 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000693 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000694 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000695 next();
696 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000697}
698
Eugene Levianta31c91b2016-07-22 07:38:40 +0000699void ScriptParser::readProvide(bool Hidden) {
700 expect("(");
Rui Ueyama113cdec2016-07-24 23:05:57 +0000701 if (SymbolAssignment *Assignment = readAssignment(next())) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000702 Assignment->Provide = true;
703 Assignment->Hidden = Hidden;
704 }
705 expect(")");
706 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000707}
708
Rui Ueyama113cdec2016-07-24 23:05:57 +0000709SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000710 expect("=");
Rui Ueyama708019c2016-07-24 18:19:40 +0000711 Expr E = readExpr();
Rui Ueyama113cdec2016-07-24 23:05:57 +0000712 auto *Cmd = new SymbolAssignment(Name, E);
713 Opt.Commands.emplace_back(Cmd);
714 return Cmd;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000715}
716
Rui Ueyama708019c2016-07-24 18:19:40 +0000717// This is an operator-precedence parser to parse a linker
718// script expression.
719Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
Eugene Levianta31c91b2016-07-22 07:38:40 +0000720
Rui Ueyama708019c2016-07-24 18:19:40 +0000721// This is a part of the operator-precedence parser. This function
722// assumes that the remaining token stream starts with an operator.
723Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
724 while (!atEOF() && !Error) {
725 // Read an operator and an expression.
726 StringRef Op1 = peek();
727 if (Op1 == "?")
728 return readTernary(Lhs);
729 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000730 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000731 next();
732 Expr Rhs = readPrimary();
733
734 // Evaluate the remaining part of the expression first if the
735 // next operator has greater precedence than the previous one.
736 // For example, if we have read "+" and "3", and if the next
737 // operator is "*", then we'll evaluate 3 * ... part first.
738 while (!atEOF()) {
739 StringRef Op2 = peek();
740 if (precedence(Op2) <= precedence(Op1))
741 break;
742 Rhs = readExpr1(Rhs, precedence(Op2));
743 }
744
745 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000746 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000747 return Lhs;
748}
749
750uint64_t static getConstant(StringRef S) {
751 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
752 return Target->PageSize;
753 error("unknown constant: " + S);
754 return 0;
755}
756
757Expr ScriptParser::readPrimary() {
758 StringRef Tok = next();
759
760 if (Tok == ".")
761 return [](uint64_t Dot) { return Dot; };
762
763 if (Tok == "(") {
764 Expr E = readExpr();
765 expect(")");
766 return E;
767 }
768
769 // Built-in functions are parsed here.
770 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
771 if (Tok == "ALIGN") {
772 expect("(");
773 Expr E = readExpr();
774 expect(")");
775 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
776 }
777 if (Tok == "CONSTANT") {
778 expect("(");
779 StringRef Tok = next();
780 expect(")");
781 return [=](uint64_t Dot) { return getConstant(Tok); };
782 }
783 if (Tok == "DATA_SEGMENT_ALIGN") {
784 expect("(");
785 Expr E = readExpr();
786 expect(",");
787 readExpr();
788 expect(")");
789 return [=](uint64_t Dot) -> uint64_t {
790 uint64_t Val = E(Dot);
791 return alignTo(Dot, Val) + (Dot & (Val - 1));
792 };
793 }
794 if (Tok == "DATA_SEGMENT_END") {
795 expect("(");
796 expect(".");
797 expect(")");
798 return [](uint64_t Dot) { return Dot; };
799 }
800
801 // Parse a number literal
802 uint64_t V = 0;
803 if (Tok.getAsInteger(0, V))
804 setError("malformed number: " + Tok);
805 return [=](uint64_t Dot) { return V; };
806}
807
808Expr ScriptParser::readTernary(Expr Cond) {
809 next();
810 Expr L = readExpr();
811 expect(":");
812 Expr R = readExpr();
813 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
814}
815
816Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
817 if (Op == "*")
818 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
819 if (Op == "/") {
820 return [=](uint64_t Dot) -> uint64_t {
821 uint64_t RHS = R(Dot);
822 if (RHS == 0) {
823 error("division by zero");
824 return 0;
825 }
826 return L(Dot) / RHS;
827 };
828 }
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 if (Op == "&")
846 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
847 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000848}
849
Eugene Leviantbbe38602016-07-19 09:25:43 +0000850std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
851 std::vector<StringRef> Phdrs;
852 while (!Error && peek().startswith(":")) {
853 StringRef Tok = next();
854 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
855 if (Tok.empty()) {
856 setError("section header name is empty");
857 break;
858 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000859 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000860 }
861 return Phdrs;
862}
863
864unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000865 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000866 unsigned Ret = StringSwitch<unsigned>(Tok)
867 .Case("PT_NULL", PT_NULL)
868 .Case("PT_LOAD", PT_LOAD)
869 .Case("PT_DYNAMIC", PT_DYNAMIC)
870 .Case("PT_INTERP", PT_INTERP)
871 .Case("PT_NOTE", PT_NOTE)
872 .Case("PT_SHLIB", PT_SHLIB)
873 .Case("PT_PHDR", PT_PHDR)
874 .Case("PT_TLS", PT_TLS)
875 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
876 .Case("PT_GNU_STACK", PT_GNU_STACK)
877 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
878 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000879
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000880 if (Ret == (unsigned)-1) {
881 setError("invalid program header type: " + Tok);
882 return PT_NULL;
883 }
884 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000885}
886
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000887static bool isUnderSysroot(StringRef Path) {
888 if (Config->Sysroot == "")
889 return false;
890 for (; !Path.empty(); Path = sys::path::parent_path(Path))
891 if (sys::fs::equivalent(Config->Sysroot, Path))
892 return true;
893 return false;
894}
895
Rui Ueyama07320e42016-04-20 20:13:41 +0000896// Entry point.
897void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000898 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000899 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000900}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000901
Rui Ueyama07320e42016-04-20 20:13:41 +0000902template class elf::LinkerScript<ELF32LE>;
903template class elf::LinkerScript<ELF32BE>;
904template class elf::LinkerScript<ELF64LE>;
905template class elf::LinkerScript<ELF64BE>;