blob: 8bb704c5247bbb4495faf825d680e0bbb7ca8c4b [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 Rimar652852c2016-04-16 10:10:32 +0000134template <class ELFT>
George Rimar0702c4e2016-07-29 15:32:46 +0000135static bool compareByName(InputSectionBase<ELFT> *A,
136 InputSectionBase<ELFT> *B) {
137 return A->getSectionName() < B->getSectionName();
138}
139
140template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000141void LinkerScript<ELFT>::createSections(
142 std::vector<OutputSectionBase<ELFT> *> *Out,
143 OutputSectionFactory<ELFT> &Factory) {
144 OutputSections = Out;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000145
Rui Ueyama6b274812016-07-25 22:51:07 +0000146 for (auto &P : getSectionMap()) {
George Rimar0702c4e2016-07-29 15:32:46 +0000147 std::vector<InputSectionBase<ELFT> *> Sections;
Rui Ueyama6b274812016-07-25 22:51:07 +0000148 StringRef OutputName = P.first;
Davide Italianoe7282792016-07-27 01:44:01 +0000149 const InputSectionDescription *I = P.second;
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000150 for (InputSectionBase<ELFT> *S : getInputSections(I)) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000151 if (OutputName == "/DISCARD/") {
152 S->Live = false;
153 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000154 continue;
George Rimareea31142016-07-21 14:26:59 +0000155 }
George Rimar0702c4e2016-07-29 15:32:46 +0000156 Sections.push_back(S);
George Rimareea31142016-07-21 14:26:59 +0000157 }
George Rimar0702c4e2016-07-29 15:32:46 +0000158 if (I->Sort)
159 std::stable_sort(Sections.begin(), Sections.end(), compareByName<ELFT>);
160 for (InputSectionBase<ELFT> *S : Sections)
George Rimar9e694502016-07-29 16:18:47 +0000161 addSection(Factory, *Out, S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000162 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000163
164 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000165 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
166 Symtab<ELFT>::X->getObjectFiles())
167 for (InputSectionBase<ELFT> *S : F->getSections())
168 if (!isDiscarded(S) && !S->OutSec)
George Rimar9e694502016-07-29 16:18:47 +0000169 addSection(Factory, *Out, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000170
Rui Ueyama3c291e12016-07-25 21:30:00 +0000171 // Remove from the output all the sections which did not meet
172 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000173 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000174}
175
176// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000177template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000178 // In this loop, we remove output sections if they don't satisfy
179 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000180 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
181 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
182 if (!Cmd || Cmd->Name == "/DISCARD/")
183 continue;
184
George Rimarbfc4a4b2016-07-26 10:47:09 +0000185 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000186 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000187
George Rimar9e694502016-07-29 16:18:47 +0000188 auto It = llvm::find_if(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
George Rimarbfc4a4b2016-07-26 10:47:09 +0000189 return S->getName() == Cmd->Name;
190 });
George Rimar9e694502016-07-29 16:18:47 +0000191 if (It == OutputSections->end())
George Rimarbfc4a4b2016-07-26 10:47:09 +0000192 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000193
194 OutputSectionBase<ELFT> *Sec = *It;
195 bool Writable = (Sec->getFlags() & SHF_WRITE);
196 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
197 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
198
Rui Ueyamaed942712016-07-29 06:21:06 +0000199 if ((RO && Writable) || (RW && !Writable))
George Rimar9e694502016-07-29 16:18:47 +0000200 OutputSections->erase(It);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000201 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000202}
203
204template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000205void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000206 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000207 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000208 // are not explicitly placed into the output file by the linker script.
209 // We place orphan sections at end of file.
210 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000211 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000212 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000213 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000214 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000215 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000216 }
George Rimar652852c2016-04-16 10:10:32 +0000217
Rui Ueyama7c18c282016-04-18 21:00:40 +0000218 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000219 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000220 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000221 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000222
George Rimar076fe152016-07-21 06:43:01 +0000223 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
224 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000225 if (Cmd->Name == ".") {
226 Dot = Cmd->Expression(Dot);
227 } else if (Cmd->Sym) {
228 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
229 }
George Rimar652852c2016-04-16 10:10:32 +0000230 continue;
231 }
232
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000233 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000234 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000235 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000236 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000237 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000238 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000239 continue;
George Rimar652852c2016-04-16 10:10:32 +0000240
George Rimar58e5c4d2016-07-25 08:29:46 +0000241 if (Cmd->AddrExpr)
242 Dot = Cmd->AddrExpr(Dot);
243
George Rimar630c6172016-07-26 18:06:29 +0000244 if (Cmd->AlignExpr)
245 Sec->updateAlignment(Cmd->AlignExpr(Dot));
246
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000247 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
248 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000249 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000250 Sec->setVA(TVA);
251 ThreadBssOffset = TVA - Dot + Sec->getSize();
252 continue;
253 }
George Rimar652852c2016-04-16 10:10:32 +0000254
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000255 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000256 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000257 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000258 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000259 Dot += Sec->getSize();
260 continue;
261 }
George Rimar652852c2016-04-16 10:10:32 +0000262 }
263 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000264
Rafael Espindola64c32d62016-07-07 14:28:47 +0000265 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000266 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000267 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
268 Out<ELFT>::ProgramHeaders->getSize(),
269 Target->PageSize);
270 Out<ELFT>::ElfHeader->setVA(MinVA);
271 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000272}
273
Rui Ueyama07320e42016-04-20 20:13:41 +0000274template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000275std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000276LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000277 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000278
279 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000280 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
281 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000282
283 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000284 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000285 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000286 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000287
288 switch (Cmd.Type) {
289 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000290 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000291 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000292 break;
293 case PT_DYNAMIC:
294 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000295 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000296 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000297 }
298 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000299 case PT_GNU_EH_FRAME:
300 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000301 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000302 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000303 }
304 break;
305 }
306 }
307
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000308 PhdrEntry<ELFT> *Load = nullptr;
309 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000310 for (OutputSectionBase<ELFT> *Sec : Sections) {
311 if (!(Sec->getFlags() & SHF_ALLOC))
312 break;
313
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000314 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000315 if (!PhdrIds.empty()) {
316 // Assign headers specified by linker script
317 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000318 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000319 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000320 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000321 }
322 } else {
323 // If we have no load segment or flags've changed then we want new load
324 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000325 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000326 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000327 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000328 Flags = NewFlags;
329 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000330 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000331 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000332 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000333 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000334}
335
336template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000337ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000338 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
339 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
340 if (Cmd->Name == Name)
341 return Cmd->Filler;
342 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000343}
344
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000345// Returns the index of the given section name in linker script
346// SECTIONS commands. Sections are laid out as the same order as they
347// were in the script. If a given name did not appear in the script,
348// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000349template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000350 int I = 0;
351 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
352 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
353 if (Cmd->Name == Name)
354 return I;
355 ++I;
356 }
357 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000358}
359
360// A compartor to sort output sections. Returns -1 or 1 if
361// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000362template <class ELFT>
363int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000364 int I = getSectionIndex(A);
365 int J = getSectionIndex(B);
366 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000367 return 0;
368 return I < J ? -1 : 1;
369}
370
Rui Ueyama8d083e62016-07-29 05:48:39 +0000371// Add symbols defined by linker scripts.
George Rimar076fe152016-07-21 06:43:01 +0000372template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000373 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
374 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
375 if (!Cmd || Cmd->Name == ".")
376 continue;
377
Rui Ueyama8d083e62016-07-29 05:48:39 +0000378 // If a symbol was in PROVIDE(), define it only when it is an
379 // undefined symbol.
Davide Italiano8ab41082016-07-23 22:09:04 +0000380 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000381 if (Cmd->Provide && !(B && B->isUndefined()))
382 continue;
383
384 // Define an absolute symbol. The symbol value will be assigned later.
385 // (At this point, we don't know the final address yet.)
386 Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
387 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
388 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
389 Cmd->Sym = Sym->body();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000390 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000391}
392
Eugene Leviantbbe38602016-07-19 09:25:43 +0000393template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
394 return !Opt.PhdrsCommands.empty();
395}
396
George Rimar9e694502016-07-29 16:18:47 +0000397template <class ELFT>
398typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
399 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
400 if (Sec->getName() == Name)
401 return Sec->getSize();
402 error("undefined section " + Name);
403 return 0;
404}
405
Eugene Leviantbbe38602016-07-19 09:25:43 +0000406// Returns indices of ELF headers containing specific section, identified
407// by Name. Each index is a zero based number of ELF header listed within
408// PHDRS {} script block.
409template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000410std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000411 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
412 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000413 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000414 continue;
415
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000416 std::vector<size_t> Ret;
417 for (StringRef PhdrName : Cmd->Phdrs)
418 Ret.push_back(getPhdrIndex(PhdrName));
419 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000420 }
George Rimar31d842f2016-07-20 16:43:03 +0000421 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000422}
423
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000424template <class ELFT>
425size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
426 size_t I = 0;
427 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
428 if (Cmd.Name == PhdrName)
429 return I;
430 ++I;
431 }
432 error("section header '" + PhdrName + "' is not listed in PHDRS");
433 return 0;
434}
435
Rui Ueyama07320e42016-04-20 20:13:41 +0000436class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000437 typedef void (ScriptParser::*Handler)();
438
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000439public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000440 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000441
Rui Ueyama4a465392016-04-22 22:59:24 +0000442 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000443
444private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000445 void addFile(StringRef Path);
446
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000447 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000448 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000449 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000450 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000451 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000452 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000453 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000454 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000455 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000456 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000457 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000458 void readSections();
459
Rui Ueyama113cdec2016-07-24 23:05:57 +0000460 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000461 void readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000462 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000463 std::vector<StringRef> readOutputSectionPhdrs();
George Rimar06598002016-07-28 21:51:30 +0000464 std::unique_ptr<InputSectionDescription> readInputSectionDescription();
George Rimar0702c4e2016-07-29 15:32:46 +0000465 void readInputFilePattern(InputSectionDescription *InCmd, bool Keep);
George Rimar06598002016-07-28 21:51:30 +0000466 void readInputSectionRules(InputSectionDescription *InCmd, bool Keep);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000467 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000468 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000469 void readAlign(OutputSectionCommand *Cmd);
George Rimar03fc0102016-07-28 07:18:23 +0000470 void readSort();
Rui Ueyama708019c2016-07-24 18:19:40 +0000471
472 Expr readExpr();
473 Expr readExpr1(Expr Lhs, int MinPrec);
474 Expr readPrimary();
475 Expr readTernary(Expr Cond);
476 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000477
George Rimarc3794e52016-02-24 09:21:47 +0000478 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000479 ScriptConfiguration &Opt = *ScriptConfig;
480 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000481 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000482};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000483
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000484const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000485 {"ENTRY", &ScriptParser::readEntry},
486 {"EXTERN", &ScriptParser::readExtern},
487 {"GROUP", &ScriptParser::readGroup},
488 {"INCLUDE", &ScriptParser::readInclude},
489 {"INPUT", &ScriptParser::readGroup},
490 {"OUTPUT", &ScriptParser::readOutput},
491 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
492 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000493 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000494 {"SEARCH_DIR", &ScriptParser::readSearchDir},
495 {"SECTIONS", &ScriptParser::readSections},
496 {";", &ScriptParser::readNothing}};
497
Rui Ueyama717677a2016-02-11 21:17:59 +0000498void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000499 while (!atEOF()) {
500 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000501 if (Handler Fn = Cmd.lookup(Tok))
502 (this->*Fn)();
503 else
George Rimar57610422016-03-11 14:43:02 +0000504 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000505 }
506}
507
Rui Ueyama717677a2016-02-11 21:17:59 +0000508void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000509 if (IsUnderSysroot && S.startswith("/")) {
510 SmallString<128> Path;
511 (Config->Sysroot + S).toStringRef(Path);
512 if (sys::fs::exists(Path)) {
513 Driver->addFile(Saver.save(Path.str()));
514 return;
515 }
516 }
517
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000518 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000519 Driver->addFile(S);
520 } else if (S.startswith("=")) {
521 if (Config->Sysroot.empty())
522 Driver->addFile(S.substr(1));
523 else
524 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
525 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000526 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000527 } else if (sys::fs::exists(S)) {
528 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000529 } else {
530 std::string Path = findFromSearchPaths(S);
531 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000532 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000533 else
534 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000535 }
536}
537
Rui Ueyama717677a2016-02-11 21:17:59 +0000538void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000539 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000540 bool Orig = Config->AsNeeded;
541 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000542 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000543 StringRef Tok = next();
544 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000545 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000546 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000547 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000548 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000549}
550
Rui Ueyama717677a2016-02-11 21:17:59 +0000551void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000552 // -e <symbol> takes predecence over ENTRY(<symbol>).
553 expect("(");
554 StringRef Tok = next();
555 if (Config->Entry.empty())
556 Config->Entry = Tok;
557 expect(")");
558}
559
Rui Ueyama717677a2016-02-11 21:17:59 +0000560void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000561 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000562 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000563 StringRef Tok = next();
564 if (Tok == ")")
565 return;
566 Config->Undefined.push_back(Tok);
567 }
568}
569
Rui Ueyama717677a2016-02-11 21:17:59 +0000570void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000571 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000572 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000573 StringRef Tok = next();
574 if (Tok == ")")
575 return;
576 if (Tok == "AS_NEEDED") {
577 readAsNeeded();
578 continue;
579 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000580 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000581 }
582}
583
Rui Ueyama717677a2016-02-11 21:17:59 +0000584void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000585 StringRef Tok = next();
586 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000587 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000588 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000589 return;
590 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000591 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000592 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
593 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000594 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000595}
596
Rui Ueyama717677a2016-02-11 21:17:59 +0000597void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000598 // -o <file> takes predecence over OUTPUT(<file>).
599 expect("(");
600 StringRef Tok = next();
601 if (Config->OutputFile.empty())
602 Config->OutputFile = Tok;
603 expect(")");
604}
605
Rui Ueyama717677a2016-02-11 21:17:59 +0000606void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000607 // Error checking only for now.
608 expect("(");
609 next();
610 expect(")");
611}
612
Rui Ueyama717677a2016-02-11 21:17:59 +0000613void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000614 // Error checking only for now.
615 expect("(");
616 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000617 StringRef Tok = next();
618 if (Tok == ")")
619 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000620 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000621 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000622 return;
623 }
Davide Italiano6836c612015-10-12 21:08:41 +0000624 next();
625 expect(",");
626 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000627 expect(")");
628}
629
Eugene Leviantbbe38602016-07-19 09:25:43 +0000630void ScriptParser::readPhdrs() {
631 expect("{");
632 while (!Error && !skip("}")) {
633 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000634 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000635 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
636
637 PhdrCmd.Type = readPhdrType();
638 do {
639 Tok = next();
640 if (Tok == ";")
641 break;
642 if (Tok == "FILEHDR")
643 PhdrCmd.HasFilehdr = true;
644 else if (Tok == "PHDRS")
645 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000646 else if (Tok == "FLAGS") {
647 expect("(");
648 next().getAsInteger(0, PhdrCmd.Flags);
649 expect(")");
650 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000651 setError("unexpected header attribute: " + Tok);
652 } while (!Error);
653 }
654}
655
Rui Ueyama717677a2016-02-11 21:17:59 +0000656void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000657 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000658 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000659 expect(")");
660}
661
Rui Ueyama717677a2016-02-11 21:17:59 +0000662void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000663 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000664 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000665 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000666 StringRef Tok = next();
George Rimar30835ea2016-07-28 21:08:56 +0000667 if (peek() == "=" || peek() == "+=") {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000668 readAssignment(Tok);
669 expect(";");
670 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000671 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000672 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000673 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000674 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000675 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000676 }
George Rimar652852c2016-04-16 10:10:32 +0000677 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000678}
679
Rui Ueyama708019c2016-07-24 18:19:40 +0000680static int precedence(StringRef Op) {
681 return StringSwitch<int>(Op)
682 .Case("*", 4)
683 .Case("/", 4)
684 .Case("+", 3)
685 .Case("-", 3)
686 .Case("<", 2)
687 .Case(">", 2)
688 .Case(">=", 2)
689 .Case("<=", 2)
690 .Case("==", 2)
691 .Case("!=", 2)
692 .Case("&", 1)
693 .Default(-1);
694}
695
George Rimar0702c4e2016-07-29 15:32:46 +0000696void ScriptParser::readInputFilePattern(InputSectionDescription *InCmd,
697 bool Keep) {
698 while (!Error && !skip(")")) {
699 if (Keep)
700 Opt.KeptSections.push_back(peek());
701 InCmd->SectionPatterns.push_back(next());
702 }
703}
704
705void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd,
706 bool Keep) {
George Rimar06598002016-07-28 21:51:30 +0000707 InCmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000708 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000709
Davide Italianoe7282792016-07-27 01:44:01 +0000710 if (skip("EXCLUDE_FILE")) {
711 expect("(");
712 while (!Error && !skip(")"))
713 InCmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000714 }
George Rimar06598002016-07-28 21:51:30 +0000715
George Rimar0702c4e2016-07-29 15:32:46 +0000716 if (skip("SORT")) {
717 expect("(");
718 InCmd->Sort = true;
719 readInputFilePattern(InCmd, Keep);
720 expect(")");
721 return;
George Rimar06598002016-07-28 21:51:30 +0000722 }
George Rimar0702c4e2016-07-29 15:32:46 +0000723
724 readInputFilePattern(InCmd, Keep);
Davide Italianoe7282792016-07-27 01:44:01 +0000725}
726
George Rimar06598002016-07-28 21:51:30 +0000727std::unique_ptr<InputSectionDescription>
728ScriptParser::readInputSectionDescription() {
George Rimar352eac32016-07-28 22:10:50 +0000729 auto InCmd = llvm::make_unique<InputSectionDescription>();
George Rimar06598002016-07-28 21:51:30 +0000730
731 // Input section wildcard can be surrounded by KEEP.
732 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
733 if (skip("KEEP")) {
734 expect("(");
735 readInputSectionRules(InCmd.get(), true);
736 expect(")");
737 } else {
738 readInputSectionRules(InCmd.get(), false);
739 }
740
741 return InCmd;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000742}
743
George Rimar630c6172016-07-26 18:06:29 +0000744void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
745 expect("(");
746 Cmd->AlignExpr = readExpr();
747 expect(")");
748}
749
George Rimar03fc0102016-07-28 07:18:23 +0000750void ScriptParser::readSort() {
751 expect("(");
752 expect("CONSTRUCTORS");
753 expect(")");
754}
755
Eugene Levianteda81a12016-07-12 06:39:48 +0000756void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000757 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
758 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000759
760 // Read an address expression.
761 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
762 if (peek() != ":")
763 Cmd->AddrExpr = readExpr();
764
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000765 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000766
George Rimar630c6172016-07-26 18:06:29 +0000767 if (skip("ALIGN"))
768 readAlign(Cmd);
769
Davide Italiano246f6812016-07-22 03:36:24 +0000770 // Parse constraints.
771 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000772 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000773 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000774 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000775 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000776
Rui Ueyama025d59b2016-02-02 20:27:59 +0000777 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000778 if (peek().startswith("*") || peek() == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000779 Cmd->Commands.push_back(readInputSectionDescription());
780 continue;
781 }
782
George Rimar481c2ce2016-02-23 07:47:54 +0000783 StringRef Tok = next();
George Rimar06598002016-07-28 21:51:30 +0000784 if (Tok == "PROVIDE") {
Davide Italiano054a6792016-07-24 23:13:48 +0000785 readProvide(false);
786 } else if (Tok == "PROVIDE_HIDDEN") {
787 readProvide(true);
George Rimar03fc0102016-07-28 07:18:23 +0000788 } else if (Tok == "SORT") {
789 readSort();
George Rimar481c2ce2016-02-23 07:47:54 +0000790 } else {
George Rimar777f9632016-03-12 08:31:34 +0000791 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000792 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000793 }
George Rimar076fe152016-07-21 06:43:01 +0000794 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000795 Cmd->Filler = readOutputSectionFiller();
796}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000797
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000798std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000799 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000800 if (!Tok.startswith("="))
801 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000802 next();
803 if (Tok.startswith("=0x"))
804 return parseHex(Tok.substr(3));
805
806 // This must be a decimal.
807 unsigned int Value;
808 if (Tok.substr(1).getAsInteger(10, Value)) {
809 setError("filler should be a decimal/hexadecimal value");
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000810 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000811 }
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000812 if (Value > 255)
813 setError("only single bytes decimal are supported for the filler now");
814 return {static_cast<unsigned char>(Value)};
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000815}
816
Eugene Levianta31c91b2016-07-22 07:38:40 +0000817void ScriptParser::readProvide(bool Hidden) {
818 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000819 SymbolAssignment *Cmd = readAssignment(next());
820 Cmd->Provide = true;
821 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000822 expect(")");
823 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000824}
825
George Rimar30835ea2016-07-28 21:08:56 +0000826static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
827 if (S == ".")
828 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000829
George Rimara9c5a522016-07-26 18:18:58 +0000830 switch (Config->EKind) {
831 case ELF32LEKind:
832 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
833 return B->getVA<ELF32LE>();
834 break;
835 case ELF32BEKind:
836 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
837 return B->getVA<ELF32BE>();
838 break;
839 case ELF64LEKind:
840 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
841 return B->getVA<ELF64LE>();
842 break;
843 case ELF64BEKind:
844 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
845 return B->getVA<ELF64BE>();
846 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000847 default:
George Rimarb567b622016-07-26 18:46:13 +0000848 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000849 }
850 error("symbol not found: " + S);
851 return 0;
852}
853
George Rimar9e694502016-07-29 16:18:47 +0000854static uint64_t getSectionSize(StringRef Name) {
855 switch (Config->EKind) {
856 case ELF32LEKind:
857 return Script<ELF32LE>::X->getOutputSectionSize(Name);
858 case ELF32BEKind:
859 return Script<ELF32BE>::X->getOutputSectionSize(Name);
860 case ELF64LEKind:
861 return Script<ELF64LE>::X->getOutputSectionSize(Name);
862 case ELF64BEKind:
863 return Script<ELF64BE>::X->getOutputSectionSize(Name);
864 default:
865 llvm_unreachable("unsupported target");
866 }
867 return 0;
868}
869
George Rimar30835ea2016-07-28 21:08:56 +0000870SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
871 StringRef Op = next();
872 assert(Op == "=" || Op == "+=");
873 Expr E = readExpr();
874 if (Op == "+=")
875 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
876 auto *Cmd = new SymbolAssignment(Name, E);
877 Opt.Commands.emplace_back(Cmd);
878 return Cmd;
879}
880
881// This is an operator-precedence parser to parse a linker
882// script expression.
883Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
884
Rui Ueyama708019c2016-07-24 18:19:40 +0000885// This is a part of the operator-precedence parser. This function
886// assumes that the remaining token stream starts with an operator.
887Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
888 while (!atEOF() && !Error) {
889 // Read an operator and an expression.
890 StringRef Op1 = peek();
891 if (Op1 == "?")
892 return readTernary(Lhs);
893 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000894 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000895 next();
896 Expr Rhs = readPrimary();
897
898 // Evaluate the remaining part of the expression first if the
899 // next operator has greater precedence than the previous one.
900 // For example, if we have read "+" and "3", and if the next
901 // operator is "*", then we'll evaluate 3 * ... part first.
902 while (!atEOF()) {
903 StringRef Op2 = peek();
904 if (precedence(Op2) <= precedence(Op1))
905 break;
906 Rhs = readExpr1(Rhs, precedence(Op2));
907 }
908
909 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000910 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000911 return Lhs;
912}
913
914uint64_t static getConstant(StringRef S) {
915 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
916 return Target->PageSize;
917 error("unknown constant: " + S);
918 return 0;
919}
920
921Expr ScriptParser::readPrimary() {
922 StringRef Tok = next();
923
Rui Ueyama708019c2016-07-24 18:19:40 +0000924 if (Tok == "(") {
925 Expr E = readExpr();
926 expect(")");
927 return E;
928 }
929
930 // Built-in functions are parsed here.
931 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
932 if (Tok == "ALIGN") {
933 expect("(");
934 Expr E = readExpr();
935 expect(")");
936 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
937 }
938 if (Tok == "CONSTANT") {
939 expect("(");
940 StringRef Tok = next();
941 expect(")");
942 return [=](uint64_t Dot) { return getConstant(Tok); };
943 }
Rafael Espindola54c145c2016-07-28 18:16:24 +0000944 if (Tok == "SEGMENT_START") {
945 expect("(");
946 next();
947 expect(",");
948 uint64_t Val;
949 next().getAsInteger(0, Val);
950 expect(")");
951 return [=](uint64_t Dot) { return Val; };
952 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000953 if (Tok == "DATA_SEGMENT_ALIGN") {
954 expect("(");
955 Expr E = readExpr();
956 expect(",");
957 readExpr();
958 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +0000959 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +0000960 }
961 if (Tok == "DATA_SEGMENT_END") {
962 expect("(");
963 expect(".");
964 expect(")");
965 return [](uint64_t Dot) { return Dot; };
966 }
George Rimar276b4e62016-07-26 17:58:44 +0000967 // GNU linkers implements more complicated logic to handle
968 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
969 // the next page boundary for simplicity.
970 if (Tok == "DATA_SEGMENT_RELRO_END") {
971 expect("(");
972 next();
973 expect(",");
974 readExpr();
975 expect(")");
976 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
977 }
George Rimar9e694502016-07-29 16:18:47 +0000978 if (Tok == "SIZEOF") {
979 expect("(");
980 StringRef Name = next();
981 expect(")");
982 return [=](uint64_t Dot) { return getSectionSize(Name); };
983 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000984
George Rimara9c5a522016-07-26 18:18:58 +0000985 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +0000986 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +0000987 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +0000988 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +0000989 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +0000990 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +0000991 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000992 return [=](uint64_t Dot) { return V; };
993}
994
995Expr ScriptParser::readTernary(Expr Cond) {
996 next();
997 Expr L = readExpr();
998 expect(":");
999 Expr R = readExpr();
1000 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1001}
1002
1003Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
1004 if (Op == "*")
1005 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1006 if (Op == "/") {
1007 return [=](uint64_t Dot) -> uint64_t {
1008 uint64_t RHS = R(Dot);
1009 if (RHS == 0) {
1010 error("division by zero");
1011 return 0;
1012 }
1013 return L(Dot) / RHS;
1014 };
1015 }
1016 if (Op == "+")
1017 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1018 if (Op == "-")
1019 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1020 if (Op == "<")
1021 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1022 if (Op == ">")
1023 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1024 if (Op == ">=")
1025 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1026 if (Op == "<=")
1027 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1028 if (Op == "==")
1029 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1030 if (Op == "!=")
1031 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1032 if (Op == "&")
1033 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1034 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +00001035}
1036
Eugene Leviantbbe38602016-07-19 09:25:43 +00001037std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1038 std::vector<StringRef> Phdrs;
1039 while (!Error && peek().startswith(":")) {
1040 StringRef Tok = next();
1041 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1042 if (Tok.empty()) {
1043 setError("section header name is empty");
1044 break;
1045 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001046 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001047 }
1048 return Phdrs;
1049}
1050
1051unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001052 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001053 unsigned Ret = StringSwitch<unsigned>(Tok)
1054 .Case("PT_NULL", PT_NULL)
1055 .Case("PT_LOAD", PT_LOAD)
1056 .Case("PT_DYNAMIC", PT_DYNAMIC)
1057 .Case("PT_INTERP", PT_INTERP)
1058 .Case("PT_NOTE", PT_NOTE)
1059 .Case("PT_SHLIB", PT_SHLIB)
1060 .Case("PT_PHDR", PT_PHDR)
1061 .Case("PT_TLS", PT_TLS)
1062 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1063 .Case("PT_GNU_STACK", PT_GNU_STACK)
1064 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1065 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001066
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001067 if (Ret == (unsigned)-1) {
1068 setError("invalid program header type: " + Tok);
1069 return PT_NULL;
1070 }
1071 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001072}
1073
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001074static bool isUnderSysroot(StringRef Path) {
1075 if (Config->Sysroot == "")
1076 return false;
1077 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1078 if (sys::fs::equivalent(Config->Sysroot, Path))
1079 return true;
1080 return false;
1081}
1082
Rui Ueyama07320e42016-04-20 20:13:41 +00001083// Entry point.
1084void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001085 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001086 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001087}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001088
Rui Ueyama07320e42016-04-20 20:13:41 +00001089template class elf::LinkerScript<ELF32LE>;
1090template class elf::LinkerScript<ELF32BE>;
1091template class elf::LinkerScript<ELF64LE>;
1092template class elf::LinkerScript<ELF64BE>;