blob: 57172ffdcfe6aa8289da76d5978d7ace9aa4dcf3 [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
Rui Ueyama808d13e2016-08-05 01:05:01 +0000216 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
217 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
218
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000219 removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
220 bool Writable = (S->getFlags() & SHF_WRITE);
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000221 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:
Rui Ueyama1034c9e2016-08-09 04:42:01 +0000321 if (Out<ELFT>::DynSymTab) {
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 Ueyamaa2acc932016-08-05 01:25:45 +0000570 while (!Error && !skip(")"))
571 addFile(next());
Rui Ueyama35da9b62015-10-11 20:59:12 +0000572 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000573}
574
Rui Ueyama717677a2016-02-11 21:17:59 +0000575void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000576 // -e <symbol> takes predecence over ENTRY(<symbol>).
577 expect("(");
578 StringRef Tok = next();
579 if (Config->Entry.empty())
580 Config->Entry = Tok;
581 expect(")");
582}
583
Rui Ueyama717677a2016-02-11 21:17:59 +0000584void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000585 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000586 while (!Error && !skip(")"))
587 Config->Undefined.push_back(next());
George Rimar83f406c2015-10-19 17:35:12 +0000588}
589
Rui Ueyama717677a2016-02-11 21:17:59 +0000590void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000591 expect("(");
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000592 while (!Error && !skip(")")) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000593 StringRef Tok = next();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000594 if (Tok == "AS_NEEDED")
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000595 readAsNeeded();
Rui Ueyamaa2acc932016-08-05 01:25:45 +0000596 else
597 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000598 }
599}
600
Rui Ueyama717677a2016-02-11 21:17:59 +0000601void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000602 StringRef Tok = next();
603 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000604 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000605 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000606 return;
607 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000608 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000609 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
610 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000611 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000612}
613
Rui Ueyama717677a2016-02-11 21:17:59 +0000614void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000615 // -o <file> takes predecence over OUTPUT(<file>).
616 expect("(");
617 StringRef Tok = next();
618 if (Config->OutputFile.empty())
619 Config->OutputFile = Tok;
620 expect(")");
621}
622
Rui Ueyama717677a2016-02-11 21:17:59 +0000623void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000624 // Error checking only for now.
625 expect("(");
626 next();
627 expect(")");
628}
629
Rui Ueyama717677a2016-02-11 21:17:59 +0000630void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000631 // Error checking only for now.
632 expect("(");
633 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000634 StringRef Tok = next();
635 if (Tok == ")")
636 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000637 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000638 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000639 return;
640 }
Davide Italiano6836c612015-10-12 21:08:41 +0000641 next();
642 expect(",");
643 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000644 expect(")");
645}
646
Eugene Leviantbbe38602016-07-19 09:25:43 +0000647void ScriptParser::readPhdrs() {
648 expect("{");
649 while (!Error && !skip("}")) {
650 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000651 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000652 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
653
654 PhdrCmd.Type = readPhdrType();
655 do {
656 Tok = next();
657 if (Tok == ";")
658 break;
659 if (Tok == "FILEHDR")
660 PhdrCmd.HasFilehdr = true;
661 else if (Tok == "PHDRS")
662 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000663 else if (Tok == "FLAGS") {
664 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000665 // Passing 0 for the value of dot is a bit of a hack. It means that
666 // we accept expressions like ".|1".
667 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000668 expect(")");
669 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000670 setError("unexpected header attribute: " + Tok);
671 } while (!Error);
672 }
673}
674
Rui Ueyama717677a2016-02-11 21:17:59 +0000675void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000676 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000677 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000678 expect(")");
679}
680
Rui Ueyama717677a2016-02-11 21:17:59 +0000681void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000682 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000683 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000684 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000685 StringRef Tok = next();
Rui Ueyama10416562016-08-04 02:03:27 +0000686 BaseCommand *Cmd;
George Rimar30835ea2016-07-28 21:08:56 +0000687 if (peek() == "=" || peek() == "+=") {
Rui Ueyama10416562016-08-04 02:03:27 +0000688 Cmd = readAssignment(Tok);
Rui Ueyama113cdec2016-07-24 23:05:57 +0000689 expect(";");
690 } else if (Tok == "PROVIDE") {
Rui Ueyama10416562016-08-04 02:03:27 +0000691 Cmd = readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000692 } else if (Tok == "PROVIDE_HIDDEN") {
Rui Ueyama10416562016-08-04 02:03:27 +0000693 Cmd = readProvide(true);
George Rimareefa7582016-08-04 09:29:31 +0000694 } else if (Tok == "ASSERT") {
695 Cmd = new AssertCommand(readAssert());
Rui Ueyama708019c2016-07-24 18:19:40 +0000696 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000697 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000698 }
Rui Ueyama10416562016-08-04 02:03:27 +0000699 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000700 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000701}
702
Rui Ueyama708019c2016-07-24 18:19:40 +0000703static int precedence(StringRef Op) {
704 return StringSwitch<int>(Op)
705 .Case("*", 4)
706 .Case("/", 4)
707 .Case("+", 3)
708 .Case("-", 3)
709 .Case("<", 2)
710 .Case(">", 2)
711 .Case(">=", 2)
712 .Case("<=", 2)
713 .Case("==", 2)
714 .Case("!=", 2)
715 .Case("&", 1)
716 .Default(-1);
717}
718
Rui Ueyama10416562016-08-04 02:03:27 +0000719std::vector<StringRef> ScriptParser::readInputFilePatterns() {
720 std::vector<StringRef> V;
721 while (!Error && !skip(")"))
722 V.push_back(next());
723 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000724}
725
Rui Ueyama742c3832016-08-04 22:27:00 +0000726SortKind ScriptParser::readSortKind() {
727 if (skip("SORT") || skip("SORT_BY_NAME"))
728 return SortByName;
729 if (skip("SORT_BY_ALIGNMENT"))
730 return SortByAlignment;
731 return SortNone;
732}
733
Rui Ueyama10416562016-08-04 02:03:27 +0000734InputSectionDescription *ScriptParser::readInputSectionRules() {
735 auto *Cmd = new InputSectionDescription;
736 Cmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000737 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000738
Rui Ueyama742c3832016-08-04 22:27:00 +0000739 // Read EXCLUDE_FILE().
Davide Italianoe7282792016-07-27 01:44:01 +0000740 if (skip("EXCLUDE_FILE")) {
741 expect("(");
742 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000743 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000744 }
George Rimar06598002016-07-28 21:51:30 +0000745
Rui Ueyama742c3832016-08-04 22:27:00 +0000746 // Read SORT().
747 if (SortKind K1 = readSortKind()) {
748 Cmd->SortOuter = K1;
George Rimar0702c4e2016-07-29 15:32:46 +0000749 expect("(");
Rui Ueyama742c3832016-08-04 22:27:00 +0000750 if (SortKind K2 = readSortKind()) {
751 Cmd->SortInner = K2;
George Rimar350ece42016-08-03 08:35:59 +0000752 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000753 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000754 expect(")");
755 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000756 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000757 }
George Rimar0702c4e2016-07-29 15:32:46 +0000758 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000759 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000760 }
George Rimar0702c4e2016-07-29 15:32:46 +0000761
Rui Ueyama10416562016-08-04 02:03:27 +0000762 Cmd->SectionPatterns = readInputFilePatterns();
763 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000764}
765
Rui Ueyama10416562016-08-04 02:03:27 +0000766InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000767 // Input section wildcard can be surrounded by KEEP.
768 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
769 if (skip("KEEP")) {
770 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000771 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000772 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000773 Opt.KeptSections.insert(Opt.KeptSections.end(),
774 Cmd->SectionPatterns.begin(),
775 Cmd->SectionPatterns.end());
776 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000777 }
Rui Ueyama10416562016-08-04 02:03:27 +0000778 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000779}
780
Rui Ueyama10416562016-08-04 02:03:27 +0000781Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000782 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000783 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000784 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000785 return E;
George Rimar630c6172016-07-26 18:06:29 +0000786}
787
George Rimar03fc0102016-07-28 07:18:23 +0000788void ScriptParser::readSort() {
789 expect("(");
790 expect("CONSTRUCTORS");
791 expect(")");
792}
793
George Rimareefa7582016-08-04 09:29:31 +0000794Expr ScriptParser::readAssert() {
795 expect("(");
796 Expr E = readExpr();
797 expect(",");
798 StringRef Msg = next();
799 expect(")");
800 return [=](uint64_t Dot) {
801 uint64_t V = E(Dot);
802 if (!V)
803 error(Msg);
804 return V;
805 };
806}
807
Rui Ueyama10416562016-08-04 02:03:27 +0000808OutputSectionCommand *
809ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000810 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000811
812 // Read an address expression.
813 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
814 if (peek() != ":")
815 Cmd->AddrExpr = readExpr();
816
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000817 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000818
George Rimar630c6172016-07-26 18:06:29 +0000819 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000820 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000821
Davide Italiano246f6812016-07-22 03:36:24 +0000822 // Parse constraints.
823 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000824 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000825 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000826 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000827 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000828
Rui Ueyama025d59b2016-02-02 20:27:59 +0000829 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000830 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000831 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000832 continue;
833 }
Rui Ueyamac1633182016-08-04 02:03:29 +0000834 if (skip("SORT")) {
George Rimar03fc0102016-07-28 07:18:23 +0000835 readSort();
Rui Ueyamac1633182016-08-04 02:03:29 +0000836 continue;
George Rimar481c2ce2016-02-23 07:47:54 +0000837 }
Rui Ueyamac1633182016-08-04 02:03:29 +0000838 setError("unknown command " + peek());
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000839 }
George Rimar076fe152016-07-21 06:43:01 +0000840 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000841 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000842 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000843}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000844
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000845std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000846 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000847 if (!Tok.startswith("="))
848 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000849 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000850
851 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000852 if (Tok.startswith("=0x"))
853 return parseHex(Tok.substr(3));
854
Rui Ueyama965827d2016-08-03 23:25:15 +0000855 // Read a decimal or octal value as a big-endian 32 bit value.
856 // Why do this? I don't know, but that's what gold does.
857 uint32_t V;
858 if (Tok.substr(1).getAsInteger(0, V)) {
859 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000860 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000861 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000862 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000863}
864
Rui Ueyama10416562016-08-04 02:03:27 +0000865SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000866 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000867 SymbolAssignment *Cmd = readAssignment(next());
868 Cmd->Provide = true;
869 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000870 expect(")");
871 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000872 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000873}
874
George Rimar30835ea2016-07-28 21:08:56 +0000875static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
876 if (S == ".")
877 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000878
George Rimara9c5a522016-07-26 18:18:58 +0000879 switch (Config->EKind) {
880 case ELF32LEKind:
881 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
882 return B->getVA<ELF32LE>();
883 break;
884 case ELF32BEKind:
885 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
886 return B->getVA<ELF32BE>();
887 break;
888 case ELF64LEKind:
889 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
890 return B->getVA<ELF64LE>();
891 break;
892 case ELF64BEKind:
893 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
894 return B->getVA<ELF64BE>();
895 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000896 default:
George Rimarb567b622016-07-26 18:46:13 +0000897 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000898 }
899 error("symbol not found: " + S);
900 return 0;
901}
902
George Rimar9e694502016-07-29 16:18:47 +0000903static uint64_t getSectionSize(StringRef Name) {
904 switch (Config->EKind) {
905 case ELF32LEKind:
906 return Script<ELF32LE>::X->getOutputSectionSize(Name);
907 case ELF32BEKind:
908 return Script<ELF32BE>::X->getOutputSectionSize(Name);
909 case ELF64LEKind:
910 return Script<ELF64LE>::X->getOutputSectionSize(Name);
911 case ELF64BEKind:
912 return Script<ELF64BE>::X->getOutputSectionSize(Name);
913 default:
914 llvm_unreachable("unsupported target");
915 }
916 return 0;
917}
918
George Rimar30835ea2016-07-28 21:08:56 +0000919SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
920 StringRef Op = next();
921 assert(Op == "=" || Op == "+=");
922 Expr E = readExpr();
923 if (Op == "+=")
924 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +0000925 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +0000926}
927
928// This is an operator-precedence parser to parse a linker
929// script expression.
930Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
931
Rui Ueyama36c1cd22016-08-05 01:04:59 +0000932static Expr combine(StringRef Op, Expr L, Expr R) {
933 if (Op == "*")
934 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
935 if (Op == "/") {
936 return [=](uint64_t Dot) -> uint64_t {
937 uint64_t RHS = R(Dot);
938 if (RHS == 0) {
939 error("division by zero");
940 return 0;
941 }
942 return L(Dot) / RHS;
943 };
944 }
945 if (Op == "+")
946 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
947 if (Op == "-")
948 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
949 if (Op == "<")
950 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
951 if (Op == ">")
952 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
953 if (Op == ">=")
954 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
955 if (Op == "<=")
956 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
957 if (Op == "==")
958 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
959 if (Op == "!=")
960 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
961 if (Op == "&")
962 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
963 llvm_unreachable("invalid operator");
964}
965
Rui Ueyama708019c2016-07-24 18:19:40 +0000966// This is a part of the operator-precedence parser. This function
967// assumes that the remaining token stream starts with an operator.
968Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
969 while (!atEOF() && !Error) {
970 // Read an operator and an expression.
971 StringRef Op1 = peek();
972 if (Op1 == "?")
973 return readTernary(Lhs);
974 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000975 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000976 next();
977 Expr Rhs = readPrimary();
978
979 // Evaluate the remaining part of the expression first if the
980 // next operator has greater precedence than the previous one.
981 // For example, if we have read "+" and "3", and if the next
982 // operator is "*", then we'll evaluate 3 * ... part first.
983 while (!atEOF()) {
984 StringRef Op2 = peek();
985 if (precedence(Op2) <= precedence(Op1))
986 break;
987 Rhs = readExpr1(Rhs, precedence(Op2));
988 }
989
990 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000991 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000992 return Lhs;
993}
994
995uint64_t static getConstant(StringRef S) {
996 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
997 return Target->PageSize;
998 error("unknown constant: " + S);
999 return 0;
1000}
1001
1002Expr ScriptParser::readPrimary() {
1003 StringRef Tok = next();
1004
Rui Ueyama708019c2016-07-24 18:19:40 +00001005 if (Tok == "(") {
1006 Expr E = readExpr();
1007 expect(")");
1008 return E;
1009 }
1010
1011 // Built-in functions are parsed here.
1012 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +00001013 if (Tok == "ASSERT")
1014 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +00001015 if (Tok == "ALIGN") {
1016 expect("(");
1017 Expr E = readExpr();
1018 expect(")");
1019 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
1020 }
1021 if (Tok == "CONSTANT") {
1022 expect("(");
1023 StringRef Tok = next();
1024 expect(")");
1025 return [=](uint64_t Dot) { return getConstant(Tok); };
1026 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001027 if (Tok == "SEGMENT_START") {
1028 expect("(");
1029 next();
1030 expect(",");
1031 uint64_t Val;
1032 next().getAsInteger(0, Val);
1033 expect(")");
1034 return [=](uint64_t Dot) { return Val; };
1035 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001036 if (Tok == "DATA_SEGMENT_ALIGN") {
1037 expect("(");
1038 Expr E = readExpr();
1039 expect(",");
1040 readExpr();
1041 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001042 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001043 }
1044 if (Tok == "DATA_SEGMENT_END") {
1045 expect("(");
1046 expect(".");
1047 expect(")");
1048 return [](uint64_t Dot) { return Dot; };
1049 }
George Rimar276b4e62016-07-26 17:58:44 +00001050 // GNU linkers implements more complicated logic to handle
1051 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1052 // the next page boundary for simplicity.
1053 if (Tok == "DATA_SEGMENT_RELRO_END") {
1054 expect("(");
1055 next();
1056 expect(",");
1057 readExpr();
1058 expect(")");
1059 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1060 }
George Rimar9e694502016-07-29 16:18:47 +00001061 if (Tok == "SIZEOF") {
1062 expect("(");
1063 StringRef Name = next();
1064 expect(")");
1065 return [=](uint64_t Dot) { return getSectionSize(Name); };
1066 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001067
George Rimara9c5a522016-07-26 18:18:58 +00001068 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001069 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001070 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001071 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001072 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001073 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001074 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001075 return [=](uint64_t Dot) { return V; };
1076}
1077
1078Expr ScriptParser::readTernary(Expr Cond) {
1079 next();
1080 Expr L = readExpr();
1081 expect(":");
1082 Expr R = readExpr();
1083 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1084}
1085
Eugene Leviantbbe38602016-07-19 09:25:43 +00001086std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1087 std::vector<StringRef> Phdrs;
1088 while (!Error && peek().startswith(":")) {
1089 StringRef Tok = next();
1090 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1091 if (Tok.empty()) {
1092 setError("section header name is empty");
1093 break;
1094 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001095 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001096 }
1097 return Phdrs;
1098}
1099
1100unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001101 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001102 unsigned Ret = StringSwitch<unsigned>(Tok)
1103 .Case("PT_NULL", PT_NULL)
1104 .Case("PT_LOAD", PT_LOAD)
1105 .Case("PT_DYNAMIC", PT_DYNAMIC)
1106 .Case("PT_INTERP", PT_INTERP)
1107 .Case("PT_NOTE", PT_NOTE)
1108 .Case("PT_SHLIB", PT_SHLIB)
1109 .Case("PT_PHDR", PT_PHDR)
1110 .Case("PT_TLS", PT_TLS)
1111 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1112 .Case("PT_GNU_STACK", PT_GNU_STACK)
1113 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1114 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001115
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001116 if (Ret == (unsigned)-1) {
1117 setError("invalid program header type: " + Tok);
1118 return PT_NULL;
1119 }
1120 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001121}
1122
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001123static bool isUnderSysroot(StringRef Path) {
1124 if (Config->Sysroot == "")
1125 return false;
1126 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1127 if (sys::fs::equivalent(Config->Sysroot, Path))
1128 return true;
1129 return false;
1130}
1131
Rui Ueyama07320e42016-04-20 20:13:41 +00001132// Entry point.
1133void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001134 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001135 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001136}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001137
Rui Ueyama07320e42016-04-20 20:13:41 +00001138template class elf::LinkerScript<ELF32LE>;
1139template class elf::LinkerScript<ELF32BE>;
1140template class elf::LinkerScript<ELF64LE>;
1141template class elf::LinkerScript<ELF64BE>;