blob: 808d62433e6ea8d699532d5c913ac9b6882296ce [file] [log] [blame]
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001//===- LinkerScript.cpp ---------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains the parser/evaluator of the linker script.
Rui Ueyama629e0aa52016-07-21 19:45:22 +000011// It parses a linker script and write the result to Config or ScriptConfig
12// objects.
13//
14// If SECTIONS command is used, a ScriptConfig contains an AST
15// of the command which will later be consumed by createSections() and
16// assignAddresses().
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000017//
18//===----------------------------------------------------------------------===//
19
Rui Ueyama717677a2016-02-11 21:17:59 +000020#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000021#include "Config.h"
22#include "Driver.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000023#include "InputSection.h"
George Rimar652852c2016-04-16 10:10:32 +000024#include "OutputSections.h"
Adhemerval Zanellae77b5bf2016-04-06 20:59:11 +000025#include "ScriptParser.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000026#include "Strings.h"
Eugene Levianteda81a12016-07-12 06:39:48 +000027#include "Symbols.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000028#include "SymbolTable.h"
Eugene Leviant467c4d52016-07-01 10:27:36 +000029#include "Target.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000030#include "Writer.h"
Rui Ueyama960504b2016-04-19 18:58:11 +000031#include "llvm/ADT/StringSwitch.h"
George Rimar652852c2016-04-16 10:10:32 +000032#include "llvm/Support/ELF.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
34#include "llvm/Support/MemoryBuffer.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000035#include "llvm/Support/Path.h"
Rui Ueyamaa47ee682015-10-11 01:53:04 +000036#include "llvm/Support/StringSaver.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000037
38using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000039using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000040using namespace llvm::object;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000041using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000042using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
Rui Ueyama07320e42016-04-20 20:13:41 +000044ScriptConfiguration *elf::ScriptConfig;
Rui Ueyama717677a2016-02-11 21:17:59 +000045
George Rimar076fe152016-07-21 06:43:01 +000046bool SymbolAssignment::classof(const BaseCommand *C) {
47 return C->Kind == AssignmentKind;
48}
49
50bool OutputSectionCommand::classof(const BaseCommand *C) {
51 return C->Kind == OutputSectionKind;
52}
53
George Rimareea31142016-07-21 14:26:59 +000054bool InputSectionDescription::classof(const BaseCommand *C) {
55 return C->Kind == InputSectionKind;
56}
57
Rui Ueyama36a153c2016-07-23 14:09:58 +000058template <class ELFT> static bool isDiscarded(InputSectionBase<ELFT> *S) {
George Rimareea31142016-07-21 14:26:59 +000059 return !S || !S->Live;
Rui Ueyama717677a2016-02-11 21:17:59 +000060}
61
Rui Ueyama07320e42016-04-20 20:13:41 +000062template <class ELFT>
63bool LinkerScript<ELFT>::shouldKeep(InputSectionBase<ELFT> *S) {
Rui Ueyama8ec77e62016-04-21 22:00:51 +000064 for (StringRef Pat : Opt.KeptSections)
Rui Ueyama722830a2016-06-29 05:32:09 +000065 if (globMatch(Pat, S->getSectionName()))
Rui Ueyama8ec77e62016-04-21 22:00:51 +000066 return true;
67 return false;
George Rimar481c2ce2016-02-23 07:47:54 +000068}
69
Rui Ueyama63dc6502016-07-25 22:41:42 +000070static bool match(ArrayRef<StringRef> Patterns, StringRef S) {
71 for (StringRef Pat : Patterns)
72 if (globMatch(Pat, S))
George Rimareea31142016-07-21 14:26:59 +000073 return true;
74 return false;
75}
76
George Rimareaee2af2016-07-29 15:07:11 +000077// Create a vector of (<output section name>, <input section description>).
Rui Ueyama6b274812016-07-25 22:51:07 +000078template <class ELFT>
Davide Italianoe7282792016-07-27 01:44:01 +000079std::vector<std::pair<StringRef, const InputSectionDescription *>>
Rui Ueyama6b274812016-07-25 22:51:07 +000080LinkerScript<ELFT>::getSectionMap() {
Davide Italianoe7282792016-07-27 01:44:01 +000081 std::vector<std::pair<StringRef, const InputSectionDescription *>> Ret;
Rui Ueyama6b274812016-07-25 22:51:07 +000082
83 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
84 if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get()))
85 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands)
86 if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get()))
Davide Italianoe7282792016-07-27 01:44:01 +000087 Ret.emplace_back(Cmd1->Name, Cmd2);
Rui Ueyama6b274812016-07-25 22:51:07 +000088
89 return Ret;
90}
91
George Rimar06598002016-07-28 21:51:30 +000092static bool fileMatches(const InputSectionDescription *Desc,
93 StringRef Filename) {
94 if (!globMatch(Desc->FilePattern, Filename))
95 return false;
96 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
97}
98
Rui Ueyama6b274812016-07-25 22:51:07 +000099// Returns input sections filtered by given glob patterns.
100template <class ELFT>
101std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000102LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000103 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000104 std::vector<InputSectionBase<ELFT> *> Ret;
105 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000106 Symtab<ELFT>::X->getObjectFiles()) {
107 if (fileMatches(I, sys::path::filename(F->getName())))
108 for (InputSectionBase<ELFT> *S : F->getSections())
109 if (!isDiscarded(S) && !S->OutSec &&
110 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000111 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000112 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000113
114 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000115 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000116
Rui Ueyama6b274812016-07-25 22:51:07 +0000117 return Ret;
118}
119
George Rimarc3cb8842016-07-29 15:12:48 +0000120// Add input section to output section. If there is no output section yet,
121// then create it and add to output section list.
122template <class ELFT>
123static void addSection(OutputSectionFactory<ELFT> &Factory,
124 std::vector<OutputSectionBase<ELFT> *> &Out,
125 InputSectionBase<ELFT> *C, StringRef Name) {
126 OutputSectionBase<ELFT> *Sec;
127 bool IsNew;
128 std::tie(Sec, IsNew) = Factory.create(C, Name);
129 if (IsNew)
130 Out.push_back(Sec);
131 Sec->addSection(C);
132}
133
George Rimar350ece42016-08-03 08:35:59 +0000134template <class ELFT> struct SectionsSorter {
135 SectionsSorter(SortKind Kind) : Kind(Kind) {}
136 bool operator()(InputSectionBase<ELFT> *A, InputSectionBase<ELFT> *B) {
137 int AlignmentCmp = A->Alignment - B->Alignment;
138 if (Kind == SortKind::Align || (Kind == SortKind::AlignName && AlignmentCmp != 0))
139 return AlignmentCmp < 0;
140
141 int NameCmp = A->getSectionName().compare(B->getSectionName());
142 if (Kind == SortKind::Name || (Kind == SortKind::NameAlign && NameCmp != 0))
143 return NameCmp < 0;
144
145 if (Kind == SortKind::NameAlign)
146 return AlignmentCmp < 0;
147 if (Kind == SortKind::AlignName)
148 return NameCmp < 0;
149
150 llvm_unreachable("unknown section sort kind in predicate");
151 return false;
152 }
153 SortKind Kind;
154};
George Rimar0702c4e2016-07-29 15:32:46 +0000155
156template <class ELFT>
George Rimar9e694502016-07-29 16:18:47 +0000157void LinkerScript<ELFT>::createSections(
158 std::vector<OutputSectionBase<ELFT> *> *Out,
159 OutputSectionFactory<ELFT> &Factory) {
160 OutputSections = Out;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000161
Rui Ueyama6b274812016-07-25 22:51:07 +0000162 for (auto &P : getSectionMap()) {
163 StringRef OutputName = P.first;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000164 const InputSectionDescription *Cmd = P.second;
165 std::vector<InputSectionBase<ELFT> *> Sections = getInputSections(Cmd);
166
167 if (OutputName == "/DISCARD/") {
168 for (InputSectionBase<ELFT> *S : Sections) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000169 S->Live = false;
170 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000171 }
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000172 continue;
George Rimareea31142016-07-21 14:26:59 +0000173 }
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000174
175 if (Cmd->Sort != SortKind::None)
George Rimar350ece42016-08-03 08:35:59 +0000176 std::stable_sort(Sections.begin(), Sections.end(),
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000177 SectionsSorter<ELFT>(Cmd->Sort));
178
George Rimar0702c4e2016-07-29 15:32:46 +0000179 for (InputSectionBase<ELFT> *S : Sections)
George Rimar9e694502016-07-29 16:18:47 +0000180 addSection(Factory, *Out, S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000181 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000182
183 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000184 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
185 Symtab<ELFT>::X->getObjectFiles())
186 for (InputSectionBase<ELFT> *S : F->getSections())
187 if (!isDiscarded(S) && !S->OutSec)
George Rimar9e694502016-07-29 16:18:47 +0000188 addSection(Factory, *Out, S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000189
Rui Ueyama3c291e12016-07-25 21:30:00 +0000190 // Remove from the output all the sections which did not meet
191 // the optional constraints.
George Rimar9e694502016-07-29 16:18:47 +0000192 filter();
Rui Ueyama3c291e12016-07-25 21:30:00 +0000193}
194
195// Process ONLY_IF_RO and ONLY_IF_RW.
George Rimar9e694502016-07-29 16:18:47 +0000196template <class ELFT> void LinkerScript<ELFT>::filter() {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000197 // In this loop, we remove output sections if they don't satisfy
198 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000199 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
200 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
201 if (!Cmd || Cmd->Name == "/DISCARD/")
202 continue;
203
George Rimarbfc4a4b2016-07-26 10:47:09 +0000204 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000205 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000206
George Rimar9e694502016-07-29 16:18:47 +0000207 auto It = llvm::find_if(*OutputSections, [&](OutputSectionBase<ELFT> *S) {
George Rimarbfc4a4b2016-07-26 10:47:09 +0000208 return S->getName() == Cmd->Name;
209 });
George Rimar9e694502016-07-29 16:18:47 +0000210 if (It == OutputSections->end())
George Rimarbfc4a4b2016-07-26 10:47:09 +0000211 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000212
213 OutputSectionBase<ELFT> *Sec = *It;
214 bool Writable = (Sec->getFlags() & SHF_WRITE);
215 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
216 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
217
Rui Ueyamaed942712016-07-29 06:21:06 +0000218 if ((RO && Writable) || (RW && !Writable))
George Rimar9e694502016-07-29 16:18:47 +0000219 OutputSections->erase(It);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000220 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000221}
222
Nico Weber2e367722016-08-03 14:37:57 +0000223template <class ELFT>
224void LinkerScript<ELFT>::assignAddresses(
225 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
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
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000252 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000253 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000254 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000255 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000256 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000257 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000258 continue;
George Rimar652852c2016-04-16 10:10:32 +0000259
George Rimar58e5c4d2016-07-25 08:29:46 +0000260 if (Cmd->AddrExpr)
261 Dot = Cmd->AddrExpr(Dot);
262
George Rimar630c6172016-07-26 18:06:29 +0000263 if (Cmd->AlignExpr)
264 Sec->updateAlignment(Cmd->AlignExpr(Dot));
265
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000266 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
267 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000268 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000269 Sec->setVA(TVA);
270 ThreadBssOffset = TVA - Dot + Sec->getSize();
271 continue;
272 }
George Rimar652852c2016-04-16 10:10:32 +0000273
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000274 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000275 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000276 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000277 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000278 Dot += Sec->getSize();
279 continue;
280 }
George Rimar652852c2016-04-16 10:10:32 +0000281 }
282 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000283
Rafael Espindola64c32d62016-07-07 14:28:47 +0000284 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000285 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000286 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
287 Out<ELFT>::ProgramHeaders->getSize(),
288 Target->PageSize);
289 Out<ELFT>::ElfHeader->setVA(MinVA);
290 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000291}
292
Rui Ueyama07320e42016-04-20 20:13:41 +0000293template <class ELFT>
Nico Weber2e367722016-08-03 14:37:57 +0000294std::vector<PhdrEntry<ELFT>>
295LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000296 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000297
298 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000299 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
300 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000301
302 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000303 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000304 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000305 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000306
307 switch (Cmd.Type) {
308 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000309 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000310 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000311 break;
312 case PT_DYNAMIC:
313 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000314 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000315 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000316 }
317 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000318 case PT_GNU_EH_FRAME:
319 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000320 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000321 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000322 }
323 break;
324 }
325 }
326
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000327 PhdrEntry<ELFT> *Load = nullptr;
328 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000329 for (OutputSectionBase<ELFT> *Sec : Sections) {
330 if (!(Sec->getFlags() & SHF_ALLOC))
331 break;
332
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000333 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000334 if (!PhdrIds.empty()) {
335 // Assign headers specified by linker script
336 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000337 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000338 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000339 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000340 }
341 } else {
342 // If we have no load segment or flags've changed then we want new load
343 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000344 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000345 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000346 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000347 Flags = NewFlags;
348 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000349 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000350 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000351 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000352 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000353}
354
355template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000356ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000357 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
358 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
359 if (Cmd->Name == Name)
360 return Cmd->Filler;
361 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000362}
363
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000364// Returns the index of the given section name in linker script
365// SECTIONS commands. Sections are laid out as the same order as they
366// were in the script. If a given name did not appear in the script,
367// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000368template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000369 int I = 0;
370 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
371 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
372 if (Cmd->Name == Name)
373 return I;
374 ++I;
375 }
376 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000377}
378
379// A compartor to sort output sections. Returns -1 or 1 if
380// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000381template <class ELFT>
382int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000383 int I = getSectionIndex(A);
384 int J = getSectionIndex(B);
385 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000386 return 0;
387 return I < J ? -1 : 1;
388}
389
Rui Ueyama8d083e62016-07-29 05:48:39 +0000390// Add symbols defined by linker scripts.
George Rimar076fe152016-07-21 06:43:01 +0000391template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000392 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
393 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
394 if (!Cmd || Cmd->Name == ".")
395 continue;
396
Rui Ueyama8d083e62016-07-29 05:48:39 +0000397 // If a symbol was in PROVIDE(), define it only when it is an
398 // undefined symbol.
Davide Italiano8ab41082016-07-23 22:09:04 +0000399 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000400 if (Cmd->Provide && !(B && B->isUndefined()))
401 continue;
402
403 // Define an absolute symbol. The symbol value will be assigned later.
404 // (At this point, we don't know the final address yet.)
405 Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
406 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
407 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
408 Cmd->Sym = Sym->body();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000409 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000410}
411
Eugene Leviantbbe38602016-07-19 09:25:43 +0000412template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
413 return !Opt.PhdrsCommands.empty();
414}
415
George Rimar9e694502016-07-29 16:18:47 +0000416template <class ELFT>
417typename ELFT::uint LinkerScript<ELFT>::getOutputSectionSize(StringRef Name) {
418 for (OutputSectionBase<ELFT> *Sec : *OutputSections)
419 if (Sec->getName() == Name)
420 return Sec->getSize();
421 error("undefined section " + Name);
422 return 0;
423}
424
Eugene Leviantbbe38602016-07-19 09:25:43 +0000425// Returns indices of ELF headers containing specific section, identified
426// by Name. Each index is a zero based number of ELF header listed within
427// PHDRS {} script block.
428template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000429std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000430 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
431 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000432 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000433 continue;
434
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000435 std::vector<size_t> Ret;
436 for (StringRef PhdrName : Cmd->Phdrs)
437 Ret.push_back(getPhdrIndex(PhdrName));
438 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000439 }
George Rimar31d842f2016-07-20 16:43:03 +0000440 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000441}
442
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000443template <class ELFT>
444size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
445 size_t I = 0;
446 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
447 if (Cmd.Name == PhdrName)
448 return I;
449 ++I;
450 }
451 error("section header '" + PhdrName + "' is not listed in PHDRS");
452 return 0;
453}
454
Rui Ueyama07320e42016-04-20 20:13:41 +0000455class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000456 typedef void (ScriptParser::*Handler)();
457
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000458public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000459 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000460
Rui Ueyama4a465392016-04-22 22:59:24 +0000461 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000462
463private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000464 void addFile(StringRef Path);
465
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000466 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000467 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000468 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000469 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000470 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000471 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000472 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000473 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000474 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000475 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000476 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000477 void readSections();
478
Rui Ueyama113cdec2016-07-24 23:05:57 +0000479 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000480 void readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000481 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000482 std::vector<StringRef> readOutputSectionPhdrs();
George Rimar06598002016-07-28 21:51:30 +0000483 std::unique_ptr<InputSectionDescription> readInputSectionDescription();
George Rimar0702c4e2016-07-29 15:32:46 +0000484 void readInputFilePattern(InputSectionDescription *InCmd, bool Keep);
George Rimar06598002016-07-28 21:51:30 +0000485 void readInputSectionRules(InputSectionDescription *InCmd, bool Keep);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000486 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000487 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000488 void readAlign(OutputSectionCommand *Cmd);
George Rimar03fc0102016-07-28 07:18:23 +0000489 void readSort();
Rui Ueyama708019c2016-07-24 18:19:40 +0000490
491 Expr readExpr();
492 Expr readExpr1(Expr Lhs, int MinPrec);
493 Expr readPrimary();
494 Expr readTernary(Expr Cond);
495 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000496
George Rimarc3794e52016-02-24 09:21:47 +0000497 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000498 ScriptConfiguration &Opt = *ScriptConfig;
499 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000500 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000501};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000502
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000503const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000504 {"ENTRY", &ScriptParser::readEntry},
505 {"EXTERN", &ScriptParser::readExtern},
506 {"GROUP", &ScriptParser::readGroup},
507 {"INCLUDE", &ScriptParser::readInclude},
508 {"INPUT", &ScriptParser::readGroup},
509 {"OUTPUT", &ScriptParser::readOutput},
510 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
511 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000512 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000513 {"SEARCH_DIR", &ScriptParser::readSearchDir},
514 {"SECTIONS", &ScriptParser::readSections},
515 {";", &ScriptParser::readNothing}};
516
Rui Ueyama717677a2016-02-11 21:17:59 +0000517void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000518 while (!atEOF()) {
519 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000520 if (Handler Fn = Cmd.lookup(Tok))
521 (this->*Fn)();
522 else
George Rimar57610422016-03-11 14:43:02 +0000523 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000524 }
525}
526
Rui Ueyama717677a2016-02-11 21:17:59 +0000527void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000528 if (IsUnderSysroot && S.startswith("/")) {
529 SmallString<128> Path;
530 (Config->Sysroot + S).toStringRef(Path);
531 if (sys::fs::exists(Path)) {
532 Driver->addFile(Saver.save(Path.str()));
533 return;
534 }
535 }
536
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000537 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000538 Driver->addFile(S);
539 } else if (S.startswith("=")) {
540 if (Config->Sysroot.empty())
541 Driver->addFile(S.substr(1));
542 else
543 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
544 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000545 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000546 } else if (sys::fs::exists(S)) {
547 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000548 } else {
549 std::string Path = findFromSearchPaths(S);
550 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000551 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000552 else
553 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000554 }
555}
556
Rui Ueyama717677a2016-02-11 21:17:59 +0000557void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000558 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000559 bool Orig = Config->AsNeeded;
560 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000561 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000562 StringRef Tok = next();
563 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000564 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000565 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000566 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000567 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000568}
569
Rui Ueyama717677a2016-02-11 21:17:59 +0000570void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000571 // -e <symbol> takes predecence over ENTRY(<symbol>).
572 expect("(");
573 StringRef Tok = next();
574 if (Config->Entry.empty())
575 Config->Entry = Tok;
576 expect(")");
577}
578
Rui Ueyama717677a2016-02-11 21:17:59 +0000579void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000580 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000581 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000582 StringRef Tok = next();
583 if (Tok == ")")
584 return;
585 Config->Undefined.push_back(Tok);
586 }
587}
588
Rui Ueyama717677a2016-02-11 21:17:59 +0000589void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000590 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000591 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000592 StringRef Tok = next();
593 if (Tok == ")")
594 return;
595 if (Tok == "AS_NEEDED") {
596 readAsNeeded();
597 continue;
598 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000599 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000600 }
601}
602
Rui Ueyama717677a2016-02-11 21:17:59 +0000603void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000604 StringRef Tok = next();
605 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000606 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000607 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000608 return;
609 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000610 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000611 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
612 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000613 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000614}
615
Rui Ueyama717677a2016-02-11 21:17:59 +0000616void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000617 // -o <file> takes predecence over OUTPUT(<file>).
618 expect("(");
619 StringRef Tok = next();
620 if (Config->OutputFile.empty())
621 Config->OutputFile = Tok;
622 expect(")");
623}
624
Rui Ueyama717677a2016-02-11 21:17:59 +0000625void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000626 // Error checking only for now.
627 expect("(");
628 next();
629 expect(")");
630}
631
Rui Ueyama717677a2016-02-11 21:17:59 +0000632void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000633 // Error checking only for now.
634 expect("(");
635 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000636 StringRef Tok = next();
637 if (Tok == ")")
638 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000639 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000640 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000641 return;
642 }
Davide Italiano6836c612015-10-12 21:08:41 +0000643 next();
644 expect(",");
645 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000646 expect(")");
647}
648
Eugene Leviantbbe38602016-07-19 09:25:43 +0000649void ScriptParser::readPhdrs() {
650 expect("{");
651 while (!Error && !skip("}")) {
652 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000653 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000654 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
655
656 PhdrCmd.Type = readPhdrType();
657 do {
658 Tok = next();
659 if (Tok == ";")
660 break;
661 if (Tok == "FILEHDR")
662 PhdrCmd.HasFilehdr = true;
663 else if (Tok == "PHDRS")
664 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000665 else if (Tok == "FLAGS") {
666 expect("(");
Rafael Espindolaeb685cd2016-08-02 22:14:57 +0000667 // Passing 0 for the value of dot is a bit of a hack. It means that
668 // we accept expressions like ".|1".
669 PhdrCmd.Flags = readExpr()(0);
Eugene Leviant865bf862016-07-21 10:43:25 +0000670 expect(")");
671 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000672 setError("unexpected header attribute: " + Tok);
673 } while (!Error);
674 }
675}
676
Rui Ueyama717677a2016-02-11 21:17:59 +0000677void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000678 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000679 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000680 expect(")");
681}
682
Rui Ueyama717677a2016-02-11 21:17:59 +0000683void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000684 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000685 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000686 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000687 StringRef Tok = next();
George Rimar30835ea2016-07-28 21:08:56 +0000688 if (peek() == "=" || peek() == "+=") {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000689 readAssignment(Tok);
690 expect(";");
691 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000692 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000693 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000694 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000695 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000696 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000697 }
George Rimar652852c2016-04-16 10:10:32 +0000698 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000699}
700
Rui Ueyama708019c2016-07-24 18:19:40 +0000701static int precedence(StringRef Op) {
702 return StringSwitch<int>(Op)
703 .Case("*", 4)
704 .Case("/", 4)
705 .Case("+", 3)
706 .Case("-", 3)
707 .Case("<", 2)
708 .Case(">", 2)
709 .Case(">=", 2)
710 .Case("<=", 2)
711 .Case("==", 2)
712 .Case("!=", 2)
713 .Case("&", 1)
714 .Default(-1);
715}
716
George Rimar0702c4e2016-07-29 15:32:46 +0000717void ScriptParser::readInputFilePattern(InputSectionDescription *InCmd,
718 bool Keep) {
719 while (!Error && !skip(")")) {
720 if (Keep)
721 Opt.KeptSections.push_back(peek());
722 InCmd->SectionPatterns.push_back(next());
723 }
724}
725
726void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd,
727 bool Keep) {
George Rimar06598002016-07-28 21:51:30 +0000728 InCmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000729 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000730
Davide Italianoe7282792016-07-27 01:44:01 +0000731 if (skip("EXCLUDE_FILE")) {
732 expect("(");
733 while (!Error && !skip(")"))
734 InCmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000735 }
George Rimar06598002016-07-28 21:51:30 +0000736
George Rimar350ece42016-08-03 08:35:59 +0000737 if (skip("SORT") || skip("SORT_BY_NAME")) {
George Rimar0702c4e2016-07-29 15:32:46 +0000738 expect("(");
George Rimar350ece42016-08-03 08:35:59 +0000739 if (skip("SORT_BY_ALIGNMENT")) {
740 InCmd->Sort = SortKind::NameAlign;
741 expect("(");
742 readInputFilePattern(InCmd, Keep);
743 expect(")");
744 } else {
745 InCmd->Sort = SortKind::Name;
746 readInputFilePattern(InCmd, Keep);
747 }
748 expect(")");
749 return;
750 }
751
752 if (skip("SORT_BY_ALIGNMENT")) {
753 expect("(");
754 if (skip("SORT") || skip("SORT_BY_NAME")) {
755 InCmd->Sort = SortKind::AlignName;
756 expect("(");
757 readInputFilePattern(InCmd, Keep);
758 expect(")");
759 } else {
760 InCmd->Sort = SortKind::Align;
761 readInputFilePattern(InCmd, Keep);
762 }
George Rimar0702c4e2016-07-29 15:32:46 +0000763 expect(")");
764 return;
George Rimar06598002016-07-28 21:51:30 +0000765 }
George Rimar0702c4e2016-07-29 15:32:46 +0000766
767 readInputFilePattern(InCmd, Keep);
Davide Italianoe7282792016-07-27 01:44:01 +0000768}
769
George Rimar06598002016-07-28 21:51:30 +0000770std::unique_ptr<InputSectionDescription>
771ScriptParser::readInputSectionDescription() {
George Rimar352eac32016-07-28 22:10:50 +0000772 auto InCmd = llvm::make_unique<InputSectionDescription>();
George Rimar06598002016-07-28 21:51:30 +0000773
774 // Input section wildcard can be surrounded by KEEP.
775 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
776 if (skip("KEEP")) {
777 expect("(");
778 readInputSectionRules(InCmd.get(), true);
779 expect(")");
780 } else {
781 readInputSectionRules(InCmd.get(), false);
782 }
783
784 return InCmd;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000785}
786
George Rimar630c6172016-07-26 18:06:29 +0000787void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
788 expect("(");
789 Cmd->AlignExpr = readExpr();
790 expect(")");
791}
792
George Rimar03fc0102016-07-28 07:18:23 +0000793void ScriptParser::readSort() {
794 expect("(");
795 expect("CONSTRUCTORS");
796 expect(")");
797}
798
Eugene Levianteda81a12016-07-12 06:39:48 +0000799void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000800 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
801 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000802
803 // Read an address expression.
804 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
805 if (peek() != ":")
806 Cmd->AddrExpr = readExpr();
807
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000808 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000809
George Rimar630c6172016-07-26 18:06:29 +0000810 if (skip("ALIGN"))
811 readAlign(Cmd);
812
Davide Italiano246f6812016-07-22 03:36:24 +0000813 // Parse constraints.
814 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000815 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000816 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000817 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000818 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000819
Rui Ueyama025d59b2016-02-02 20:27:59 +0000820 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000821 if (peek().startswith("*") || peek() == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000822 Cmd->Commands.push_back(readInputSectionDescription());
823 continue;
824 }
825
George Rimar481c2ce2016-02-23 07:47:54 +0000826 StringRef Tok = next();
George Rimar06598002016-07-28 21:51:30 +0000827 if (Tok == "PROVIDE") {
Davide Italiano054a6792016-07-24 23:13:48 +0000828 readProvide(false);
829 } else if (Tok == "PROVIDE_HIDDEN") {
830 readProvide(true);
George Rimar03fc0102016-07-28 07:18:23 +0000831 } else if (Tok == "SORT") {
832 readSort();
George Rimar481c2ce2016-02-23 07:47:54 +0000833 } else {
George Rimar777f9632016-03-12 08:31:34 +0000834 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000835 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000836 }
George Rimar076fe152016-07-21 06:43:01 +0000837 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000838 Cmd->Filler = readOutputSectionFiller();
839}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000840
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000841std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000842 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000843 if (!Tok.startswith("="))
844 return {};
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000845 next();
Rui Ueyama965827d2016-08-03 23:25:15 +0000846
847 // Read a hexstring of arbitrary length.
Davide Italiano5ac0d7c2016-07-29 22:21:28 +0000848 if (Tok.startswith("=0x"))
849 return parseHex(Tok.substr(3));
850
Rui Ueyama965827d2016-08-03 23:25:15 +0000851 // Read a decimal or octal value as a big-endian 32 bit value.
852 // Why do this? I don't know, but that's what gold does.
853 uint32_t V;
854 if (Tok.substr(1).getAsInteger(0, V)) {
855 setError("invalid filler expression: " + Tok);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000856 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000857 }
Rui Ueyama965827d2016-08-03 23:25:15 +0000858 return { uint8_t(V >> 24), uint8_t(V >> 16), uint8_t(V >> 8), uint8_t(V) };
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000859}
860
Eugene Levianta31c91b2016-07-22 07:38:40 +0000861void ScriptParser::readProvide(bool Hidden) {
862 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000863 SymbolAssignment *Cmd = readAssignment(next());
864 Cmd->Provide = true;
865 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000866 expect(")");
867 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000868}
869
George Rimar30835ea2016-07-28 21:08:56 +0000870static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
871 if (S == ".")
872 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000873
George Rimara9c5a522016-07-26 18:18:58 +0000874 switch (Config->EKind) {
875 case ELF32LEKind:
876 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
877 return B->getVA<ELF32LE>();
878 break;
879 case ELF32BEKind:
880 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
881 return B->getVA<ELF32BE>();
882 break;
883 case ELF64LEKind:
884 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
885 return B->getVA<ELF64LE>();
886 break;
887 case ELF64BEKind:
888 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
889 return B->getVA<ELF64BE>();
890 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000891 default:
George Rimarb567b622016-07-26 18:46:13 +0000892 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000893 }
894 error("symbol not found: " + S);
895 return 0;
896}
897
George Rimar9e694502016-07-29 16:18:47 +0000898static uint64_t getSectionSize(StringRef Name) {
899 switch (Config->EKind) {
900 case ELF32LEKind:
901 return Script<ELF32LE>::X->getOutputSectionSize(Name);
902 case ELF32BEKind:
903 return Script<ELF32BE>::X->getOutputSectionSize(Name);
904 case ELF64LEKind:
905 return Script<ELF64LE>::X->getOutputSectionSize(Name);
906 case ELF64BEKind:
907 return Script<ELF64BE>::X->getOutputSectionSize(Name);
908 default:
909 llvm_unreachable("unsupported target");
910 }
911 return 0;
912}
913
George Rimar30835ea2016-07-28 21:08:56 +0000914SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
915 StringRef Op = next();
916 assert(Op == "=" || Op == "+=");
917 Expr E = readExpr();
918 if (Op == "+=")
919 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
920 auto *Cmd = new SymbolAssignment(Name, E);
921 Opt.Commands.emplace_back(Cmd);
922 return Cmd;
923}
924
925// This is an operator-precedence parser to parse a linker
926// script expression.
927Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
928
Rui Ueyama708019c2016-07-24 18:19:40 +0000929// This is a part of the operator-precedence parser. This function
930// assumes that the remaining token stream starts with an operator.
931Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
932 while (!atEOF() && !Error) {
933 // Read an operator and an expression.
934 StringRef Op1 = peek();
935 if (Op1 == "?")
936 return readTernary(Lhs);
937 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000938 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000939 next();
940 Expr Rhs = readPrimary();
941
942 // Evaluate the remaining part of the expression first if the
943 // next operator has greater precedence than the previous one.
944 // For example, if we have read "+" and "3", and if the next
945 // operator is "*", then we'll evaluate 3 * ... part first.
946 while (!atEOF()) {
947 StringRef Op2 = peek();
948 if (precedence(Op2) <= precedence(Op1))
949 break;
950 Rhs = readExpr1(Rhs, precedence(Op2));
951 }
952
953 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000954 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000955 return Lhs;
956}
957
958uint64_t static getConstant(StringRef S) {
959 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
960 return Target->PageSize;
961 error("unknown constant: " + S);
962 return 0;
963}
964
965Expr ScriptParser::readPrimary() {
966 StringRef Tok = next();
967
Rui Ueyama708019c2016-07-24 18:19:40 +0000968 if (Tok == "(") {
969 Expr E = readExpr();
970 expect(")");
971 return E;
972 }
973
974 // Built-in functions are parsed here.
975 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
976 if (Tok == "ALIGN") {
977 expect("(");
978 Expr E = readExpr();
979 expect(")");
980 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
981 }
982 if (Tok == "CONSTANT") {
983 expect("(");
984 StringRef Tok = next();
985 expect(")");
986 return [=](uint64_t Dot) { return getConstant(Tok); };
987 }
Rafael Espindola54c145c2016-07-28 18:16:24 +0000988 if (Tok == "SEGMENT_START") {
989 expect("(");
990 next();
991 expect(",");
992 uint64_t Val;
993 next().getAsInteger(0, Val);
994 expect(")");
995 return [=](uint64_t Dot) { return Val; };
996 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000997 if (Tok == "DATA_SEGMENT_ALIGN") {
998 expect("(");
999 Expr E = readExpr();
1000 expect(",");
1001 readExpr();
1002 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +00001003 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +00001004 }
1005 if (Tok == "DATA_SEGMENT_END") {
1006 expect("(");
1007 expect(".");
1008 expect(")");
1009 return [](uint64_t Dot) { return Dot; };
1010 }
George Rimar276b4e62016-07-26 17:58:44 +00001011 // GNU linkers implements more complicated logic to handle
1012 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
1013 // the next page boundary for simplicity.
1014 if (Tok == "DATA_SEGMENT_RELRO_END") {
1015 expect("(");
1016 next();
1017 expect(",");
1018 readExpr();
1019 expect(")");
1020 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
1021 }
George Rimar9e694502016-07-29 16:18:47 +00001022 if (Tok == "SIZEOF") {
1023 expect("(");
1024 StringRef Name = next();
1025 expect(")");
1026 return [=](uint64_t Dot) { return getSectionSize(Name); };
1027 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001028
George Rimara9c5a522016-07-26 18:18:58 +00001029 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +00001030 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +00001031 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +00001032 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +00001033 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +00001034 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +00001035 }
Rui Ueyama708019c2016-07-24 18:19:40 +00001036 return [=](uint64_t Dot) { return V; };
1037}
1038
1039Expr ScriptParser::readTernary(Expr Cond) {
1040 next();
1041 Expr L = readExpr();
1042 expect(":");
1043 Expr R = readExpr();
1044 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
1045}
1046
1047Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
1048 if (Op == "*")
1049 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
1050 if (Op == "/") {
1051 return [=](uint64_t Dot) -> uint64_t {
1052 uint64_t RHS = R(Dot);
1053 if (RHS == 0) {
1054 error("division by zero");
1055 return 0;
1056 }
1057 return L(Dot) / RHS;
1058 };
1059 }
1060 if (Op == "+")
1061 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
1062 if (Op == "-")
1063 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
1064 if (Op == "<")
1065 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
1066 if (Op == ">")
1067 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
1068 if (Op == ">=")
1069 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
1070 if (Op == "<=")
1071 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
1072 if (Op == "==")
1073 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
1074 if (Op == "!=")
1075 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
1076 if (Op == "&")
1077 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
1078 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +00001079}
1080
Eugene Leviantbbe38602016-07-19 09:25:43 +00001081std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
1082 std::vector<StringRef> Phdrs;
1083 while (!Error && peek().startswith(":")) {
1084 StringRef Tok = next();
1085 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
1086 if (Tok.empty()) {
1087 setError("section header name is empty");
1088 break;
1089 }
Rui Ueyama047404f2016-07-20 19:36:36 +00001090 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001091 }
1092 return Phdrs;
1093}
1094
1095unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +00001096 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001097 unsigned Ret = StringSwitch<unsigned>(Tok)
1098 .Case("PT_NULL", PT_NULL)
1099 .Case("PT_LOAD", PT_LOAD)
1100 .Case("PT_DYNAMIC", PT_DYNAMIC)
1101 .Case("PT_INTERP", PT_INTERP)
1102 .Case("PT_NOTE", PT_NOTE)
1103 .Case("PT_SHLIB", PT_SHLIB)
1104 .Case("PT_PHDR", PT_PHDR)
1105 .Case("PT_TLS", PT_TLS)
1106 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1107 .Case("PT_GNU_STACK", PT_GNU_STACK)
1108 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1109 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001110
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001111 if (Ret == (unsigned)-1) {
1112 setError("invalid program header type: " + Tok);
1113 return PT_NULL;
1114 }
1115 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001116}
1117
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001118static bool isUnderSysroot(StringRef Path) {
1119 if (Config->Sysroot == "")
1120 return false;
1121 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1122 if (sys::fs::equivalent(Config->Sysroot, Path))
1123 return true;
1124 return false;
1125}
1126
Rui Ueyama07320e42016-04-20 20:13:41 +00001127// Entry point.
1128void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001129 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001130 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001131}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001132
Rui Ueyama07320e42016-04-20 20:13:41 +00001133template class elf::LinkerScript<ELF32LE>;
1134template class elf::LinkerScript<ELF32BE>;
1135template class elf::LinkerScript<ELF64LE>;
1136template class elf::LinkerScript<ELF64BE>;