blob: a2f611a1d492d0a0871407bfc097c02237d06c25 [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
George Rimareefa7582016-08-04 09:29:31 +000058bool AssertCommand::classof(const BaseCommand *C) {
59 return C->Kind == AssertKind;
60}
61
Rui Ueyama36a153c2016-07-23 14:09:58 +000062template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000063 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000064}
65
Rui Ueyama07320e42016-04-20 20:13:41 +000066template <class ELFT>
67bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000068 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000069 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000070 return true;
71 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000072}
73
Rui Ueyama63dc6502016-07-25 22:41:42 +000074static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
75 for (StringRef Pat : Patterns)
76 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +000077 return true;
78 return false;
79}
80
George Rimareaee2af2016-07-29 15:07:11 +000081// Create a vector of (<output section name>, <input section description>).
Rui Ueyama6b274812016-07-25 22:51:07 +000082template <class ELFT>
Davide Italianoe7282792016-07-27 01:44:01 +000083std::vector<std::pair<StringRef, const InputSectionDescription *>>
Rui Ueyama6b274812016-07-25 22:51:07 +000084LinkerScript<ELFT>::getSectionMap() {
Davide Italianoe7282792016-07-27 01:44:01 +000085 std::vector<std::pair<StringRef, const InputSectionDescription *>> Ret;
Rui Ueyama6b274812016-07-25 22:51:07 +000086
87 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
88 if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get()))
89 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands)
90 if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get()))
Davide Italianoe7282792016-07-27 01:44:01 +000091 Ret.emplace_back(Cmd1->Name, Cmd2);
Rui Ueyama6b274812016-07-25 22:51:07 +000092
93 return Ret;
94}
95
George Rimar06598002016-07-28 21:51:30 +000096static bool fileMatches(const InputSectionDescription *Desc,
97 StringRef Filename) {
98 if (!globMatch(Desc->FilePattern, Filename))
99 return false;
100 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
101}
102
Rui Ueyama6b274812016-07-25 22:51:07 +0000103// Returns input sections filtered by given glob patterns.
104template <class ELFT>
105std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000106LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000107 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000108 std::vector<InputSectionBase<ELFT> *> Ret;
109 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000110 Symtab<ELFT>::X->getObjectFiles()) {
111 if (fileMatches(I, sys::path::filename(F->getName())))
112 for (InputSectionBase<ELFT> *S : F->getSections())
113 if (!isDiscarded(S) && !S->OutSec &&
114 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000115 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000116 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000117
118 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000119 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000120
Rui Ueyama6b274812016-07-25 22:51:07 +0000121 return Ret;
122}
123
George Rimarc3cb8842016-07-29 15:12:48 +0000124// Add input section to output section. If there is no output section yet,
125// then create it and add to output section list.
126template <class ELFT>
127static void addSection(OutputSectionFactory<ELFT> &Factory,
128 std::vector<OutputSectionBase<ELFT> *> &Out,
129 InputSectionBase<ELFT> *C, StringRef Name) {
130 OutputSectionBase<ELFT> *Sec;
131 bool IsNew;
132 std::tie(Sec, IsNew) = Factory.create(C, Name);
133 if (IsNew)
134 Out.push_back(Sec);
135 Sec->addSection(C);
136}
137
Rui Ueyama742c3832016-08-04 22:27:00 +0000138template <class ELFT>
139static bool compareName(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
140 return A->getSectionName() < B->getSectionName();
141}
George Rimar350ece42016-08-03 08:35:59 +0000142
Rui Ueyama742c3832016-08-04 22:27:00 +0000143template <class ELFT>
144static bool compareAlignment(InputSectionBase<ELFT> *A,
145 InputSectionBase<ELFT> *B) {
146 // ">" is not a mistake. Larger alignments are placed before smaller
147 // alignments in order to reduce the amount of padding necessary.
148 // This is compatible with GNU.
149 return A->Alignment > B->Alignment;
150}
George Rimar350ece42016-08-03 08:35:59 +0000151
Rui Ueyama742c3832016-08-04 22:27:00 +0000152template <class ELFT>
153static std::function<bool(InputSectionBase<ELFT> *, InputSectionBase<ELFT> *)>
154getComparator(SortKind K) {
155 if (K == SortByName)
156 return compareName<ELFT>;
157 return compareAlignment<ELFT>;
158}
George Rimar0702c4e2016-07-29 15:32:46 +0000159
160template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000161void LinkerScript<ELFT>::createSections(
George Rimar9e694502016-07-29 16:18:47 +0000162 OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000163 for (auto &P : getSectionMap()) {
164 StringRef OutputName = P.first;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000165 const InputSectionDescription *Cmd = P.second;
166 std::vector<InputSectionBase<ELFT> *> Sections = getInputSections(Cmd);
167
168 if (OutputName == "/DISCARD/") {
169 for (InputSectionBase<ELFT> *S : Sections) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000170 S->Live = false;
171 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000172 }
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000173 continue;
George Rimareea31142016-07-21 14:26:59 +0000174 }
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000175
Rui Ueyama742c3832016-08-04 22:27:00 +0000176 if (Cmd->SortInner)
George Rimar350ece42016-08-03 08:35:59 +0000177 std::stable_sort(Sections.begin(), Sections.end(),
Rui Ueyama742c3832016-08-04 22:27:00 +0000178 getComparator<ELFT>(Cmd->SortInner));
179 if (Cmd->SortOuter)
180 std::stable_sort(Sections.begin(), Sections.end(),
181 getComparator<ELFT>(Cmd->SortOuter));
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000182
George Rimar0702c4e2016-07-29 15:32:46 +0000183 for (InputSectionBase<ELFT> *S : Sections)
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000184 addSection(Factory, *OutputSections, S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000185 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000186
187 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000188 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
189 Symtab<ELFT>::X->getObjectFiles())
190 for (InputSectionBase<ELFT> *S : F->getSections())
191 if (!isDiscarded(S) && !S->OutSec)
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000192 addSection(Factory, *OutputSections, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000193
Rui Ueyama3c291e12016-07-25 21:30:00 +0000194 // Remove from the output all the sections which did not meet
195 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000196 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000197}
198
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000199template <class R, class T>
200static inline void removeElementsIf(R &Range, const T &Pred) {
201 Range.erase(std::remove_if(Range.begin(), Range.end(), Pred), Range.end());
202}
203
Rui Ueyama3c291e12016-07-25 21:30:00 +0000204// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000205template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000206 // In this loop, we remove output sections if they don't satisfy
207 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000208 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
209 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
210 if (!Cmd || Cmd->Name == "/DISCARD/")
211 continue;
212
George Rimarbfc4a4b2016-07-26 10:47:09 +0000213 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000214 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000215
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000216 removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
217 bool Writable = (S->getFlags() & SHF_WRITE);
218 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
219 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
220
221 return S->getName() == Cmd->Name &&
222 ((RO && Writable) || (RW && !Writable));
George Rimarbfc4a4b2016-07-26 10:47:09 +0000223 });
Rui Ueyama3c291e12016-07-25 21:30:00 +0000224 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000225}
226
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000227template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
228 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
George Rimar652852c2016-04-16 10:10:32 +0000229 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000230 // are not explicitly placed into the output file by the linker script.
231 // We place orphan sections at end of file.
232 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000233 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000234 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000235 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000236 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000237 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000238 }
George Rimar652852c2016-04-16 10:10:32 +0000239
Rui Ueyama7c18c282016-04-18 21:00:40 +0000240 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000241 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000242 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000243 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000244
George Rimar076fe152016-07-21 06:43:01 +0000245 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
246 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000247 if (Cmd->Name == ".") {
248 Dot = Cmd->Expression(Dot);
249 } else if (Cmd->Sym) {
250 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
251 }
George Rimar652852c2016-04-16 10:10:32 +0000252 continue;
253 }
254
George Rimareefa7582016-08-04 09:29:31 +0000255 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
256 Cmd->Expression(Dot);
257 continue;
258 }
259
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000260 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000261 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000262 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000263 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000264 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000265 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000266 continue;
George Rimar652852c2016-04-16 10:10:32 +0000267
George Rimar58e5c4d2016-07-25 08:29:46 +0000268 if (Cmd->AddrExpr)
269 Dot = Cmd->AddrExpr(Dot);
270
George Rimar630c6172016-07-26 18:06:29 +0000271 if (Cmd->AlignExpr)
272 Sec->updateAlignment(Cmd->AlignExpr(Dot));
273
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000274 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
275 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000276 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000277 Sec->setVA(TVA);
278 ThreadBssOffset = TVA - Dot + Sec->getSize();
279 continue;
280 }
George Rimar652852c2016-04-16 10:10:32 +0000281
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000282 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000283 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000284 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000285 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000286 Dot += Sec->getSize();
287 continue;
288 }
George Rimar652852c2016-04-16 10:10:32 +0000289 }
290 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000291
Rafael Espindola64c32d62016-07-07 14:28:47 +0000292 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000293 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000294 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
295 Out<ELFT>::ProgramHeaders->getSize(),
296 Target->PageSize);
297 Out<ELFT>::ElfHeader->setVA(MinVA);
298 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000299}
300
Rui Ueyama07320e42016-04-20 20:13:41 +0000301template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000302std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
303 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000304 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000305
306 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000307 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
308 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000309
310 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000311 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000312 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000313 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000314
315 switch (Cmd.Type) {
316 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000317 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000318 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000319 break;
320 case PT_DYNAMIC:
321 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000322 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000323 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000324 }
325 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000326 case PT_GNU_EH_FRAME:
327 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000328 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000329 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000330 }
331 break;
332 }
333 }
334
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000335 PhdrEntry<ELFT> *Load = nullptr;
336 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000337 for (OutputSectionBase<ELFT> *Sec : Sections) {
338 if (!(Sec->getFlags() & SHF_ALLOC))
339 break;
340
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000341 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000342 if (!PhdrIds.empty()) {
343 // Assign headers specified by linker script
344 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000345 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000346 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000347 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000348 }
349 } else {
350 // If we have no load segment or flags've changed then we want new load
351 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000352 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000353 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000354 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000355 Flags = NewFlags;
356 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000357 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000358 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000359 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000360 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000361}
362
363template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000364ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000365 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
366 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
367 if (Cmd->Name == Name)
368 return Cmd->Filler;
369 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000370}
371
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000372// Returns the index of the given section name in linker script
373// SECTIONS commands. Sections are laid out as the same order as they
374// were in the script. If a given name did not appear in the script,
375// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000376template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000377 int I = 0;
378 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
379 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
380 if (Cmd->Name == Name)
381 return I;
382 ++I;
383 }
384 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000385}
386
387// A compartor to sort output sections. Returns -1 or 1 if
388// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000389template <class ELFT>
390int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000391 int I = getSectionIndex(A);
392 int J = getSectionIndex(B);
393 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000394 return 0;
395 return I < J ? -1 : 1;
396}
397
Rui Ueyama8d083e62016-07-29 05:48:39 +0000398// Add symbols defined by linker scripts.
George Rimar076fe152016-07-21 06:43:01 +0000399template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000400 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
401 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
402 if (!Cmd || Cmd->Name == ".")
403 continue;
404
Rui Ueyama8d083e62016-07-29 05:48:39 +0000405 // If a symbol was in PROVIDE(), define it only when it is an
406 // undefined symbol.
Davide Italiano8ab41082016-07-23 22:09:04 +0000407 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000408 if (Cmd->Provide && !(B && B->isUndefined()))
409 continue;
410
411 // Define an absolute symbol. The symbol value will be assigned later.
412 // (At this point, we don't know the final address yet.)
413 Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
414 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
415 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
416 Cmd->Sym = Sym->body();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000417 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000418}
419
Eugene Leviantbbe38602016-07-19 09:25:43 +0000420template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
421 return !Opt.PhdrsCommands.empty();
422}
423
George Rimar9e694502016-07-29 16:18:47 +0000424template <class ELFT>
425typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
426 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
427 if (Sec->getName() == Name)
428 return Sec->getSize();
429 error("undefined section " + Name);
430 return 0;
431}
432
Eugene Leviantbbe38602016-07-19 09:25:43 +0000433// Returns indices of ELF headers containing specific section, identified
434// by Name. Each index is a zero based number of ELF header listed within
435// PHDRS {} script block.
436template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000437std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000438 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
439 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000440 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000441 continue;
442
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000443 std::vector<size_t> Ret;
444 for (StringRef PhdrName : Cmd->Phdrs)
445 Ret.push_back(getPhdrIndex(PhdrName));
446 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000447 }
George Rimar31d842f2016-07-20 16:43:03 +0000448 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000449}
450
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000451template <class ELFT>
452size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
453 size_t I = 0;
454 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
455 if (Cmd.Name == PhdrName)
456 return I;
457 ++I;
458 }
459 error("section header '" + PhdrName + "' is not listed in PHDRS");
460 return 0;
461}
462
Rui Ueyama07320e42016-04-20 20:13:41 +0000463class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000464 typedef void (ScriptParser::*Handler)();
465
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000466public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000467 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000468
Rui Ueyama4a465392016-04-22 22:59:24 +0000469 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000470
471private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000472 void addFile(StringRef Path);
473
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000474 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000475 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000476 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000477 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000478 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000479 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000480 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000481 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000482 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000483 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000484 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000485 void readSections();
486
Rui Ueyama113cdec2016-07-24 23:05:57 +0000487 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000488 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000489 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000490 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000491 InputSectionDescription *readInputSectionDescription();
492 std::vector<StringRef> readInputFilePatterns();
493 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000494 unsigned readPhdrType();
Rui Ueyama742c3832016-08-04 22:27:00 +0000495 SortKind readSortKind();
Rui Ueyama10416562016-08-04 02:03:27 +0000496 SymbolAssignment *readProvide(bool Hidden);
497 Expr readAlign();
George Rimar03fc0102016-07-28 07:18:23 +0000498 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000499 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000500
501 Expr readExpr();
502 Expr readExpr1(Expr Lhs, int MinPrec);
503 Expr readPrimary();
504 Expr readTernary(Expr Cond);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000505
George Rimarc3794e52016-02-24 09:21:47 +0000506 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000507 ScriptConfiguration &Opt = *ScriptConfig;
508 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000509 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000510};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000511
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000512const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000513 {"ENTRY", &ScriptParser::readEntry},
514 {"EXTERN", &ScriptParser::readExtern},
515 {"GROUP", &ScriptParser::readGroup},
516 {"INCLUDE", &ScriptParser::readInclude},
517 {"INPUT", &ScriptParser::readGroup},
518 {"OUTPUT", &ScriptParser::readOutput},
519 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
520 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000521 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000522 {"SEARCH_DIR", &ScriptParser::readSearchDir},
523 {"SECTIONS", &ScriptParser::readSections},
524 {";", &ScriptParser::readNothing}};
525
Rui Ueyama717677a2016-02-11 21:17:59 +0000526void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000527 while (!atEOF()) {
528 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000529 if (Handler Fn = Cmd.lookup(Tok))
530 (this->*Fn)();
531 else
George Rimar57610422016-03-11 14:43:02 +0000532 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000533 }
534}
535
Rui Ueyama717677a2016-02-11 21:17:59 +0000536void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000537 if (IsUnderSysroot && S.startswith("/")) {
538 SmallString<128> Path;
539 (Config->Sysroot + S).toStringRef(Path);
540 if (sys::fs::exists(Path)) {
541 Driver->addFile(Saver.save(Path.str()));
542 return;
543 }
544 }
545
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000546 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000547 Driver->addFile(S);
548 } else if (S.startswith("=")) {
549 if (Config->Sysroot.empty())
550 Driver->addFile(S.substr(1));
551 else
552 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
553 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000554 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000555 } else if (sys::fs::exists(S)) {
556 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000557 } else {
558 std::string Path = findFromSearchPaths(S);
559 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000560 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000561 else
562 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000563 }
564}
565
Rui Ueyama717677a2016-02-11 21:17:59 +0000566void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000567 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000568 bool Orig = Config->AsNeeded;
569 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000570 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000571 StringRef Tok = next();
572 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000573 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000574 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000575 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000576 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000577}
578
Rui Ueyama717677a2016-02-11 21:17:59 +0000579void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000580 // -e <symbol> takes predecence over ENTRY(<symbol>).
581 expect("(");
582 StringRef Tok = next();
583 if (Config->Entry.empty())
584 Config->Entry = Tok;
585 expect(")");
586}
587
Rui Ueyama717677a2016-02-11 21:17:59 +0000588void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000589 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000590 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000591 StringRef Tok = next();
592 if (Tok == ")")
593 return;
594 Config->Undefined.push_back(Tok);
595 }
596}
597
Rui Ueyama717677a2016-02-11 21:17:59 +0000598void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000599 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000600 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000601 StringRef Tok = next();
602 if (Tok == ")")
603 return;
604 if (Tok == "AS_NEEDED") {
605 readAsNeeded();
606 continue;
607 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000608 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000609 }
610}
611
Rui Ueyama717677a2016-02-11 21:17:59 +0000612void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000613 StringRef Tok = next();
614 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000615 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000616 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000617 return;
618 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000619 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000620 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
621 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000622 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000623}
624
Rui Ueyama717677a2016-02-11 21:17:59 +0000625void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000626 // -o <file> takes predecence over OUTPUT(<file>).
627 expect("(");
628 StringRef Tok = next();
629 if (Config->OutputFile.empty())
630 Config->OutputFile = Tok;
631 expect(")");
632}
633
Rui Ueyama717677a2016-02-11 21:17:59 +0000634void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000635 // Error checking only for now.
636 expect("(");
637 next();
638 expect(")");
639}
640
Rui Ueyama717677a2016-02-11 21:17:59 +0000641void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000642 // Error checking only for now.
643 expect("(");
644 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000645 StringRef Tok = next();
646 if (Tok == ")")
647 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000648 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000649 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000650 return;
651 }
Davide Italiano6836c612015-10-12 21:08:41 +0000652 next();
653 expect(",");
654 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000655 expect(")");
656}
657
Eugene Leviantbbe38602016-07-19 09:25:43 +0000658void ScriptParser::readPhdrs() {
659 expect("{");
660 while (!Error && !skip("}")) {
661 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000662 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000663 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
664
665 PhdrCmd.Type = readPhdrType();
666 do {
667 Tok = next();
668 if (Tok == ";")
669 break;
670 if (Tok == "FILEHDR")
671 PhdrCmd.HasFilehdr = true;
672 else if (Tok == "PHDRS")
673 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000674 else if (Tok == "FLAGS") {
675 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000676 // Passing 0 for the value of dot is a bit of a hack. It means that
677 // we accept expressions like ".|1".
678 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000679 expect(")");
680 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000681 setError("unexpected header attribute: " + Tok);
682 } while (!Error);
683 }
684}
685
Rui Ueyama717677a2016-02-11 21:17:59 +0000686void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000687 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000688 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000689 expect(")");
690}
691
Rui Ueyama717677a2016-02-11 21:17:59 +0000692void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000693 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000694 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000695 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000696 StringRef Tok = next();
Rui Ueyama10416562016-08-04 02:03:27 +0000697 BaseCommand *Cmd;
George Rimar30835ea2016-07-28 21:08:56 +0000698 if (peek() == "=" || peek() == "+=") {
Rui Ueyama10416562016-08-04 02:03:27 +0000699 Cmd = readAssignment(Tok);
Rui Ueyama113cdec2016-07-24 23:05:57 +0000700 expect(";");
701 } else if (Tok == "PROVIDE") {
Rui Ueyama10416562016-08-04 02:03:27 +0000702 Cmd = readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000703 } else if (Tok == "PROVIDE_HIDDEN") {
Rui Ueyama10416562016-08-04 02:03:27 +0000704 Cmd = readProvide(true);
George Rimareefa7582016-08-04 09:29:31 +0000705 } else if (Tok == "ASSERT") {
706 Cmd = new AssertCommand(readAssert());
Rui Ueyama708019c2016-07-24 18:19:40 +0000707 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000708 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000709 }
Rui Ueyama10416562016-08-04 02:03:27 +0000710 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000711 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000712}
713
Rui Ueyama708019c2016-07-24 18:19:40 +0000714static int precedence(StringRef Op) {
715 return StringSwitch<int>(Op)
716 .Case("*", 4)
717 .Case("/", 4)
718 .Case("+", 3)
719 .Case("-", 3)
720 .Case("<", 2)
721 .Case(">", 2)
722 .Case(">=", 2)
723 .Case("<=", 2)
724 .Case("==", 2)
725 .Case("!=", 2)
726 .Case("&", 1)
727 .Default(-1);
728}
729
Rui Ueyama10416562016-08-04 02:03:27 +0000730std::vector<StringRef> ScriptParser::readInputFilePatterns() {
731 std::vector<StringRef> V;
732 while (!Error && !skip(")"))
733 V.push_back(next());
734 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000735}
736
Rui Ueyama742c3832016-08-04 22:27:00 +0000737SortKind ScriptParser::readSortKind() {
738 if (skip("SORT") || skip("SORT_BY_NAME"))
739 return SortByName;
740 if (skip("SORT_BY_ALIGNMENT"))
741 return SortByAlignment;
742 return SortNone;
743}
744
Rui Ueyama10416562016-08-04 02:03:27 +0000745InputSectionDescription *ScriptParser::readInputSectionRules() {
746 auto *Cmd = new InputSectionDescription;
747 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000748 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000749
Rui Ueyama742c3832016-08-04 22:27:00 +0000750 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000751 if (skip("EXCLUDE_FILE")) {
752 expect("(");
753 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000754 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000755 }
George Rimar06598002016-07-28 21:51:30 +0000756
Rui Ueyama742c3832016-08-04 22:27:00 +0000757 // Read SORT().
758 if (SortKind K1 = readSortKind()) {
759 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000760 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000761 if (SortKind K2 = readSortKind()) {
762 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000763 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000764 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000765 expect(")");
766 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000767 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000768 }
George Rimar0702c4e2016-07-29 15:32:46 +0000769 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000770 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000771 }
George Rimar0702c4e2016-07-29 15:32:46 +0000772
Rui Ueyama10416562016-08-04 02:03:27 +0000773 Cmd->SectionPatterns = readInputFilePatterns();
774 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000775}
776
Rui Ueyama10416562016-08-04 02:03:27 +0000777InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000778 // Input section wildcard can be surrounded by KEEP.
779 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
780 if (skip("KEEP")) {
781 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000782 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000783 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000784 Opt.KeptSections.insert(Opt.KeptSections.end(),
785 Cmd->SectionPatterns.begin(),
786 Cmd->SectionPatterns.end());
787 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000788 }
Rui Ueyama10416562016-08-04 02:03:27 +0000789 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000790}
791
Rui Ueyama10416562016-08-04 02:03:27 +0000792Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000793 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000794 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000795 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000796 return E;
George Rimar630c6172016-07-26 18:06:29 +0000797}
798
George Rimar03fc0102016-07-28 07:18:23 +0000799void ScriptParser::readSort() {
800 expect("(");
801 expect("CONSTRUCTORS");
802 expect(")");
803}
804
George Rimareefa7582016-08-04 09:29:31 +0000805Expr ScriptParser::readAssert() {
806 expect("(");
807 Expr E = readExpr();
808 expect(",");
809 StringRef Msg = next();
810 expect(")");
811 return [=](uint64_t Dot) {
812 uint64_t V = E(Dot);
813 if (!V)
814 error(Msg);
815 return V;
816 };
817}
818
Rui Ueyama10416562016-08-04 02:03:27 +0000819OutputSectionCommand *
820ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000821 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000822
823 // Read an address expression.
824 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
825 if (peek() != ":")
826 Cmd->AddrExpr = readExpr();
827
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000828 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000829
George Rimar630c6172016-07-26 18:06:29 +0000830 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000831 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000832
Davide Italiano246f6812016-07-22 03:36:24 +0000833 // Parse constraints.
834 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000835 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000836 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000837 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000838 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000839
Rui Ueyama025d59b2016-02-02 20:27:59 +0000840 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000841 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000842 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000843 continue;
844 }
Rui Ueyamac1633182016-08-04 02:03:29 +0000845 if (skip("SORT")) {
George Rimar03fc0102016-07-28 07:18:23 +0000846 readSort();
Rui Ueyamac1633182016-08-04 02:03:29 +0000847 continue;
George Rimar481c2ce2016-02-23 07:47:54 +0000848 }
Rui Ueyamac1633182016-08-04 02:03:29 +0000849 setError("unknown command " + peek());
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000850 }
George Rimar076fe152016-07-21 06:43:01 +0000851 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000852 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000853 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000854}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000855
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000856std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000857 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000858 if (!Tok.startswith("="))
859 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000860 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000861
862 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000863 if (Tok.startswith("=0x"))
864 return parseHex(Tok.substr(3));
865
Rui Ueyama965827d2016-08-03 23:25:15 +0000866 // Read a decimal or octal value as a big-endian 32 bit value.
867 // Why do this? I don't know, but that's what gold does.
868 uint32_t V;
869 if (Tok.substr(1).getAsInteger(0, V)) {
870 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000871 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000872 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000873 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000874}
875
Rui Ueyama10416562016-08-04 02:03:27 +0000876SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000877 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000878 SymbolAssignment *Cmd = readAssignment(next());
879 Cmd->Provide = true;
880 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000881 expect(")");
882 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000883 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000884}
885
George Rimar30835ea2016-07-28 21:08:56 +0000886static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
887 if (S == ".")
888 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000889
George Rimara9c5a522016-07-26 18:18:58 +0000890 switch (Config->EKind) {
891 case ELF32LEKind:
892 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
893 return B->getVA<ELF32LE>();
894 break;
895 case ELF32BEKind:
896 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
897 return B->getVA<ELF32BE>();
898 break;
899 case ELF64LEKind:
900 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
901 return B->getVA<ELF64LE>();
902 break;
903 case ELF64BEKind:
904 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
905 return B->getVA<ELF64BE>();
906 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000907 default:
George Rimarb567b622016-07-26 18:46:13 +0000908 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000909 }
910 error("symbol not found: " + S);
911 return 0;
912}
913
George Rimar9e694502016-07-29 16:18:47 +0000914static uint64_t getSectionSize(StringRef Name) {
915 switch (Config->EKind) {
916 case ELF32LEKind:
917 return Script<ELF32LE>::X->getOutputSectionSize(Name);
918 case ELF32BEKind:
919 return Script<ELF32BE>::X->getOutputSectionSize(Name);
920 case ELF64LEKind:
921 return Script<ELF64LE>::X->getOutputSectionSize(Name);
922 case ELF64BEKind:
923 return Script<ELF64BE>::X->getOutputSectionSize(Name);
924 default:
925 llvm_unreachable("unsupported target");
926 }
927 return 0;
928}
929
George Rimar30835ea2016-07-28 21:08:56 +0000930SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
931 StringRef Op = next();
932 assert(Op == "=" || Op == "+=");
933 Expr E = readExpr();
934 if (Op == "+=")
935 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +0000936 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +0000937}
938
939// This is an operator-precedence parser to parse a linker
940// script expression.
941Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
942
Rui Ueyama36c1cd22016-08-05 01:04:59 +0000943static Expr combine(StringRef Op, Expr L, Expr R) {
944 if (Op == "*")
945 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
946 if (Op == "/") {
947 return [=](uint64_t Dot) -> uint64_t {
948 uint64_t RHS = R(Dot);
949 if (RHS == 0) {
950 error("division by zero");
951 return 0;
952 }
953 return L(Dot) / RHS;
954 };
955 }
956 if (Op == "+")
957 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
958 if (Op == "-")
959 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
960 if (Op == "<")
961 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
962 if (Op == ">")
963 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
964 if (Op == ">=")
965 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
966 if (Op == "<=")
967 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
968 if (Op == "==")
969 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
970 if (Op == "!=")
971 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
972 if (Op == "&")
973 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
974 llvm_unreachable("invalid operator");
975}
976
Rui Ueyama708019c2016-07-24 18:19:40 +0000977// This is a part of the operator-precedence parser. This function
978// assumes that the remaining token stream starts with an operator.
979Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
980 while (!atEOF() && !Error) {
981 // Read an operator and an expression.
982 StringRef Op1 = peek();
983 if (Op1 == "?")
984 return readTernary(Lhs);
985 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000986 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000987 next();
988 Expr Rhs = readPrimary();
989
990 // Evaluate the remaining part of the expression first if the
991 // next operator has greater precedence than the previous one.
992 // For example, if we have read "+" and "3", and if the next
993 // operator is "*", then we'll evaluate 3 * ... part first.
994 while (!atEOF()) {
995 StringRef Op2 = peek();
996 if (precedence(Op2) <= precedence(Op1))
997 break;
998 Rhs = readExpr1(Rhs, precedence(Op2));
999 }
1000
1001 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +00001002 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001003 return Lhs;
1004}
1005
1006uint64_t static getConstant(StringRef S) {
1007 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
1008 return Target->PageSize;
1009 error("unknown constant: " + S);
1010 return 0;
1011}
1012
1013Expr ScriptParser::readPrimary() {
1014 StringRef Tok = next();
1015
Rui Ueyama708019c2016-07-24 18:19:40 +00001016 if (Tok == "(") {
1017 Expr E = readExpr();
1018 expect(")");
1019 return E;
1020 }
1021
1022 // Built-in functions are parsed here.
1023 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001024 if (Tok == "ASSERT")
1025 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001026 if (Tok == "ALIGN") {
1027 expect("(");
1028 Expr E = readExpr();
1029 expect(")");
1030 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1031 }
1032 if (Tok == "CONSTANT") {
1033 expect("(");
1034 StringRef Tok = next();
1035 expect(")");
1036 return [=](uint64_t Dot) { return getConstant(Tok); };
1037 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001038 if (Tok == "SEGMENT_START") {
1039 expect("(");
1040 next();
1041 expect(",");
1042 uint64_t Val;
1043 next().getAsInteger(0, Val);
1044 expect(")");
1045 return [=](uint64_t Dot) { return Val; };
1046 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001047 if (Tok == "DATA_SEGMENT_ALIGN") {
1048 expect("(");
1049 Expr E = readExpr();
1050 expect(",");
1051 readExpr();
1052 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001053 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001054 }
1055 if (Tok == "DATA_SEGMENT_END") {
1056 expect("(");
1057 expect(".");
1058 expect(")");
1059 return [](uint64_t Dot) { return Dot; };
1060 }
George Rimar276b4e62016-07-26 17:58:44 +00001061 // GNU linkers implements more complicated logic to handle
1062 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1063 // the next page boundary for simplicity.
1064 if (Tok == "DATA_SEGMENT_RELRO_END") {
1065 expect("(");
1066 next();
1067 expect(",");
1068 readExpr();
1069 expect(")");
1070 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1071 }
George Rimar9e694502016-07-29 16:18:47 +00001072 if (Tok == "SIZEOF") {
1073 expect("(");
1074 StringRef Name = next();
1075 expect(")");
1076 return [=](uint64_t Dot) { return getSectionSize(Name); };
1077 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001078
George Rimara9c5a522016-07-26 18:18:58 +00001079 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001080 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001081 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001082 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001083 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001084 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001085 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001086 return [=](uint64_t Dot) { return V; };
1087}
1088
1089Expr ScriptParser::readTernary(Expr Cond) {
1090 next();
1091 Expr L = readExpr();
1092 expect(":");
1093 Expr R = readExpr();
1094 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1095}
1096
Eugene Leviantbbe38602016-07-19 09:25:43 +00001097std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1098 std::vector<StringRef> Phdrs;
1099 while (!Error && peek().startswith(":")) {
1100 StringRef Tok = next();
1101 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1102 if (Tok.empty()) {
1103 setError("section header name is empty");
1104 break;
1105 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001106 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001107 }
1108 return Phdrs;
1109}
1110
1111unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001112 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001113 unsigned Ret = StringSwitch<unsigned>(Tok)
1114 .Case("PT_NULL", PT_NULL)
1115 .Case("PT_LOAD", PT_LOAD)
1116 .Case("PT_DYNAMIC", PT_DYNAMIC)
1117 .Case("PT_INTERP", PT_INTERP)
1118 .Case("PT_NOTE", PT_NOTE)
1119 .Case("PT_SHLIB", PT_SHLIB)
1120 .Case("PT_PHDR", PT_PHDR)
1121 .Case("PT_TLS", PT_TLS)
1122 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1123 .Case("PT_GNU_STACK", PT_GNU_STACK)
1124 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1125 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001126
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001127 if (Ret == (unsigned)-1) {
1128 setError("invalid program header type: " + Tok);
1129 return PT_NULL;
1130 }
1131 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001132}
1133
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001134static bool isUnderSysroot(StringRef Path) {
1135 if (Config->Sysroot == "")
1136 return false;
1137 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1138 if (sys::fs::equivalent(Config->Sysroot, Path))
1139 return true;
1140 return false;
1141}
1142
Rui Ueyama07320e42016-04-20 20:13:41 +00001143// Entry point.
1144void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001145 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001146 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001147}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001148
Rui Ueyama07320e42016-04-20 20:13:41 +00001149template class elf::LinkerScript<ELF32LE>;
1150template class elf::LinkerScript<ELF32BE>;
1151template class elf::LinkerScript<ELF64LE>;
1152template class elf::LinkerScript<ELF64BE>;