blob: b69c02aad4be2aa83a3833e2cd31bd2163f9bf91 [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
George Rimar350ece42016-08-03 08:35:59 +0000138template <class ELFT> struct SectionsSorter {
139 SectionsSorter(SortKind Kind) : Kind(Kind) {}
140 bool operator()(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
141 int AlignmentCmp = A->Alignment - B->Alignment;
142 if (Kind == SortKind::Align || (Kind == SortKind::AlignName && AlignmentCmp != 0))
George Rimar9e5386c2016-08-04 08:56:17 +0000143 return AlignmentCmp > 0;
George Rimar350ece42016-08-03 08:35:59 +0000144
145 int NameCmp = A->getSectionName().compare(B->getSectionName());
146 if (Kind == SortKind::Name || (Kind == SortKind::NameAlign && NameCmp != 0))
147 return NameCmp < 0;
148
149 if (Kind == SortKind::NameAlign)
George Rimar9e5386c2016-08-04 08:56:17 +0000150 return AlignmentCmp > 0;
George Rimar350ece42016-08-03 08:35:59 +0000151 if (Kind == SortKind::AlignName)
152 return NameCmp < 0;
153
154 llvm_unreachable("unknown section sort kind in predicate");
155 return false;
156 }
157 SortKind Kind;
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
176 if (Cmd->Sort != SortKind::None)
George Rimar350ece42016-08-03 08:35:59 +0000177 std::stable_sort(Sections.begin(), Sections.end(),
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000178 SectionsSorter<ELFT>(Cmd->Sort));
179
George Rimar0702c4e2016-07-29 15:32:46 +0000180 for (InputSectionBase<ELFT> *S : Sections)
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000181 addSection(Factory, *OutputSections, S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000182 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000183
184 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000185 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
186 Symtab<ELFT>::X->getObjectFiles())
187 for (InputSectionBase<ELFT> *S : F->getSections())
188 if (!isDiscarded(S) && !S->OutSec)
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000189 addSection(Factory, *OutputSections, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000190
Rui Ueyama3c291e12016-07-25 21:30:00 +0000191 // Remove from the output all the sections which did not meet
192 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000193 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000194}
195
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000196template <class R, class T>
197static inline void removeElementsIf(R &Range, const T &Pred) {
198 Range.erase(std::remove_if(Range.begin(), Range.end(), Pred), Range.end());
199}
200
Rui Ueyama3c291e12016-07-25 21:30:00 +0000201// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000202template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000203 // In this loop, we remove output sections if they don't satisfy
204 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000205 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
206 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
207 if (!Cmd || Cmd->Name == "/DISCARD/")
208 continue;
209
George Rimarbfc4a4b2016-07-26 10:47:09 +0000210 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000211 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000212
Eugene Leviantc7611fc2016-08-04 08:20:23 +0000213 removeElementsIf(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
214 bool Writable = (S->getFlags() & SHF_WRITE);
215 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
216 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
217
218 return S->getName() == Cmd->Name &&
219 ((RO && Writable) || (RW && !Writable));
George Rimarbfc4a4b2016-07-26 10:47:09 +0000220 });
Rui Ueyama3c291e12016-07-25 21:30:00 +0000221 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000222}
223
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000224template <class ELFT> void LinkerScript<ELFT>::assignAddresses() {
225 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
George Rimar652852c2016-04-16 10:10:32 +0000226 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000227 // are not explicitly placed into the output file by the linker script.
228 // We place orphan sections at end of file.
229 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000230 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000231 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000232 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000233 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000234 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000235 }
George Rimar652852c2016-04-16 10:10:32 +0000236
Rui Ueyama7c18c282016-04-18 21:00:40 +0000237 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000238 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000239 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000240 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000241
George Rimar076fe152016-07-21 06:43:01 +0000242 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
243 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000244 if (Cmd->Name == ".") {
245 Dot = Cmd->Expression(Dot);
246 } else if (Cmd->Sym) {
247 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
248 }
George Rimar652852c2016-04-16 10:10:32 +0000249 continue;
250 }
251
George Rimareefa7582016-08-04 09:29:31 +0000252 if (auto *Cmd = dyn_cast<AssertCommand>(Base.get())) {
253 Cmd->Expression(Dot);
254 continue;
255 }
256
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000257 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000258 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000259 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000260 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000261 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000262 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000263 continue;
George Rimar652852c2016-04-16 10:10:32 +0000264
George Rimar58e5c4d2016-07-25 08:29:46 +0000265 if (Cmd->AddrExpr)
266 Dot = Cmd->AddrExpr(Dot);
267
George Rimar630c6172016-07-26 18:06:29 +0000268 if (Cmd->AlignExpr)
269 Sec->updateAlignment(Cmd->AlignExpr(Dot));
270
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000271 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
272 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000273 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000274 Sec->setVA(TVA);
275 ThreadBssOffset = TVA - Dot + Sec->getSize();
276 continue;
277 }
George Rimar652852c2016-04-16 10:10:32 +0000278
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000279 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000280 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000281 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000282 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000283 Dot += Sec->getSize();
284 continue;
285 }
George Rimar652852c2016-04-16 10:10:32 +0000286 }
287 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000288
Rafael Espindola64c32d62016-07-07 14:28:47 +0000289 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000290 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000291 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
292 Out<ELFT>::ProgramHeaders->getSize(),
293 Target->PageSize);
294 Out<ELFT>::ElfHeader->setVA(MinVA);
295 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000296}
297
Rui Ueyama07320e42016-04-20 20:13:41 +0000298template <class ELFT>
Rafael Espindolaa4b41dc2016-08-04 12:13:05 +0000299std::vector<PhdrEntry<ELFT>> LinkerScript<ELFT>::createPhdrs() {
300 ArrayRef<OutputSectionBase<ELFT> *> Sections = *OutputSections;
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000301 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000302
303 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000304 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
305 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000306
307 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000308 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000309 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000310 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000311
312 switch (Cmd.Type) {
313 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000314 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000315 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000316 break;
317 case PT_DYNAMIC:
318 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000319 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000320 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000321 }
322 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000323 case PT_GNU_EH_FRAME:
324 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000325 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000326 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000327 }
328 break;
329 }
330 }
331
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000332 PhdrEntry<ELFT> *Load = nullptr;
333 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000334 for (OutputSectionBase<ELFT> *Sec : Sections) {
335 if (!(Sec->getFlags() & SHF_ALLOC))
336 break;
337
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000338 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000339 if (!PhdrIds.empty()) {
340 // Assign headers specified by linker script
341 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000342 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000343 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000344 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000345 }
346 } else {
347 // If we have no load segment or flags've changed then we want new load
348 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000349 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000350 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000351 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000352 Flags = NewFlags;
353 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000354 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000355 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000356 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000357 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000358}
359
360template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000361ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000362 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
363 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
364 if (Cmd->Name == Name)
365 return Cmd->Filler;
366 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000367}
368
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000369// Returns the index of the given section name in linker script
370// SECTIONS commands. Sections are laid out as the same order as they
371// were in the script. If a given name did not appear in the script,
372// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000373template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000374 int I = 0;
375 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
376 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
377 if (Cmd->Name == Name)
378 return I;
379 ++I;
380 }
381 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000382}
383
384// A compartor to sort output sections. Returns -1 or 1 if
385// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000386template <class ELFT>
387int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000388 int I = getSectionIndex(A);
389 int J = getSectionIndex(B);
390 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000391 return 0;
392 return I < J ? -1 : 1;
393}
394
Rui Ueyama8d083e62016-07-29 05:48:39 +0000395// Add symbols defined by linker scripts.
George Rimar076fe152016-07-21 06:43:01 +0000396template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000397 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
398 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
399 if (!Cmd || Cmd->Name == ".")
400 continue;
401
Rui Ueyama8d083e62016-07-29 05:48:39 +0000402 // If a symbol was in PROVIDE(), define it only when it is an
403 // undefined symbol.
Davide Italiano8ab41082016-07-23 22:09:04 +0000404 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000405 if (Cmd->Provide && !(B && B->isUndefined()))
406 continue;
407
408 // Define an absolute symbol. The symbol value will be assigned later.
409 // (At this point, we don't know the final address yet.)
410 Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
411 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
412 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
413 Cmd->Sym = Sym->body();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000414 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000415}
416
Eugene Leviantbbe38602016-07-19 09:25:43 +0000417template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
418 return !Opt.PhdrsCommands.empty();
419}
420
George Rimar9e694502016-07-29 16:18:47 +0000421template <class ELFT>
422typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
423 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
424 if (Sec->getName() == Name)
425 return Sec->getSize();
426 error("undefined section " + Name);
427 return 0;
428}
429
Eugene Leviantbbe38602016-07-19 09:25:43 +0000430// Returns indices of ELF headers containing specific section, identified
431// by Name. Each index is a zero based number of ELF header listed within
432// PHDRS {} script block.
433template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000434std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000435 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
436 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000437 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000438 continue;
439
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000440 std::vector<size_t> Ret;
441 for (StringRef PhdrName : Cmd->Phdrs)
442 Ret.push_back(getPhdrIndex(PhdrName));
443 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000444 }
George Rimar31d842f2016-07-20 16:43:03 +0000445 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000446}
447
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000448template <class ELFT>
449size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
450 size_t I = 0;
451 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
452 if (Cmd.Name == PhdrName)
453 return I;
454 ++I;
455 }
456 error("section header '" + PhdrName + "' is not listed in PHDRS");
457 return 0;
458}
459
Rui Ueyama07320e42016-04-20 20:13:41 +0000460class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000461 typedef void (ScriptParser::*Handler)();
462
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000463public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000464 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000465
Rui Ueyama4a465392016-04-22 22:59:24 +0000466 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000467
468private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000469 void addFile(StringRef Path);
470
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000471 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000472 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000473 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000474 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000475 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000476 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000477 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000478 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000479 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000480 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000481 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000482 void readSections();
483
Rui Ueyama113cdec2016-07-24 23:05:57 +0000484 SymbolAssignment *readAssignment(StringRef Name);
Rui Ueyama10416562016-08-04 02:03:27 +0000485 OutputSectionCommand *readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000486 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000487 std::vector<StringRef> readOutputSectionPhdrs();
Rui Ueyama10416562016-08-04 02:03:27 +0000488 InputSectionDescription *readInputSectionDescription();
489 std::vector<StringRef> readInputFilePatterns();
490 InputSectionDescription *readInputSectionRules();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000491 unsigned readPhdrType();
Rui Ueyama10416562016-08-04 02:03:27 +0000492 SymbolAssignment *readProvide(bool Hidden);
493 Expr readAlign();
George Rimar03fc0102016-07-28 07:18:23 +0000494 void readSort();
George Rimareefa7582016-08-04 09:29:31 +0000495 Expr readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000496
497 Expr readExpr();
498 Expr readExpr1(Expr Lhs, int MinPrec);
499 Expr readPrimary();
500 Expr readTernary(Expr Cond);
501 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000502
George Rimarc3794e52016-02-24 09:21:47 +0000503 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000504 ScriptConfiguration &Opt = *ScriptConfig;
505 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000506 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000507};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000508
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000509const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000510 {"ENTRY", &ScriptParser::readEntry},
511 {"EXTERN", &ScriptParser::readExtern},
512 {"GROUP", &ScriptParser::readGroup},
513 {"INCLUDE", &ScriptParser::readInclude},
514 {"INPUT", &ScriptParser::readGroup},
515 {"OUTPUT", &ScriptParser::readOutput},
516 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
517 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000518 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000519 {"SEARCH_DIR", &ScriptParser::readSearchDir},
520 {"SECTIONS", &ScriptParser::readSections},
521 {";", &ScriptParser::readNothing}};
522
Rui Ueyama717677a2016-02-11 21:17:59 +0000523void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000524 while (!atEOF()) {
525 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000526 if (Handler Fn = Cmd.lookup(Tok))
527 (this->*Fn)();
528 else
George Rimar57610422016-03-11 14:43:02 +0000529 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000530 }
531}
532
Rui Ueyama717677a2016-02-11 21:17:59 +0000533void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000534 if (IsUnderSysroot && S.startswith("/")) {
535 SmallString<128> Path;
536 (Config->Sysroot + S).toStringRef(Path);
537 if (sys::fs::exists(Path)) {
538 Driver->addFile(Saver.save(Path.str()));
539 return;
540 }
541 }
542
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000543 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000544 Driver->addFile(S);
545 } else if (S.startswith("=")) {
546 if (Config->Sysroot.empty())
547 Driver->addFile(S.substr(1));
548 else
549 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
550 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000551 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000552 } else if (sys::fs::exists(S)) {
553 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000554 } else {
555 std::string Path = findFromSearchPaths(S);
556 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000557 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000558 else
559 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000560 }
561}
562
Rui Ueyama717677a2016-02-11 21:17:59 +0000563void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000564 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000565 bool Orig = Config->AsNeeded;
566 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000567 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000568 StringRef Tok = next();
569 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000570 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000571 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000572 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000573 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000574}
575
Rui Ueyama717677a2016-02-11 21:17:59 +0000576void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000577 // -e <symbol> takes predecence over ENTRY(<symbol>).
578 expect("(");
579 StringRef Tok = next();
580 if (Config->Entry.empty())
581 Config->Entry = Tok;
582 expect(")");
583}
584
Rui Ueyama717677a2016-02-11 21:17:59 +0000585void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000586 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000587 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000588 StringRef Tok = next();
589 if (Tok == ")")
590 return;
591 Config->Undefined.push_back(Tok);
592 }
593}
594
Rui Ueyama717677a2016-02-11 21:17:59 +0000595void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000596 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000597 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000598 StringRef Tok = next();
599 if (Tok == ")")
600 return;
601 if (Tok == "AS_NEEDED") {
602 readAsNeeded();
603 continue;
604 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000605 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000606 }
607}
608
Rui Ueyama717677a2016-02-11 21:17:59 +0000609void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000610 StringRef Tok = next();
611 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000612 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000613 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000614 return;
615 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000616 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000617 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
618 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000619 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000620}
621
Rui Ueyama717677a2016-02-11 21:17:59 +0000622void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000623 // -o <file> takes predecence over OUTPUT(<file>).
624 expect("(");
625 StringRef Tok = next();
626 if (Config->OutputFile.empty())
627 Config->OutputFile = Tok;
628 expect(")");
629}
630
Rui Ueyama717677a2016-02-11 21:17:59 +0000631void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000632 // Error checking only for now.
633 expect("(");
634 next();
635 expect(")");
636}
637
Rui Ueyama717677a2016-02-11 21:17:59 +0000638void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000639 // Error checking only for now.
640 expect("(");
641 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000642 StringRef Tok = next();
643 if (Tok == ")")
644 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000645 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000646 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000647 return;
648 }
Davide Italiano6836c612015-10-12 21:08:41 +0000649 next();
650 expect(",");
651 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000652 expect(")");
653}
654
Eugene Leviantbbe38602016-07-19 09:25:43 +0000655void ScriptParser::readPhdrs() {
656 expect("{");
657 while (!Error && !skip("}")) {
658 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000659 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000660 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
661
662 PhdrCmd.Type = readPhdrType();
663 do {
664 Tok = next();
665 if (Tok == ";")
666 break;
667 if (Tok == "FILEHDR")
668 PhdrCmd.HasFilehdr = true;
669 else if (Tok == "PHDRS")
670 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000671 else if (Tok == "FLAGS") {
672 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000673 // Passing 0 for the value of dot is a bit of a hack. It means that
674 // we accept expressions like ".|1".
675 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000676 expect(")");
677 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000678 setError("unexpected header attribute: " + Tok);
679 } while (!Error);
680 }
681}
682
Rui Ueyama717677a2016-02-11 21:17:59 +0000683void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000684 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000685 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000686 expect(")");
687}
688
Rui Ueyama717677a2016-02-11 21:17:59 +0000689void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000690 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000691 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000692 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000693 StringRef Tok = next();
Rui Ueyama10416562016-08-04 02:03:27 +0000694 BaseCommand *Cmd;
George Rimar30835ea2016-07-28 21:08:56 +0000695 if (peek() == "=" || peek() == "+=") {
Rui Ueyama10416562016-08-04 02:03:27 +0000696 Cmd = readAssignment(Tok);
Rui Ueyama113cdec2016-07-24 23:05:57 +0000697 expect(";");
698 } else if (Tok == "PROVIDE") {
Rui Ueyama10416562016-08-04 02:03:27 +0000699 Cmd = readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000700 } else if (Tok == "PROVIDE_HIDDEN") {
Rui Ueyama10416562016-08-04 02:03:27 +0000701 Cmd = readProvide(true);
George Rimareefa7582016-08-04 09:29:31 +0000702 } else if (Tok == "ASSERT") {
703 Cmd = new AssertCommand(readAssert());
Rui Ueyama708019c2016-07-24 18:19:40 +0000704 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000705 Cmd = readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000706 }
Rui Ueyama10416562016-08-04 02:03:27 +0000707 Opt.Commands.emplace_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000708 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000709}
710
Rui Ueyama708019c2016-07-24 18:19:40 +0000711static int precedence(StringRef Op) {
712 return StringSwitch<int>(Op)
713 .Case("*", 4)
714 .Case("/", 4)
715 .Case("+", 3)
716 .Case("-", 3)
717 .Case("<", 2)
718 .Case(">", 2)
719 .Case(">=", 2)
720 .Case("<=", 2)
721 .Case("==", 2)
722 .Case("!=", 2)
723 .Case("&", 1)
724 .Default(-1);
725}
726
Rui Ueyama10416562016-08-04 02:03:27 +0000727std::vector<StringRef> ScriptParser::readInputFilePatterns() {
728 std::vector<StringRef> V;
729 while (!Error && !skip(")"))
730 V.push_back(next());
731 return V;
George Rimar0702c4e2016-07-29 15:32:46 +0000732}
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
Davide Italianoe7282792016-07-27 01:44:01 +0000739 if (skip("EXCLUDE_FILE")) {
740 expect("(");
741 while (!Error && !skip(")"))
Rui Ueyama10416562016-08-04 02:03:27 +0000742 Cmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000743 }
George Rimar06598002016-07-28 21:51:30 +0000744
George Rimar350ece42016-08-03 08:35:59 +0000745 if (skip("SORT") || skip("SORT_BY_NAME")) {
George Rimar0702c4e2016-07-29 15:32:46 +0000746 expect("(");
George Rimar350ece42016-08-03 08:35:59 +0000747 if (skip("SORT_BY_ALIGNMENT")) {
Rui Ueyama10416562016-08-04 02:03:27 +0000748 Cmd->Sort = SortKind::NameAlign;
George Rimar350ece42016-08-03 08:35:59 +0000749 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000750 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000751 expect(")");
752 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000753 Cmd->Sort = SortKind::Name;
754 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000755 }
756 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000757 return Cmd;
George Rimar350ece42016-08-03 08:35:59 +0000758 }
759
760 if (skip("SORT_BY_ALIGNMENT")) {
761 expect("(");
762 if (skip("SORT") || skip("SORT_BY_NAME")) {
Rui Ueyama10416562016-08-04 02:03:27 +0000763 Cmd->Sort = SortKind::AlignName;
George Rimar350ece42016-08-03 08:35:59 +0000764 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000765 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000766 expect(")");
767 } else {
Rui Ueyama10416562016-08-04 02:03:27 +0000768 Cmd->Sort = SortKind::Align;
769 Cmd->SectionPatterns = readInputFilePatterns();
George Rimar350ece42016-08-03 08:35:59 +0000770 }
George Rimar0702c4e2016-07-29 15:32:46 +0000771 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000772 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000773 }
George Rimar0702c4e2016-07-29 15:32:46 +0000774
Rui Ueyama10416562016-08-04 02:03:27 +0000775 Cmd->SectionPatterns = readInputFilePatterns();
776 return Cmd;
Davide Italianoe7282792016-07-27 01:44:01 +0000777}
778
Rui Ueyama10416562016-08-04 02:03:27 +0000779InputSectionDescription *ScriptParser::readInputSectionDescription() {
George Rimar06598002016-07-28 21:51:30 +0000780 // Input section wildcard can be surrounded by KEEP.
781 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
782 if (skip("KEEP")) {
783 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000784 InputSectionDescription *Cmd = readInputSectionRules();
George Rimar06598002016-07-28 21:51:30 +0000785 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000786 Opt.KeptSections.insert(Opt.KeptSections.end(),
787 Cmd->SectionPatterns.begin(),
788 Cmd->SectionPatterns.end());
789 return Cmd;
George Rimar06598002016-07-28 21:51:30 +0000790 }
Rui Ueyama10416562016-08-04 02:03:27 +0000791 return readInputSectionRules();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000792}
793
Rui Ueyama10416562016-08-04 02:03:27 +0000794Expr ScriptParser::readAlign() {
George Rimar630c6172016-07-26 18:06:29 +0000795 expect("(");
Rui Ueyama10416562016-08-04 02:03:27 +0000796 Expr E = readExpr();
George Rimar630c6172016-07-26 18:06:29 +0000797 expect(")");
Rui Ueyama10416562016-08-04 02:03:27 +0000798 return E;
George Rimar630c6172016-07-26 18:06:29 +0000799}
800
George Rimar03fc0102016-07-28 07:18:23 +0000801void ScriptParser::readSort() {
802 expect("(");
803 expect("CONSTRUCTORS");
804 expect(")");
805}
806
George Rimareefa7582016-08-04 09:29:31 +0000807Expr ScriptParser::readAssert() {
808 expect("(");
809 Expr E = readExpr();
810 expect(",");
811 StringRef Msg = next();
812 expect(")");
813 return [=](uint64_t Dot) {
814 uint64_t V = E(Dot);
815 if (!V)
816 error(Msg);
817 return V;
818 };
819}
820
Rui Ueyama10416562016-08-04 02:03:27 +0000821OutputSectionCommand *
822ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000823 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
George Rimar58e5c4d2016-07-25 08:29:46 +0000824
825 // Read an address expression.
826 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
827 if (peek() != ":")
828 Cmd->AddrExpr = readExpr();
829
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000830 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000831
George Rimar630c6172016-07-26 18:06:29 +0000832 if (skip("ALIGN"))
Rui Ueyama10416562016-08-04 02:03:27 +0000833 Cmd->AlignExpr = readAlign();
George Rimar630c6172016-07-26 18:06:29 +0000834
Davide Italiano246f6812016-07-22 03:36:24 +0000835 // Parse constraints.
836 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000837 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000838 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000839 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000840 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000841
Rui Ueyama025d59b2016-02-02 20:27:59 +0000842 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000843 if (peek().startswith("*") || peek() == "KEEP") {
Rui Ueyama10416562016-08-04 02:03:27 +0000844 Cmd->Commands.emplace_back(readInputSectionDescription());
George Rimar06598002016-07-28 21:51:30 +0000845 continue;
846 }
Rui Ueyamac1633182016-08-04 02:03:29 +0000847 if (skip("SORT")) {
George Rimar03fc0102016-07-28 07:18:23 +0000848 readSort();
Rui Ueyamac1633182016-08-04 02:03:29 +0000849 continue;
George Rimar481c2ce2016-02-23 07:47:54 +0000850 }
Rui Ueyamac1633182016-08-04 02:03:29 +0000851 setError("unknown command " + peek());
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000852 }
George Rimar076fe152016-07-21 06:43:01 +0000853 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000854 Cmd->Filler = readOutputSectionFiller();
Rui Ueyama10416562016-08-04 02:03:27 +0000855 return Cmd;
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000856}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000857
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000858std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000859 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000860 if (!Tok.startswith("="))
861 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000862 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000863
864 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000865 if (Tok.startswith("=0x"))
866 return parseHex(Tok.substr(3));
867
Rui Ueyama965827d2016-08-03 23:25:15 +0000868 // Read a decimal or octal value as a big-endian 32 bit value.
869 // Why do this? I don't know, but that's what gold does.
870 uint32_t V;
871 if (Tok.substr(1).getAsInteger(0, V)) {
872 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000873 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000874 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000875 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000876}
877
Rui Ueyama10416562016-08-04 02:03:27 +0000878SymbolAssignment *ScriptParser::readProvide(bool Hidden) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000879 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000880 SymbolAssignment *Cmd = readAssignment(next());
881 Cmd->Provide = true;
882 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000883 expect(")");
884 expect(";");
Rui Ueyama10416562016-08-04 02:03:27 +0000885 return Cmd;
Eugene Levianteda81a12016-07-12 06:39:48 +0000886}
887
George Rimar30835ea2016-07-28 21:08:56 +0000888static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
889 if (S == ".")
890 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000891
George Rimara9c5a522016-07-26 18:18:58 +0000892 switch (Config->EKind) {
893 case ELF32LEKind:
894 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
895 return B->getVA<ELF32LE>();
896 break;
897 case ELF32BEKind:
898 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
899 return B->getVA<ELF32BE>();
900 break;
901 case ELF64LEKind:
902 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
903 return B->getVA<ELF64LE>();
904 break;
905 case ELF64BEKind:
906 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
907 return B->getVA<ELF64BE>();
908 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000909 default:
George Rimarb567b622016-07-26 18:46:13 +0000910 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000911 }
912 error("symbol not found: " + S);
913 return 0;
914}
915
George Rimar9e694502016-07-29 16:18:47 +0000916static uint64_t getSectionSize(StringRef Name) {
917 switch (Config->EKind) {
918 case ELF32LEKind:
919 return Script<ELF32LE>::X->getOutputSectionSize(Name);
920 case ELF32BEKind:
921 return Script<ELF32BE>::X->getOutputSectionSize(Name);
922 case ELF64LEKind:
923 return Script<ELF64LE>::X->getOutputSectionSize(Name);
924 case ELF64BEKind:
925 return Script<ELF64BE>::X->getOutputSectionSize(Name);
926 default:
927 llvm_unreachable("unsupported target");
928 }
929 return 0;
930}
931
George Rimar30835ea2016-07-28 21:08:56 +0000932SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
933 StringRef Op = next();
934 assert(Op == "=" || Op == "+=");
935 Expr E = readExpr();
936 if (Op == "+=")
937 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
Rui Ueyama10416562016-08-04 02:03:27 +0000938 return new SymbolAssignment(Name, E);
George Rimar30835ea2016-07-28 21:08:56 +0000939}
940
941// This is an operator-precedence parser to parse a linker
942// script expression.
943Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
944
Rui Ueyama708019c2016-07-24 18:19:40 +0000945// This is a part of the operator-precedence parser. This function
946// assumes that the remaining token stream starts with an operator.
947Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
948 while (!atEOF() && !Error) {
949 // Read an operator and an expression.
950 StringRef Op1 = peek();
951 if (Op1 == "?")
952 return readTernary(Lhs);
953 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000954 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000955 next();
956 Expr Rhs = readPrimary();
957
958 // Evaluate the remaining part of the expression first if the
959 // next operator has greater precedence than the previous one.
960 // For example, if we have read "+" and "3", and if the next
961 // operator is "*", then we'll evaluate 3 * ... part first.
962 while (!atEOF()) {
963 StringRef Op2 = peek();
964 if (precedence(Op2) <= precedence(Op1))
965 break;
966 Rhs = readExpr1(Rhs, precedence(Op2));
967 }
968
969 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000970 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000971 return Lhs;
972}
973
974uint64_t static getConstant(StringRef S) {
975 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
976 return Target->PageSize;
977 error("unknown constant: " + S);
978 return 0;
979}
980
981Expr ScriptParser::readPrimary() {
982 StringRef Tok = next();
983
Rui Ueyama708019c2016-07-24 18:19:40 +0000984 if (Tok == "(") {
985 Expr E = readExpr();
986 expect(")");
987 return E;
988 }
989
990 // Built-in functions are parsed here.
991 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
George Rimareefa7582016-08-04 09:29:31 +0000992 if (Tok == "ASSERT")
993 return readAssert();
Rui Ueyama708019c2016-07-24 18:19:40 +0000994 if (Tok == "ALIGN") {
995 expect("(");
996 Expr E = readExpr();
997 expect(")");
998 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
999 }
1000 if (Tok == "CONSTANT") {
1001 expect("(");
1002 StringRef Tok = next();
1003 expect(")");
1004 return [=](uint64_t Dot) { return getConstant(Tok); };
1005 }
Rafael Espindola54c145c2016-07-28 18:16:24 +00001006 if (Tok == "SEGMENT_START") {
1007 expect("(");
1008 next();
1009 expect(",");
1010 uint64_t Val;
1011 next().getAsInteger(0, Val);
1012 expect(")");
1013 return [=](uint64_t Dot) { return Val; };
1014 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001015 if (Tok == "DATA_SEGMENT_ALIGN") {
1016 expect("(");
1017 Expr E = readExpr();
1018 expect(",");
1019 readExpr();
1020 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001021 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001022 }
1023 if (Tok == "DATA_SEGMENT_END") {
1024 expect("(");
1025 expect(".");
1026 expect(")");
1027 return [](uint64_t Dot) { return Dot; };
1028 }
George Rimar276b4e62016-07-26 17:58:44 +00001029 // GNU linkers implements more complicated logic to handle
1030 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1031 // the next page boundary for simplicity.
1032 if (Tok == "DATA_SEGMENT_RELRO_END") {
1033 expect("(");
1034 next();
1035 expect(",");
1036 readExpr();
1037 expect(")");
1038 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1039 }
George Rimar9e694502016-07-29 16:18:47 +00001040 if (Tok == "SIZEOF") {
1041 expect("(");
1042 StringRef Name = next();
1043 expect(")");
1044 return [=](uint64_t Dot) { return getSectionSize(Name); };
1045 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001046
George Rimara9c5a522016-07-26 18:18:58 +00001047 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001048 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001049 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001050 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001051 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001052 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001053 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001054 return [=](uint64_t Dot) { return V; };
1055}
1056
1057Expr ScriptParser::readTernary(Expr Cond) {
1058 next();
1059 Expr L = readExpr();
1060 expect(":");
1061 Expr R = readExpr();
1062 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1063}
1064
1065Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
1066 if (Op == "*")
1067 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1068 if (Op == "/") {
1069 return [=](uint64_t Dot) -> uint64_t {
1070 uint64_t RHS = R(Dot);
1071 if (RHS == 0) {
1072 error("division by zero");
1073 return 0;
1074 }
1075 return L(Dot) / RHS;
1076 };
1077 }
1078 if (Op == "+")
1079 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1080 if (Op == "-")
1081 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1082 if (Op == "<")
1083 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1084 if (Op == ">")
1085 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1086 if (Op == ">=")
1087 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1088 if (Op == "<=")
1089 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1090 if (Op == "==")
1091 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1092 if (Op == "!=")
1093 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1094 if (Op == "&")
1095 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1096 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +00001097}
1098
Eugene Leviantbbe38602016-07-19 09:25:43 +00001099std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1100 std::vector<StringRef> Phdrs;
1101 while (!Error && peek().startswith(":")) {
1102 StringRef Tok = next();
1103 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1104 if (Tok.empty()) {
1105 setError("section header name is empty");
1106 break;
1107 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001108 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001109 }
1110 return Phdrs;
1111}
1112
1113unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001114 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001115 unsigned Ret = StringSwitch<unsigned>(Tok)
1116 .Case("PT_NULL", PT_NULL)
1117 .Case("PT_LOAD", PT_LOAD)
1118 .Case("PT_DYNAMIC", PT_DYNAMIC)
1119 .Case("PT_INTERP", PT_INTERP)
1120 .Case("PT_NOTE", PT_NOTE)
1121 .Case("PT_SHLIB", PT_SHLIB)
1122 .Case("PT_PHDR", PT_PHDR)
1123 .Case("PT_TLS", PT_TLS)
1124 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1125 .Case("PT_GNU_STACK", PT_GNU_STACK)
1126 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1127 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001128
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001129 if (Ret == (unsigned)-1) {
1130 setError("invalid program header type: " + Tok);
1131 return PT_NULL;
1132 }
1133 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001134}
1135
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001136static bool isUnderSysroot(StringRef Path) {
1137 if (Config->Sysroot == "")
1138 return false;
1139 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1140 if (sys::fs::equivalent(Config->Sysroot, Path))
1141 return true;
1142 return false;
1143}
1144
Rui Ueyama07320e42016-04-20 20:13:41 +00001145// Entry point.
1146void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001147 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001148 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001149}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001150
Rui Ueyama07320e42016-04-20 20:13:41 +00001151template class elf::LinkerScript<ELF32LE>;
1152template class elf::LinkerScript<ELF32BE>;
1153template class elf::LinkerScript<ELF64LE>;
1154template class elf::LinkerScript<ELF64BE>;