blob: 1079a2fa99b3abcb131903c3664a8bc4801f7e23 [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) {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000153 // In this loop, we remove output sections if they don't satisfy
154 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000155 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
156 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
157 if (!Cmd || Cmd->Name == "/DISCARD/")
158 continue;
159
George Rimarbfc4a4b2016-07-26 10:47:09 +0000160 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000161 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000162
163 auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
164 return S->getName() == Cmd->Name;
165 });
166 if (It == Sections.end())
167 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000168
169 OutputSectionBase<ELFT> *Sec = *It;
170 bool Writable = (Sec->getFlags() & SHF_WRITE);
171 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
172 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
173
174 if ((RO && Writable) || (RW && !Writable)) {
175 Sections.erase(It);
176 continue;
177 }
Rui Ueyama3c291e12016-07-25 21:30:00 +0000178 }
179 return Sections;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000180}
181
182template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000183void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
Rui Ueyama708019c2016-07-24 18:19:40 +0000184 uint64_t Val = Cmd->Expression(Dot);
George Rimar10e576e2016-07-21 16:07:40 +0000185 if (Cmd->Name == ".") {
186 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000187 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000188 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
189 D->Value = Val;
190 }
191}
192
193template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000194void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000195 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000196 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000197 // are not explicitly placed into the output file by the linker script.
198 // We place orphan sections at end of file.
199 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000200 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000201 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000202 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000203 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000204 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000205 }
George Rimar652852c2016-04-16 10:10:32 +0000206
Rui Ueyama7c18c282016-04-18 21:00:40 +0000207 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000208 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000209 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000210 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000211
George Rimar076fe152016-07-21 06:43:01 +0000212 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
213 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000214 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000215 continue;
216 }
217
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000218 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000219 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000220 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000221 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000222 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000223 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000224 continue;
George Rimar652852c2016-04-16 10:10:32 +0000225
George Rimar58e5c4d2016-07-25 08:29:46 +0000226 if (Cmd->AddrExpr)
227 Dot = Cmd->AddrExpr(Dot);
228
George Rimar630c6172016-07-26 18:06:29 +0000229 if (Cmd->AlignExpr)
230 Sec->updateAlignment(Cmd->AlignExpr(Dot));
231
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000232 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
233 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000234 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000235 Sec->setVA(TVA);
236 ThreadBssOffset = TVA - Dot + Sec->getSize();
237 continue;
238 }
George Rimar652852c2016-04-16 10:10:32 +0000239
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000240 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000241 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000242 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000243 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000244 Dot += Sec->getSize();
245 continue;
246 }
George Rimar652852c2016-04-16 10:10:32 +0000247 }
248 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000249
Rafael Espindola64c32d62016-07-07 14:28:47 +0000250 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000251 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000252 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
253 Out<ELFT>::ProgramHeaders->getSize(),
254 Target->PageSize);
255 Out<ELFT>::ElfHeader->setVA(MinVA);
256 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000257}
258
Rui Ueyama07320e42016-04-20 20:13:41 +0000259template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000260std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000261LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000262 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000263
264 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000265 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
266 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000267
268 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000269 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000270 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000271 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000272
273 switch (Cmd.Type) {
274 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000275 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000276 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000277 break;
278 case PT_DYNAMIC:
279 if (isOutputDynamic<ELFT>()) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000280 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::Dynamic->getFlags());
281 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000282 }
283 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000284 case PT_GNU_EH_FRAME:
285 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rui Ueyamaadca2452016-07-23 14:18:48 +0000286 Phdr.H.p_flags = toPhdrFlags(Out<ELFT>::EhFrameHdr->getFlags());
287 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000288 }
289 break;
290 }
291 }
292
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000293 PhdrEntry<ELFT> *Load = nullptr;
294 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000295 for (OutputSectionBase<ELFT> *Sec : Sections) {
296 if (!(Sec->getFlags() & SHF_ALLOC))
297 break;
298
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000299 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000300 if (!PhdrIds.empty()) {
301 // Assign headers specified by linker script
302 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000303 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000304 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000305 Ret[Id].H.p_flags |= toPhdrFlags(Sec->getFlags());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000306 }
307 } else {
308 // If we have no load segment or flags've changed then we want new load
309 // segment.
310 uintX_t NewFlags = toPhdrFlags(Sec->getFlags());
311 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000312 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000313 Flags = NewFlags;
314 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000315 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000316 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000317 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000318 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000319}
320
321template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000322ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000323 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
324 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
325 if (Cmd->Name == Name)
326 return Cmd->Filler;
327 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000328}
329
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000330// Returns the index of the given section name in linker script
331// SECTIONS commands. Sections are laid out as the same order as they
332// were in the script. If a given name did not appear in the script,
333// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000334template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000335 int I = 0;
336 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
337 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
338 if (Cmd->Name == Name)
339 return I;
340 ++I;
341 }
342 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000343}
344
345// A compartor to sort output sections. Returns -1 or 1 if
346// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000347template <class ELFT>
348int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000349 int I = getSectionIndex(A);
350 int J = getSectionIndex(B);
351 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000352 return 0;
353 return I < J ? -1 : 1;
354}
355
George Rimar076fe152016-07-21 06:43:01 +0000356template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000357 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
358 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
359 if (!Cmd || Cmd->Name == ".")
360 continue;
361
Davide Italiano8ab41082016-07-23 22:09:04 +0000362 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Davide Italiano373a5332016-07-25 00:25:18 +0000363 // The semantic of PROVIDE is that of introducing a symbol only if
364 // it's not defined and there's at least a reference to it.
365 if ((!B && !Cmd->Provide) || (B && B->isUndefined()))
Eugene Levianta31c91b2016-07-22 07:38:40 +0000366 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
367 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
368 else
369 // Symbol already exists in symbol table. If it is provided
370 // then we can't override its value.
371 Cmd->Ignore = Cmd->Provide;
372 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000373}
374
Eugene Leviantbbe38602016-07-19 09:25:43 +0000375template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
376 return !Opt.PhdrsCommands.empty();
377}
378
379// Returns indices of ELF headers containing specific section, identified
380// by Name. Each index is a zero based number of ELF header listed within
381// PHDRS {} script block.
382template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000383std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000384 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
385 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000386 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000387 continue;
388
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000389 std::vector<size_t> Ret;
390 for (StringRef PhdrName : Cmd->Phdrs)
391 Ret.push_back(getPhdrIndex(PhdrName));
392 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000393 }
George Rimar31d842f2016-07-20 16:43:03 +0000394 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000395}
396
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000397template <class ELFT>
398size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
399 size_t I = 0;
400 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
401 if (Cmd.Name == PhdrName)
402 return I;
403 ++I;
404 }
405 error("section header '" + PhdrName + "' is not listed in PHDRS");
406 return 0;
407}
408
Rui Ueyama07320e42016-04-20 20:13:41 +0000409class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000410 typedef void (ScriptParser::*Handler)();
411
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000412public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000413 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000414
Rui Ueyama4a465392016-04-22 22:59:24 +0000415 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000416
417private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000418 void addFile(StringRef Path);
419
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000420 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000421 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000422 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000423 void readGroup();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000424 void readKeep(OutputSectionCommand *Cmd);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000425 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000426 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000427 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000428 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000429 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000430 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000431 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000432 void readSections();
433
Rui Ueyama113cdec2016-07-24 23:05:57 +0000434 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000435 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000436 std::vector<StringRef> readOutputSectionPhdrs();
437 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000438 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000439 void readAlign(OutputSectionCommand *Cmd);
Rui Ueyama708019c2016-07-24 18:19:40 +0000440
441 Expr readExpr();
442 Expr readExpr1(Expr Lhs, int MinPrec);
443 Expr readPrimary();
444 Expr readTernary(Expr Cond);
445 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000446
George Rimarc3794e52016-02-24 09:21:47 +0000447 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000448 ScriptConfiguration &Opt = *ScriptConfig;
449 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000450 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000451};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000452
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000453const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000454 {"ENTRY", &ScriptParser::readEntry},
455 {"EXTERN", &ScriptParser::readExtern},
456 {"GROUP", &ScriptParser::readGroup},
457 {"INCLUDE", &ScriptParser::readInclude},
458 {"INPUT", &ScriptParser::readGroup},
459 {"OUTPUT", &ScriptParser::readOutput},
460 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
461 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000462 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000463 {"SEARCH_DIR", &ScriptParser::readSearchDir},
464 {"SECTIONS", &ScriptParser::readSections},
465 {";", &ScriptParser::readNothing}};
466
Rui Ueyama717677a2016-02-11 21:17:59 +0000467void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000468 while (!atEOF()) {
469 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000470 if (Handler Fn = Cmd.lookup(Tok))
471 (this->*Fn)();
472 else
George Rimar57610422016-03-11 14:43:02 +0000473 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000474 }
475}
476
Rui Ueyama717677a2016-02-11 21:17:59 +0000477void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000478 if (IsUnderSysroot && S.startswith("/")) {
479 SmallString<128> Path;
480 (Config->Sysroot + S).toStringRef(Path);
481 if (sys::fs::exists(Path)) {
482 Driver->addFile(Saver.save(Path.str()));
483 return;
484 }
485 }
486
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000487 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000488 Driver->addFile(S);
489 } else if (S.startswith("=")) {
490 if (Config->Sysroot.empty())
491 Driver->addFile(S.substr(1));
492 else
493 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
494 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000495 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000496 } else if (sys::fs::exists(S)) {
497 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000498 } else {
499 std::string Path = findFromSearchPaths(S);
500 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000501 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000502 else
503 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000504 }
505}
506
Rui Ueyama717677a2016-02-11 21:17:59 +0000507void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000508 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000509 bool Orig = Config->AsNeeded;
510 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000511 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000512 StringRef Tok = next();
513 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000514 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000515 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000516 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000517 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000518}
519
Rui Ueyama717677a2016-02-11 21:17:59 +0000520void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000521 // -e <symbol> takes predecence over ENTRY(<symbol>).
522 expect("(");
523 StringRef Tok = next();
524 if (Config->Entry.empty())
525 Config->Entry = Tok;
526 expect(")");
527}
528
Rui Ueyama717677a2016-02-11 21:17:59 +0000529void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000530 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000531 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000532 StringRef Tok = next();
533 if (Tok == ")")
534 return;
535 Config->Undefined.push_back(Tok);
536 }
537}
538
Rui Ueyama717677a2016-02-11 21:17:59 +0000539void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000540 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000541 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000542 StringRef Tok = next();
543 if (Tok == ")")
544 return;
545 if (Tok == "AS_NEEDED") {
546 readAsNeeded();
547 continue;
548 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000549 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000550 }
551}
552
Rui Ueyama717677a2016-02-11 21:17:59 +0000553void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000554 StringRef Tok = next();
555 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000556 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000557 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000558 return;
559 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000560 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000561 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
562 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000563 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000564}
565
Rui Ueyama717677a2016-02-11 21:17:59 +0000566void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000567 // -o <file> takes predecence over OUTPUT(<file>).
568 expect("(");
569 StringRef Tok = next();
570 if (Config->OutputFile.empty())
571 Config->OutputFile = Tok;
572 expect(")");
573}
574
Rui Ueyama717677a2016-02-11 21:17:59 +0000575void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000576 // Error checking only for now.
577 expect("(");
578 next();
579 expect(")");
580}
581
Rui Ueyama717677a2016-02-11 21:17:59 +0000582void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000583 // Error checking only for now.
584 expect("(");
585 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000586 StringRef Tok = next();
587 if (Tok == ")")
588 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000589 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000590 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000591 return;
592 }
Davide Italiano6836c612015-10-12 21:08:41 +0000593 next();
594 expect(",");
595 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000596 expect(")");
597}
598
Eugene Leviantbbe38602016-07-19 09:25:43 +0000599void ScriptParser::readPhdrs() {
600 expect("{");
601 while (!Error && !skip("}")) {
602 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000603 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000604 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
605
606 PhdrCmd.Type = readPhdrType();
607 do {
608 Tok = next();
609 if (Tok == ";")
610 break;
611 if (Tok == "FILEHDR")
612 PhdrCmd.HasFilehdr = true;
613 else if (Tok == "PHDRS")
614 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000615 else if (Tok == "FLAGS") {
616 expect("(");
617 next().getAsInteger(0, PhdrCmd.Flags);
618 expect(")");
619 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000620 setError("unexpected header attribute: " + Tok);
621 } while (!Error);
622 }
623}
624
Rui Ueyama717677a2016-02-11 21:17:59 +0000625void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000626 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000627 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000628 expect(")");
629}
630
Rui Ueyama717677a2016-02-11 21:17:59 +0000631void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000632 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000633 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000634 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000635 StringRef Tok = next();
636 if (peek() == "=") {
637 readAssignment(Tok);
638 expect(";");
639 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000640 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000641 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000642 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000643 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000644 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000645 }
George Rimar652852c2016-04-16 10:10:32 +0000646 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000647}
648
Rui Ueyama708019c2016-07-24 18:19:40 +0000649static int precedence(StringRef Op) {
650 return StringSwitch<int>(Op)
651 .Case("*", 4)
652 .Case("/", 4)
653 .Case("+", 3)
654 .Case("-", 3)
655 .Case("<", 2)
656 .Case(">", 2)
657 .Case(">=", 2)
658 .Case("<=", 2)
659 .Case("==", 2)
660 .Case("!=", 2)
661 .Case("&", 1)
662 .Default(-1);
663}
664
Davide Italiano0ed42b02016-07-25 21:47:13 +0000665void ScriptParser::readKeep(OutputSectionCommand *Cmd) {
666 expect("(");
667 expect("*");
668 expect("(");
669 auto *InCmd = new InputSectionDescription();
670 Cmd->Commands.emplace_back(InCmd);
671 while (!Error && !skip(")")) {
672 Opt.KeptSections.push_back(peek());
673 InCmd->Patterns.push_back(next());
674 }
675 expect(")");
676}
677
George Rimar630c6172016-07-26 18:06:29 +0000678void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
679 expect("(");
680 Cmd->AlignExpr = readExpr();
681 expect(")");
682}
683
Eugene Levianteda81a12016-07-12 06:39:48 +0000684void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000685 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
686 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000687
688 // Read an address expression.
689 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
690 if (peek() != ":")
691 Cmd->AddrExpr = readExpr();
692
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000693 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000694
George Rimar630c6172016-07-26 18:06:29 +0000695 if (skip("ALIGN"))
696 readAlign(Cmd);
697
Davide Italiano246f6812016-07-22 03:36:24 +0000698 // Parse constraints.
699 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000700 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000701 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000702 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000703 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000704
Rui Ueyama025d59b2016-02-02 20:27:59 +0000705 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000706 StringRef Tok = next();
707 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000708 auto *InCmd = new InputSectionDescription();
709 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000710 expect("(");
711 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000712 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000713 } else if (Tok == "KEEP") {
Davide Italiano0ed42b02016-07-25 21:47:13 +0000714 readKeep(Cmd);
Davide Italiano054a6792016-07-24 23:13:48 +0000715 } else if (Tok == "PROVIDE") {
716 readProvide(false);
717 } else if (Tok == "PROVIDE_HIDDEN") {
718 readProvide(true);
George Rimar481c2ce2016-02-23 07:47:54 +0000719 } else {
George Rimar777f9632016-03-12 08:31:34 +0000720 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000721 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000722 }
George Rimar076fe152016-07-21 06:43:01 +0000723 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000724
George Rimare2ee72b2016-02-26 14:48:31 +0000725 StringRef Tok = peek();
726 if (Tok.startswith("=")) {
727 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000728 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000729 return;
730 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000731 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000732 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000733 next();
734 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000735}
736
Eugene Levianta31c91b2016-07-22 07:38:40 +0000737void ScriptParser::readProvide(bool Hidden) {
738 expect("(");
Rui Ueyama113cdec2016-07-24 23:05:57 +0000739 if (SymbolAssignment *Assignment = readAssignment(next())) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000740 Assignment->Provide = true;
741 Assignment->Hidden = Hidden;
742 }
743 expect(")");
744 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000745}
746
Rui Ueyama113cdec2016-07-24 23:05:57 +0000747SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000748 expect("=");
Rui Ueyama708019c2016-07-24 18:19:40 +0000749 Expr E = readExpr();
Rui Ueyama113cdec2016-07-24 23:05:57 +0000750 auto *Cmd = new SymbolAssignment(Name, E);
751 Opt.Commands.emplace_back(Cmd);
752 return Cmd;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000753}
754
Rui Ueyama708019c2016-07-24 18:19:40 +0000755// This is an operator-precedence parser to parse a linker
756// script expression.
757Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
Eugene Levianta31c91b2016-07-22 07:38:40 +0000758
George Rimara9c5a522016-07-26 18:18:58 +0000759static uint64_t getSymbolValue(StringRef S) {
760 switch (Config->EKind) {
761 case ELF32LEKind:
762 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
763 return B->getVA<ELF32LE>();
764 break;
765 case ELF32BEKind:
766 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
767 return B->getVA<ELF32BE>();
768 break;
769 case ELF64LEKind:
770 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
771 return B->getVA<ELF64LE>();
772 break;
773 case ELF64BEKind:
774 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
775 return B->getVA<ELF64BE>();
776 break;
777 }
778 error("symbol not found: " + S);
779 return 0;
780}
781
Rui Ueyama708019c2016-07-24 18:19:40 +0000782// This is a part of the operator-precedence parser. This function
783// assumes that the remaining token stream starts with an operator.
784Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
785 while (!atEOF() && !Error) {
786 // Read an operator and an expression.
787 StringRef Op1 = peek();
788 if (Op1 == "?")
789 return readTernary(Lhs);
790 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000791 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000792 next();
793 Expr Rhs = readPrimary();
794
795 // Evaluate the remaining part of the expression first if the
796 // next operator has greater precedence than the previous one.
797 // For example, if we have read "+" and "3", and if the next
798 // operator is "*", then we'll evaluate 3 * ... part first.
799 while (!atEOF()) {
800 StringRef Op2 = peek();
801 if (precedence(Op2) <= precedence(Op1))
802 break;
803 Rhs = readExpr1(Rhs, precedence(Op2));
804 }
805
806 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000807 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000808 return Lhs;
809}
810
811uint64_t static getConstant(StringRef S) {
812 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
813 return Target->PageSize;
814 error("unknown constant: " + S);
815 return 0;
816}
817
818Expr ScriptParser::readPrimary() {
819 StringRef Tok = next();
820
821 if (Tok == ".")
822 return [](uint64_t Dot) { return Dot; };
823
824 if (Tok == "(") {
825 Expr E = readExpr();
826 expect(")");
827 return E;
828 }
829
830 // Built-in functions are parsed here.
831 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
832 if (Tok == "ALIGN") {
833 expect("(");
834 Expr E = readExpr();
835 expect(")");
836 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
837 }
838 if (Tok == "CONSTANT") {
839 expect("(");
840 StringRef Tok = next();
841 expect(")");
842 return [=](uint64_t Dot) { return getConstant(Tok); };
843 }
844 if (Tok == "DATA_SEGMENT_ALIGN") {
845 expect("(");
846 Expr E = readExpr();
847 expect(",");
848 readExpr();
849 expect(")");
George Rimar4509a4f2016-07-26 17:01:18 +0000850 return [=](uint64_t Dot) -> uint64_t { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +0000851 }
852 if (Tok == "DATA_SEGMENT_END") {
853 expect("(");
854 expect(".");
855 expect(")");
856 return [](uint64_t Dot) { return Dot; };
857 }
George Rimar276b4e62016-07-26 17:58:44 +0000858 // GNU linkers implements more complicated logic to handle
859 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
860 // the next page boundary for simplicity.
861 if (Tok == "DATA_SEGMENT_RELRO_END") {
862 expect("(");
863 next();
864 expect(",");
865 readExpr();
866 expect(")");
867 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
868 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000869
George Rimara9c5a522016-07-26 18:18:58 +0000870 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +0000871 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +0000872 if (Tok.getAsInteger(0, V)) {
873 if (!isValidCIdentifier(Tok))
874 setError("malformed number: " + Tok);
875 return [=](uint64_t Dot) { return getSymbolValue(Tok); };
876 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000877 return [=](uint64_t Dot) { return V; };
878}
879
880Expr ScriptParser::readTernary(Expr Cond) {
881 next();
882 Expr L = readExpr();
883 expect(":");
884 Expr R = readExpr();
885 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
886}
887
888Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
889 if (Op == "*")
890 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
891 if (Op == "/") {
892 return [=](uint64_t Dot) -> uint64_t {
893 uint64_t RHS = R(Dot);
894 if (RHS == 0) {
895 error("division by zero");
896 return 0;
897 }
898 return L(Dot) / RHS;
899 };
900 }
901 if (Op == "+")
902 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
903 if (Op == "-")
904 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
905 if (Op == "<")
906 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
907 if (Op == ">")
908 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
909 if (Op == ">=")
910 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
911 if (Op == "<=")
912 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
913 if (Op == "==")
914 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
915 if (Op == "!=")
916 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
917 if (Op == "&")
918 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
919 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000920}
921
Eugene Leviantbbe38602016-07-19 09:25:43 +0000922std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
923 std::vector<StringRef> Phdrs;
924 while (!Error && peek().startswith(":")) {
925 StringRef Tok = next();
926 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
927 if (Tok.empty()) {
928 setError("section header name is empty");
929 break;
930 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000931 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000932 }
933 return Phdrs;
934}
935
936unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000937 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000938 unsigned Ret = StringSwitch<unsigned>(Tok)
939 .Case("PT_NULL", PT_NULL)
940 .Case("PT_LOAD", PT_LOAD)
941 .Case("PT_DYNAMIC", PT_DYNAMIC)
942 .Case("PT_INTERP", PT_INTERP)
943 .Case("PT_NOTE", PT_NOTE)
944 .Case("PT_SHLIB", PT_SHLIB)
945 .Case("PT_PHDR", PT_PHDR)
946 .Case("PT_TLS", PT_TLS)
947 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
948 .Case("PT_GNU_STACK", PT_GNU_STACK)
949 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
950 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000951
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000952 if (Ret == (unsigned)-1) {
953 setError("invalid program header type: " + Tok);
954 return PT_NULL;
955 }
956 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000957}
958
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000959static bool isUnderSysroot(StringRef Path) {
960 if (Config->Sysroot == "")
961 return false;
962 for (; !Path.empty(); Path = sys::path::parent_path(Path))
963 if (sys::fs::equivalent(Config->Sysroot, Path))
964 return true;
965 return false;
966}
967
Rui Ueyama07320e42016-04-20 20:13:41 +0000968// Entry point.
969void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000970 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000971 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000972}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000973
Rui Ueyama07320e42016-04-20 20:13:41 +0000974template class elf::LinkerScript<ELF32LE>;
975template class elf::LinkerScript<ELF32BE>;
976template class elf::LinkerScript<ELF64LE>;
977template class elf::LinkerScript<ELF64BE>;