blob: 656e646a6998fb360911ec6583c0d6609fa7e691 [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
George Rimar076fe152016-07-21 06:43:01 +000046bool SymbolAssignment::classof(const BaseCommand *C) {
47 return C->Kind == AssignmentKind;
48}
49
50bool OutputSectionCommand::classof(const BaseCommand *C) {
51 return C->Kind == OutputSectionKind;
52}
53
George Rimareea31142016-07-21 14:26:59 +000054bool InputSectionDescription::classof(const BaseCommand *C) {
55 return C->Kind == InputSectionKind;
56}
57
Rui Ueyama36a153c2016-07-23 14:09:58 +000058template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000059 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000060}
61
Rui Ueyama07320e42016-04-20 20:13:41 +000062template <class ELFT>
63bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000064 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000065 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000066 return true;
67 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000068}
69
Rui Ueyama63dc6502016-07-25 22:41:42 +000070static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
71 for (StringRef Pat : Patterns)
72 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +000073 return true;
74 return false;
75}
76
George Rimareaee2af2016-07-29 15:07:11 +000077// Create a vector of (<output section name>, <input section description>).
Rui Ueyama6b274812016-07-25 22:51:07 +000078template <class ELFT>
Davide Italianoe7282792016-07-27 01:44:01 +000079std::vector<std::pair<StringRef, const InputSectionDescription *>>
Rui Ueyama6b274812016-07-25 22:51:07 +000080LinkerScript<ELFT>::getSectionMap() {
Davide Italianoe7282792016-07-27 01:44:01 +000081 std::vector<std::pair<StringRef, const InputSectionDescription *>> Ret;
Rui Ueyama6b274812016-07-25 22:51:07 +000082
83 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
84 if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get()))
85 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands)
86 if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get()))
Davide Italianoe7282792016-07-27 01:44:01 +000087 Ret.emplace_back(Cmd1->Name, Cmd2);
Rui Ueyama6b274812016-07-25 22:51:07 +000088
89 return Ret;
90}
91
George Rimar06598002016-07-28 21:51:30 +000092static bool fileMatches(const InputSectionDescription *Desc,
93 StringRef Filename) {
94 if (!globMatch(Desc->FilePattern, Filename))
95 return false;
96 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
97}
98
Rui Ueyama6b274812016-07-25 22:51:07 +000099// Returns input sections filtered by given glob patterns.
100template <class ELFT>
101std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000102LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000103 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000104 std::vector<InputSectionBase<ELFT> *> Ret;
105 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000106 Symtab<ELFT>::X->getObjectFiles()) {
107 if (fileMatches(I, sys::path::filename(F->getName())))
108 for (InputSectionBase<ELFT> *S : F->getSections())
109 if (!isDiscarded(S) && !S->OutSec &&
110 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000111 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000112 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000113
114 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000115 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000116
Rui Ueyama6b274812016-07-25 22:51:07 +0000117 return Ret;
118}
119
George Rimarc3cb8842016-07-29 15:12:48 +0000120// Add input section to output section. If there is no output section yet,
121// then create it and add to output section list.
122template <class ELFT>
123static void addSection(OutputSectionFactory<ELFT> &Factory,
124 std::vector<OutputSectionBase<ELFT> *> &Out,
125 InputSectionBase<ELFT> *C, StringRef Name) {
126 OutputSectionBase<ELFT> *Sec;
127 bool IsNew;
128 std::tie(Sec, IsNew) = Factory.create(C, Name);
129 if (IsNew)
130 Out.push_back(Sec);
131 Sec->addSection(C);
132}
133
George Rimar350ece42016-08-03 08:35:59 +0000134template <class ELFT> struct SectionsSorter {
135 SectionsSorter(SortKind Kind) : Kind(Kind) {}
136 bool operator()(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
137 int AlignmentCmp = A->Alignment - B->Alignment;
138 if (Kind == SortKind::Align || (Kind == SortKind::AlignName && AlignmentCmp != 0))
139 return AlignmentCmp < 0;
140
141 int NameCmp = A->getSectionName().compare(B->getSectionName());
142 if (Kind == SortKind::Name || (Kind == SortKind::NameAlign && NameCmp != 0))
143 return NameCmp < 0;
144
145 if (Kind == SortKind::NameAlign)
146 return AlignmentCmp < 0;
147 if (Kind == SortKind::AlignName)
148 return NameCmp < 0;
149
150 llvm_unreachable("unknown section sort kind in predicate");
151 return false;
152 }
153 SortKind Kind;
154};
George Rimar0702c4e2016-07-29 15:32:46 +0000155
156template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000157void LinkerScript<ELFT>::createSections(
158 std::vector<OutputSectionBase<ELFT> *> *Out,
159 OutputSectionFactory<ELFT> &Factory) {
160 OutputSections = Out;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000161
Rui Ueyama6b274812016-07-25 22:51:07 +0000162 for (auto &P : getSectionMap()) {
George Rimar0702c4e2016-07-29 15:32:46 +0000163 std::vector<InputSectionBase<ELFT> *> Sections;
Rui Ueyama6b274812016-07-25 22:51:07 +0000164 StringRef OutputName = P.first;
Davide Italianoe7282792016-07-27 01:44:01 +0000165 const InputSectionDescription *I = P.second;
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000166 for (InputSectionBase<ELFT> *S : getInputSections(I)) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000167 if (OutputName == "/DISCARD/") {
168 S->Live = false;
169 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000170 continue;
George Rimareea31142016-07-21 14:26:59 +0000171 }
George Rimar0702c4e2016-07-29 15:32:46 +0000172 Sections.push_back(S);
George Rimareea31142016-07-21 14:26:59 +0000173 }
George Rimar350ece42016-08-03 08:35:59 +0000174 if (I->Sort != SortKind::None)
175 std::stable_sort(Sections.begin(), Sections.end(),
176 SectionsSorter<ELFT>(I->Sort));
George Rimar0702c4e2016-07-29 15:32:46 +0000177 for (InputSectionBase<ELFT> *S : Sections)
George Rimar9e694502016-07-29 16:18:47 +0000178 addSection(Factory, *Out, S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000179 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000180
181 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000182 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
183 Symtab<ELFT>::X->getObjectFiles())
184 for (InputSectionBase<ELFT> *S : F->getSections())
185 if (!isDiscarded(S) && !S->OutSec)
George Rimar9e694502016-07-29 16:18:47 +0000186 addSection(Factory, *Out, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000187
Rui Ueyama3c291e12016-07-25 21:30:00 +0000188 // Remove from the output all the sections which did not meet
189 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000190 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000191}
192
193// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000194template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000195 // In this loop, we remove output sections if they don't satisfy
196 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000197 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
198 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
199 if (!Cmd || Cmd->Name == "/DISCARD/")
200 continue;
201
George Rimarbfc4a4b2016-07-26 10:47:09 +0000202 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000203 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000204
George Rimar9e694502016-07-29 16:18:47 +0000205 auto It = llvm::find_if(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
George Rimarbfc4a4b2016-07-26 10:47:09 +0000206 return S->getName() == Cmd->Name;
207 });
George Rimar9e694502016-07-29 16:18:47 +0000208 if (It == OutputSections->end())
George Rimarbfc4a4b2016-07-26 10:47:09 +0000209 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000210
211 OutputSectionBase<ELFT> *Sec = *It;
212 bool Writable = (Sec->getFlags() & SHF_WRITE);
213 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
214 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
215
Rui Ueyamaed942712016-07-29 06:21:06 +0000216 if ((RO && Writable) || (RW && !Writable))
George Rimar9e694502016-07-29 16:18:47 +0000217 OutputSections->erase(It);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000218 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000219}
220
Nico Weber2e367722016-08-03 14:37:57 +0000221template <class ELFT>
222void LinkerScript<ELFT>::assignAddresses(
223 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000224 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000225 // are not explicitly placed into the output file by the linker script.
226 // We place orphan sections at end of file.
227 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000228 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000229 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000230 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000231 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000232 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000233 }
George Rimar652852c2016-04-16 10:10:32 +0000234
Rui Ueyama7c18c282016-04-18 21:00:40 +0000235 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000236 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000237 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000238 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000239
George Rimar076fe152016-07-21 06:43:01 +0000240 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
241 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000242 if (Cmd->Name == ".") {
243 Dot = Cmd->Expression(Dot);
244 } else if (Cmd->Sym) {
245 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
246 }
George Rimar652852c2016-04-16 10:10:32 +0000247 continue;
248 }
249
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000250 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000251 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000252 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000253 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000254 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000255 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000256 continue;
George Rimar652852c2016-04-16 10:10:32 +0000257
George Rimar58e5c4d2016-07-25 08:29:46 +0000258 if (Cmd->AddrExpr)
259 Dot = Cmd->AddrExpr(Dot);
260
George Rimar630c6172016-07-26 18:06:29 +0000261 if (Cmd->AlignExpr)
262 Sec->updateAlignment(Cmd->AlignExpr(Dot));
263
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000264 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
265 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000266 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000267 Sec->setVA(TVA);
268 ThreadBssOffset = TVA - Dot + Sec->getSize();
269 continue;
270 }
George Rimar652852c2016-04-16 10:10:32 +0000271
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000272 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000273 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000274 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000275 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000276 Dot += Sec->getSize();
277 continue;
278 }
George Rimar652852c2016-04-16 10:10:32 +0000279 }
280 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000281
Rafael Espindola64c32d62016-07-07 14:28:47 +0000282 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000283 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000284 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
285 Out<ELFT>::ProgramHeaders->getSize(),
286 Target->PageSize);
287 Out<ELFT>::ElfHeader->setVA(MinVA);
288 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000289}
290
Rui Ueyama07320e42016-04-20 20:13:41 +0000291template <class ELFT>
Nico Weber2e367722016-08-03 14:37:57 +0000292std::vector<PhdrEntry<ELFT>>
293LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000294 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000295
296 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000297 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
298 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000299
300 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000301 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000302 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000303 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000304
305 switch (Cmd.Type) {
306 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000307 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000308 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000309 break;
310 case PT_DYNAMIC:
311 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000312 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000313 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000314 }
315 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000316 case PT_GNU_EH_FRAME:
317 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000318 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000319 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000320 }
321 break;
322 }
323 }
324
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000325 PhdrEntry<ELFT> *Load = nullptr;
326 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000327 for (OutputSectionBase<ELFT> *Sec : Sections) {
328 if (!(Sec->getFlags() & SHF_ALLOC))
329 break;
330
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000331 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000332 if (!PhdrIds.empty()) {
333 // Assign headers specified by linker script
334 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000335 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000336 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000337 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000338 }
339 } else {
340 // If we have no load segment or flags've changed then we want new load
341 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000342 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000343 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000344 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000345 Flags = NewFlags;
346 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000347 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000348 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000349 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000350 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000351}
352
353template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000354ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000355 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
356 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
357 if (Cmd->Name == Name)
358 return Cmd->Filler;
359 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000360}
361
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000362// Returns the index of the given section name in linker script
363// SECTIONS commands. Sections are laid out as the same order as they
364// were in the script. If a given name did not appear in the script,
365// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000366template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000367 int I = 0;
368 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
369 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
370 if (Cmd->Name == Name)
371 return I;
372 ++I;
373 }
374 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000375}
376
377// A compartor to sort output sections. Returns -1 or 1 if
378// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000379template <class ELFT>
380int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000381 int I = getSectionIndex(A);
382 int J = getSectionIndex(B);
383 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000384 return 0;
385 return I < J ? -1 : 1;
386}
387
Rui Ueyama8d083e62016-07-29 05:48:39 +0000388// Add symbols defined by linker scripts.
George Rimar076fe152016-07-21 06:43:01 +0000389template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000390 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
391 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
392 if (!Cmd || Cmd->Name == ".")
393 continue;
394
Rui Ueyama8d083e62016-07-29 05:48:39 +0000395 // If a symbol was in PROVIDE(), define it only when it is an
396 // undefined symbol.
Davide Italiano8ab41082016-07-23 22:09:04 +0000397 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000398 if (Cmd->Provide && !(B && B->isUndefined()))
399 continue;
400
401 // Define an absolute symbol. The symbol value will be assigned later.
402 // (At this point, we don't know the final address yet.)
403 Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
404 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
405 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
406 Cmd->Sym = Sym->body();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000407 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000408}
409
Eugene Leviantbbe38602016-07-19 09:25:43 +0000410template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
411 return !Opt.PhdrsCommands.empty();
412}
413
George Rimar9e694502016-07-29 16:18:47 +0000414template <class ELFT>
415typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
416 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
417 if (Sec->getName() == Name)
418 return Sec->getSize();
419 error("undefined section " + Name);
420 return 0;
421}
422
Eugene Leviantbbe38602016-07-19 09:25:43 +0000423// Returns indices of ELF headers containing specific section, identified
424// by Name. Each index is a zero based number of ELF header listed within
425// PHDRS {} script block.
426template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000427std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000428 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
429 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000430 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000431 continue;
432
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000433 std::vector<size_t> Ret;
434 for (StringRef PhdrName : Cmd->Phdrs)
435 Ret.push_back(getPhdrIndex(PhdrName));
436 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000437 }
George Rimar31d842f2016-07-20 16:43:03 +0000438 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000439}
440
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000441template <class ELFT>
442size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
443 size_t I = 0;
444 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
445 if (Cmd.Name == PhdrName)
446 return I;
447 ++I;
448 }
449 error("section header '" + PhdrName + "' is not listed in PHDRS");
450 return 0;
451}
452
Rui Ueyama07320e42016-04-20 20:13:41 +0000453class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000454 typedef void (ScriptParser::*Handler)();
455
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000456public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000457 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000458
Rui Ueyama4a465392016-04-22 22:59:24 +0000459 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000460
461private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000462 void addFile(StringRef Path);
463
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000464 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000465 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000466 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000467 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000468 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000469 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000470 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000471 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000472 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000473 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000474 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000475 void readSections();
476
Rui Ueyama113cdec2016-07-24 23:05:57 +0000477 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000478 void readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000479 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000480 std::vector<StringRef> readOutputSectionPhdrs();
George Rimar06598002016-07-28 21:51:30 +0000481 std::unique_ptr<InputSectionDescription> readInputSectionDescription();
George Rimar0702c4e2016-07-29 15:32:46 +0000482 void readInputFilePattern(InputSectionDescription *InCmd, bool Keep);
George Rimar06598002016-07-28 21:51:30 +0000483 void readInputSectionRules(InputSectionDescription *InCmd, bool Keep);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000484 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000485 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000486 void readAlign(OutputSectionCommand *Cmd);
George Rimar03fc0102016-07-28 07:18:23 +0000487 void readSort();
Rui Ueyama708019c2016-07-24 18:19:40 +0000488
489 Expr readExpr();
490 Expr readExpr1(Expr Lhs, int MinPrec);
491 Expr readPrimary();
492 Expr readTernary(Expr Cond);
493 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000494
George Rimarc3794e52016-02-24 09:21:47 +0000495 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000496 ScriptConfiguration &Opt = *ScriptConfig;
497 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000498 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000499};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000500
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000501const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000502 {"ENTRY", &ScriptParser::readEntry},
503 {"EXTERN", &ScriptParser::readExtern},
504 {"GROUP", &ScriptParser::readGroup},
505 {"INCLUDE", &ScriptParser::readInclude},
506 {"INPUT", &ScriptParser::readGroup},
507 {"OUTPUT", &ScriptParser::readOutput},
508 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
509 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000510 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000511 {"SEARCH_DIR", &ScriptParser::readSearchDir},
512 {"SECTIONS", &ScriptParser::readSections},
513 {";", &ScriptParser::readNothing}};
514
Rui Ueyama717677a2016-02-11 21:17:59 +0000515void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000516 while (!atEOF()) {
517 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000518 if (Handler Fn = Cmd.lookup(Tok))
519 (this->*Fn)();
520 else
George Rimar57610422016-03-11 14:43:02 +0000521 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000522 }
523}
524
Rui Ueyama717677a2016-02-11 21:17:59 +0000525void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000526 if (IsUnderSysroot && S.startswith("/")) {
527 SmallString<128> Path;
528 (Config->Sysroot + S).toStringRef(Path);
529 if (sys::fs::exists(Path)) {
530 Driver->addFile(Saver.save(Path.str()));
531 return;
532 }
533 }
534
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000535 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000536 Driver->addFile(S);
537 } else if (S.startswith("=")) {
538 if (Config->Sysroot.empty())
539 Driver->addFile(S.substr(1));
540 else
541 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
542 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000543 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000544 } else if (sys::fs::exists(S)) {
545 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000546 } else {
547 std::string Path = findFromSearchPaths(S);
548 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000549 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000550 else
551 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000552 }
553}
554
Rui Ueyama717677a2016-02-11 21:17:59 +0000555void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000556 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000557 bool Orig = Config->AsNeeded;
558 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000559 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000560 StringRef Tok = next();
561 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000562 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000563 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000564 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000565 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000566}
567
Rui Ueyama717677a2016-02-11 21:17:59 +0000568void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000569 // -e <symbol> takes predecence over ENTRY(<symbol>).
570 expect("(");
571 StringRef Tok = next();
572 if (Config->Entry.empty())
573 Config->Entry = Tok;
574 expect(")");
575}
576
Rui Ueyama717677a2016-02-11 21:17:59 +0000577void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000578 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000579 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000580 StringRef Tok = next();
581 if (Tok == ")")
582 return;
583 Config->Undefined.push_back(Tok);
584 }
585}
586
Rui Ueyama717677a2016-02-11 21:17:59 +0000587void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000588 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000589 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000590 StringRef Tok = next();
591 if (Tok == ")")
592 return;
593 if (Tok == "AS_NEEDED") {
594 readAsNeeded();
595 continue;
596 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000597 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();
George Rimar30835ea2016-07-28 21:08:56 +0000686 if (peek() == "=" || peek() == "+=") {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000687 readAssignment(Tok);
688 expect(";");
689 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000690 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000691 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000692 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000693 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000694 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000695 }
George Rimar652852c2016-04-16 10:10:32 +0000696 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000697}
698
Rui Ueyama708019c2016-07-24 18:19:40 +0000699static int precedence(StringRef Op) {
700 return StringSwitch<int>(Op)
701 .Case("*", 4)
702 .Case("/", 4)
703 .Case("+", 3)
704 .Case("-", 3)
705 .Case("<", 2)
706 .Case(">", 2)
707 .Case(">=", 2)
708 .Case("<=", 2)
709 .Case("==", 2)
710 .Case("!=", 2)
711 .Case("&", 1)
712 .Default(-1);
713}
714
George Rimar0702c4e2016-07-29 15:32:46 +0000715void ScriptParser::readInputFilePattern(InputSectionDescription *InCmd,
716 bool Keep) {
717 while (!Error && !skip(")")) {
718 if (Keep)
719 Opt.KeptSections.push_back(peek());
720 InCmd->SectionPatterns.push_back(next());
721 }
722}
723
724void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd,
725 bool Keep) {
George Rimar06598002016-07-28 21:51:30 +0000726 InCmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000727 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000728
Davide Italianoe7282792016-07-27 01:44:01 +0000729 if (skip("EXCLUDE_FILE")) {
730 expect("(");
731 while (!Error && !skip(")"))
732 InCmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000733 }
George Rimar06598002016-07-28 21:51:30 +0000734
George Rimar350ece42016-08-03 08:35:59 +0000735 if (skip("SORT") || skip("SORT_BY_NAME")) {
George Rimar0702c4e2016-07-29 15:32:46 +0000736 expect("(");
George Rimar350ece42016-08-03 08:35:59 +0000737 if (skip("SORT_BY_ALIGNMENT")) {
738 InCmd->Sort = SortKind::NameAlign;
739 expect("(");
740 readInputFilePattern(InCmd, Keep);
741 expect(")");
742 } else {
743 InCmd->Sort = SortKind::Name;
744 readInputFilePattern(InCmd, Keep);
745 }
746 expect(")");
747 return;
748 }
749
750 if (skip("SORT_BY_ALIGNMENT")) {
751 expect("(");
752 if (skip("SORT") || skip("SORT_BY_NAME")) {
753 InCmd->Sort = SortKind::AlignName;
754 expect("(");
755 readInputFilePattern(InCmd, Keep);
756 expect(")");
757 } else {
758 InCmd->Sort = SortKind::Align;
759 readInputFilePattern(InCmd, Keep);
760 }
George Rimar0702c4e2016-07-29 15:32:46 +0000761 expect(")");
762 return;
George Rimar06598002016-07-28 21:51:30 +0000763 }
George Rimar0702c4e2016-07-29 15:32:46 +0000764
765 readInputFilePattern(InCmd, Keep);
Davide Italianoe7282792016-07-27 01:44:01 +0000766}
767
George Rimar06598002016-07-28 21:51:30 +0000768std::unique_ptr<InputSectionDescription>
769ScriptParser::readInputSectionDescription() {
George Rimar352eac32016-07-28 22:10:50 +0000770 auto InCmd = llvm::make_unique<InputSectionDescription>();
George Rimar06598002016-07-28 21:51:30 +0000771
772 // Input section wildcard can be surrounded by KEEP.
773 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
774 if (skip("KEEP")) {
775 expect("(");
776 readInputSectionRules(InCmd.get(), true);
777 expect(")");
778 } else {
779 readInputSectionRules(InCmd.get(), false);
780 }
781
782 return InCmd;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000783}
784
George Rimar630c6172016-07-26 18:06:29 +0000785void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
786 expect("(");
787 Cmd->AlignExpr = readExpr();
788 expect(")");
789}
790
George Rimar03fc0102016-07-28 07:18:23 +0000791void ScriptParser::readSort() {
792 expect("(");
793 expect("CONSTRUCTORS");
794 expect(")");
795}
796
Eugene Levianteda81a12016-07-12 06:39:48 +0000797void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000798 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
799 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000800
801 // Read an address expression.
802 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
803 if (peek() != ":")
804 Cmd->AddrExpr = readExpr();
805
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000806 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000807
George Rimar630c6172016-07-26 18:06:29 +0000808 if (skip("ALIGN"))
809 readAlign(Cmd);
810
Davide Italiano246f6812016-07-22 03:36:24 +0000811 // Parse constraints.
812 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000813 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000814 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000815 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000816 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000817
Rui Ueyama025d59b2016-02-02 20:27:59 +0000818 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000819 if (peek().startswith("*") || peek() == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000820 Cmd->Commands.push_back(readInputSectionDescription());
821 continue;
822 }
823
George Rimar481c2ce2016-02-23 07:47:54 +0000824 StringRef Tok = next();
George Rimar06598002016-07-28 21:51:30 +0000825 if (Tok == "PROVIDE") {
Davide Italiano054a6792016-07-24 23:13:48 +0000826 readProvide(false);
827 } else if (Tok == "PROVIDE_HIDDEN") {
828 readProvide(true);
George Rimar03fc0102016-07-28 07:18:23 +0000829 } else if (Tok == "SORT") {
830 readSort();
George Rimar481c2ce2016-02-23 07:47:54 +0000831 } else {
George Rimar777f9632016-03-12 08:31:34 +0000832 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000833 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000834 }
George Rimar076fe152016-07-21 06:43:01 +0000835 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000836 Cmd->Filler = readOutputSectionFiller();
837}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000838
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000839std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000840 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000841 if (!Tok.startswith("="))
842 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000843 next();
844 if (Tok.startswith("=0x"))
845 return parseHex(Tok.substr(3));
846
847 // This must be a decimal.
848 unsigned int Value;
849 if (Tok.substr(1).getAsInteger(10, Value)) {
850 setError("filler should be a decimal/hexadecimal value");
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000851 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000852 }
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000853 if (Value > 255)
854 setError("only single bytes decimal are supported for the filler now");
855 return {static_cast<unsigned char>(Value)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000856}
857
Eugene Levianta31c91b2016-07-22 07:38:40 +0000858void ScriptParser::readProvide(bool Hidden) {
859 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000860 SymbolAssignment *Cmd = readAssignment(next());
861 Cmd->Provide = true;
862 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000863 expect(")");
864 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000865}
866
George Rimar30835ea2016-07-28 21:08:56 +0000867static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
868 if (S == ".")
869 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000870
George Rimara9c5a522016-07-26 18:18:58 +0000871 switch (Config->EKind) {
872 case ELF32LEKind:
873 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
874 return B->getVA<ELF32LE>();
875 break;
876 case ELF32BEKind:
877 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
878 return B->getVA<ELF32BE>();
879 break;
880 case ELF64LEKind:
881 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
882 return B->getVA<ELF64LE>();
883 break;
884 case ELF64BEKind:
885 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
886 return B->getVA<ELF64BE>();
887 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000888 default:
George Rimarb567b622016-07-26 18:46:13 +0000889 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000890 }
891 error("symbol not found: " + S);
892 return 0;
893}
894
George Rimar9e694502016-07-29 16:18:47 +0000895static uint64_t getSectionSize(StringRef Name) {
896 switch (Config->EKind) {
897 case ELF32LEKind:
898 return Script<ELF32LE>::X->getOutputSectionSize(Name);
899 case ELF32BEKind:
900 return Script<ELF32BE>::X->getOutputSectionSize(Name);
901 case ELF64LEKind:
902 return Script<ELF64LE>::X->getOutputSectionSize(Name);
903 case ELF64BEKind:
904 return Script<ELF64BE>::X->getOutputSectionSize(Name);
905 default:
906 llvm_unreachable("unsupported target");
907 }
908 return 0;
909}
910
George Rimar30835ea2016-07-28 21:08:56 +0000911SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
912 StringRef Op = next();
913 assert(Op == "=" || Op == "+=");
914 Expr E = readExpr();
915 if (Op == "+=")
916 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
917 auto *Cmd = new SymbolAssignment(Name, E);
918 Opt.Commands.emplace_back(Cmd);
919 return Cmd;
920}
921
922// This is an operator-precedence parser to parse a linker
923// script expression.
924Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
925
Rui Ueyama708019c2016-07-24 18:19:40 +0000926// This is a part of the operator-precedence parser. This function
927// assumes that the remaining token stream starts with an operator.
928Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
929 while (!atEOF() && !Error) {
930 // Read an operator and an expression.
931 StringRef Op1 = peek();
932 if (Op1 == "?")
933 return readTernary(Lhs);
934 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000935 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000936 next();
937 Expr Rhs = readPrimary();
938
939 // Evaluate the remaining part of the expression first if the
940 // next operator has greater precedence than the previous one.
941 // For example, if we have read "+" and "3", and if the next
942 // operator is "*", then we'll evaluate 3 * ... part first.
943 while (!atEOF()) {
944 StringRef Op2 = peek();
945 if (precedence(Op2) <= precedence(Op1))
946 break;
947 Rhs = readExpr1(Rhs, precedence(Op2));
948 }
949
950 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000951 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000952 return Lhs;
953}
954
955uint64_t static getConstant(StringRef S) {
956 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
957 return Target->PageSize;
958 error("unknown constant: " + S);
959 return 0;
960}
961
962Expr ScriptParser::readPrimary() {
963 StringRef Tok = next();
964
Rui Ueyama708019c2016-07-24 18:19:40 +0000965 if (Tok == "(") {
966 Expr E = readExpr();
967 expect(")");
968 return E;
969 }
970
971 // Built-in functions are parsed here.
972 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
973 if (Tok == "ALIGN") {
974 expect("(");
975 Expr E = readExpr();
976 expect(")");
977 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
978 }
979 if (Tok == "CONSTANT") {
980 expect("(");
981 StringRef Tok = next();
982 expect(")");
983 return [=](uint64_t Dot) { return getConstant(Tok); };
984 }
Rafael Espindola54c145c2016-07-28 18:16:24 +0000985 if (Tok == "SEGMENT_START") {
986 expect("(");
987 next();
988 expect(",");
989 uint64_t Val;
990 next().getAsInteger(0, Val);
991 expect(")");
992 return [=](uint64_t Dot) { return Val; };
993 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000994 if (Tok == "DATA_SEGMENT_ALIGN") {
995 expect("(");
996 Expr E = readExpr();
997 expect(",");
998 readExpr();
999 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001000 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001001 }
1002 if (Tok == "DATA_SEGMENT_END") {
1003 expect("(");
1004 expect(".");
1005 expect(")");
1006 return [](uint64_t Dot) { return Dot; };
1007 }
George Rimar276b4e62016-07-26 17:58:44 +00001008 // GNU linkers implements more complicated logic to handle
1009 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1010 // the next page boundary for simplicity.
1011 if (Tok == "DATA_SEGMENT_RELRO_END") {
1012 expect("(");
1013 next();
1014 expect(",");
1015 readExpr();
1016 expect(")");
1017 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1018 }
George Rimar9e694502016-07-29 16:18:47 +00001019 if (Tok == "SIZEOF") {
1020 expect("(");
1021 StringRef Name = next();
1022 expect(")");
1023 return [=](uint64_t Dot) { return getSectionSize(Name); };
1024 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001025
George Rimara9c5a522016-07-26 18:18:58 +00001026 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001027 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001028 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001029 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001030 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001031 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001032 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001033 return [=](uint64_t Dot) { return V; };
1034}
1035
1036Expr ScriptParser::readTernary(Expr Cond) {
1037 next();
1038 Expr L = readExpr();
1039 expect(":");
1040 Expr R = readExpr();
1041 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1042}
1043
1044Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
1045 if (Op == "*")
1046 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1047 if (Op == "/") {
1048 return [=](uint64_t Dot) -> uint64_t {
1049 uint64_t RHS = R(Dot);
1050 if (RHS == 0) {
1051 error("division by zero");
1052 return 0;
1053 }
1054 return L(Dot) / RHS;
1055 };
1056 }
1057 if (Op == "+")
1058 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1059 if (Op == "-")
1060 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1061 if (Op == "<")
1062 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1063 if (Op == ">")
1064 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1065 if (Op == ">=")
1066 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1067 if (Op == "<=")
1068 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1069 if (Op == "==")
1070 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1071 if (Op == "!=")
1072 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1073 if (Op == "&")
1074 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1075 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +00001076}
1077
Eugene Leviantbbe38602016-07-19 09:25:43 +00001078std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1079 std::vector<StringRef> Phdrs;
1080 while (!Error && peek().startswith(":")) {
1081 StringRef Tok = next();
1082 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1083 if (Tok.empty()) {
1084 setError("section header name is empty");
1085 break;
1086 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001087 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001088 }
1089 return Phdrs;
1090}
1091
1092unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001093 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001094 unsigned Ret = StringSwitch<unsigned>(Tok)
1095 .Case("PT_NULL", PT_NULL)
1096 .Case("PT_LOAD", PT_LOAD)
1097 .Case("PT_DYNAMIC", PT_DYNAMIC)
1098 .Case("PT_INTERP", PT_INTERP)
1099 .Case("PT_NOTE", PT_NOTE)
1100 .Case("PT_SHLIB", PT_SHLIB)
1101 .Case("PT_PHDR", PT_PHDR)
1102 .Case("PT_TLS", PT_TLS)
1103 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1104 .Case("PT_GNU_STACK", PT_GNU_STACK)
1105 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1106 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001107
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001108 if (Ret == (unsigned)-1) {
1109 setError("invalid program header type: " + Tok);
1110 return PT_NULL;
1111 }
1112 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001113}
1114
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001115static bool isUnderSysroot(StringRef Path) {
1116 if (Config->Sysroot == "")
1117 return false;
1118 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1119 if (sys::fs::equivalent(Config->Sysroot, Path))
1120 return true;
1121 return false;
1122}
1123
Rui Ueyama07320e42016-04-20 20:13:41 +00001124// Entry point.
1125void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001126 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001127 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001128}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001129
Rui Ueyama07320e42016-04-20 20:13:41 +00001130template class elf::LinkerScript<ELF32LE>;
1131template class elf::LinkerScript<ELF32BE>;
1132template class elf::LinkerScript<ELF64LE>;
1133template class elf::LinkerScript<ELF64BE>;