blob: 97fa471e4a7e16fcbd01352ffd3d8c8608b0d96e [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
Rui Ueyama6b274812016-07-25 22:51:07 +000077// Create a vector of (<output section name>, <input section name patterns>).
78// For example, if a returned vector contains (".text" (".foo.*" ".bar.*")),
79// input sections start with ".foo." or ".bar." should be added to
80// ".text" section.
81template <class ELFT>
Davide Italianoe7282792016-07-27 01:44:01 +000082std::vector<std::pair<StringRef, const InputSectionDescription *>>
Rui Ueyama6b274812016-07-25 22:51:07 +000083LinkerScript<ELFT>::getSectionMap() {
Davide Italianoe7282792016-07-27 01:44:01 +000084 std::vector<std::pair<StringRef, const InputSectionDescription *>> Ret;
Rui Ueyama6b274812016-07-25 22:51:07 +000085
86 for (const std::unique_ptr<BaseCommand> &Base1 : Opt.Commands)
87 if (auto *Cmd1 = dyn_cast<OutputSectionCommand>(Base1.get()))
88 for (const std::unique_ptr<BaseCommand> &Base2 : Cmd1->Commands)
89 if (auto *Cmd2 = dyn_cast<InputSectionDescription>(Base2.get()))
Davide Italianoe7282792016-07-27 01:44:01 +000090 Ret.emplace_back(Cmd1->Name, Cmd2);
Rui Ueyama6b274812016-07-25 22:51:07 +000091
92 return Ret;
93}
94
George Rimar06598002016-07-28 21:51:30 +000095static bool fileMatches(const InputSectionDescription *Desc,
96 StringRef Filename) {
97 if (!globMatch(Desc->FilePattern, Filename))
98 return false;
99 return Desc->ExcludedFiles.empty() || !match(Desc->ExcludedFiles, Filename);
100}
101
Rui Ueyama6b274812016-07-25 22:51:07 +0000102// Returns input sections filtered by given glob patterns.
103template <class ELFT>
104std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000105LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
George Rimar06598002016-07-28 21:51:30 +0000106 ArrayRef<StringRef> Patterns = I->SectionPatterns;
Rui Ueyama6b274812016-07-25 22:51:07 +0000107 std::vector<InputSectionBase<ELFT> *> Ret;
108 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
George Rimar06598002016-07-28 21:51:30 +0000109 Symtab<ELFT>::X->getObjectFiles()) {
110 if (fileMatches(I, sys::path::filename(F->getName())))
111 for (InputSectionBase<ELFT> *S : F->getSections())
112 if (!isDiscarded(S) && !S->OutSec &&
113 match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000114 Ret.push_back(S);
George Rimar06598002016-07-28 21:51:30 +0000115 }
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000116
117 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000118 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000119
Rui Ueyama6b274812016-07-25 22:51:07 +0000120 return Ret;
121}
122
George Rimar652852c2016-04-16 10:10:32 +0000123template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000124std::vector<OutputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000125LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000126 std::vector<OutputSectionBase<ELFT> *> Ret;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000127
Eugene Leviante63d81b2016-07-20 14:43:20 +0000128 // Add input section to output section. If there is no output section yet,
129 // then create it and add to output section list.
Rui Ueyama6b274812016-07-25 22:51:07 +0000130 auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000131 OutputSectionBase<ELFT> *Sec;
132 bool IsNew;
133 std::tie(Sec, IsNew) = Factory.create(C, Name);
134 if (IsNew)
Rui Ueyama6b274812016-07-25 22:51:07 +0000135 Ret.push_back(Sec);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000136 Sec->addSection(C);
137 };
138
Rui Ueyama6b274812016-07-25 22:51:07 +0000139 for (auto &P : getSectionMap()) {
140 StringRef OutputName = P.first;
Davide Italianoe7282792016-07-27 01:44:01 +0000141 const InputSectionDescription *I = P.second;
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000142 for (InputSectionBase<ELFT> *S : getInputSections(I)) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000143 if (OutputName == "/DISCARD/") {
144 S->Live = false;
145 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000146 continue;
George Rimareea31142016-07-21 14:26:59 +0000147 }
Rui Ueyama6b274812016-07-25 22:51:07 +0000148 Add(S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000149 }
150 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000151
152 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000153 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
154 Symtab<ELFT>::X->getObjectFiles())
155 for (InputSectionBase<ELFT> *S : F->getSections())
156 if (!isDiscarded(S) && !S->OutSec)
157 Add(S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000158
Rui Ueyama3c291e12016-07-25 21:30:00 +0000159 // Remove from the output all the sections which did not meet
160 // the optional constraints.
Rui Ueyama6b274812016-07-25 22:51:07 +0000161 return filter(Ret);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000162}
163
164// Process ONLY_IF_RO and ONLY_IF_RW.
165template <class ELFT>
166std::vector<OutputSectionBase<ELFT> *>
167LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000168 // In this loop, we remove output sections if they don't satisfy
169 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000170 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
171 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
172 if (!Cmd || Cmd->Name == "/DISCARD/")
173 continue;
174
George Rimarbfc4a4b2016-07-26 10:47:09 +0000175 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000176 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000177
178 auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
179 return S->getName() == Cmd->Name;
180 });
181 if (It == Sections.end())
182 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000183
184 OutputSectionBase<ELFT> *Sec = *It;
185 bool Writable = (Sec->getFlags() & SHF_WRITE);
186 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
187 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
188
189 if ((RO && Writable) || (RW && !Writable)) {
190 Sections.erase(It);
191 continue;
192 }
Rui Ueyama3c291e12016-07-25 21:30:00 +0000193 }
194 return Sections;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000195}
196
197template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000198void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000199 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000200 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000201 // are not explicitly placed into the output file by the linker script.
202 // We place orphan sections at end of file.
203 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000204 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000205 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000206 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000207 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000208 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000209 }
George Rimar652852c2016-04-16 10:10:32 +0000210
Rui Ueyama7c18c282016-04-18 21:00:40 +0000211 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000212 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000213 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000214 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000215
George Rimar076fe152016-07-21 06:43:01 +0000216 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
217 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000218 if (Cmd->Name == ".") {
219 Dot = Cmd->Expression(Dot);
220 } else if (Cmd->Sym) {
221 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
222 }
George Rimar652852c2016-04-16 10:10:32 +0000223 continue;
224 }
225
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000226 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000227 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000228 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000229 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000230 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000231 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000232 continue;
George Rimar652852c2016-04-16 10:10:32 +0000233
George Rimar58e5c4d2016-07-25 08:29:46 +0000234 if (Cmd->AddrExpr)
235 Dot = Cmd->AddrExpr(Dot);
236
George Rimar630c6172016-07-26 18:06:29 +0000237 if (Cmd->AlignExpr)
238 Sec->updateAlignment(Cmd->AlignExpr(Dot));
239
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000240 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
241 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000242 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000243 Sec->setVA(TVA);
244 ThreadBssOffset = TVA - Dot + Sec->getSize();
245 continue;
246 }
George Rimar652852c2016-04-16 10:10:32 +0000247
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000248 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000249 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000250 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000251 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000252 Dot += Sec->getSize();
253 continue;
254 }
George Rimar652852c2016-04-16 10:10:32 +0000255 }
256 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000257
Rafael Espindola64c32d62016-07-07 14:28:47 +0000258 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000259 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000260 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
261 Out<ELFT>::ProgramHeaders->getSize(),
262 Target->PageSize);
263 Out<ELFT>::ElfHeader->setVA(MinVA);
264 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000265}
266
Rui Ueyama07320e42016-04-20 20:13:41 +0000267template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000268std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000269LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000270 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000271
272 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000273 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
274 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000275
276 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000277 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000278 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000279 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000280
281 switch (Cmd.Type) {
282 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000283 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000284 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000285 break;
286 case PT_DYNAMIC:
287 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000288 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000289 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000290 }
291 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000292 case PT_GNU_EH_FRAME:
293 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000294 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000295 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000296 }
297 break;
298 }
299 }
300
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000301 PhdrEntry<ELFT> *Load = nullptr;
302 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000303 for (OutputSectionBase<ELFT> *Sec : Sections) {
304 if (!(Sec->getFlags() & SHF_ALLOC))
305 break;
306
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000307 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000308 if (!PhdrIds.empty()) {
309 // Assign headers specified by linker script
310 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000311 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000312 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000313 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000314 }
315 } else {
316 // If we have no load segment or flags've changed then we want new load
317 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000318 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000319 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000320 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000321 Flags = NewFlags;
322 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000323 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000324 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000325 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000326 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000327}
328
329template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000330ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000331 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
332 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
333 if (Cmd->Name == Name)
334 return Cmd->Filler;
335 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000336}
337
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000338// Returns the index of the given section name in linker script
339// SECTIONS commands. Sections are laid out as the same order as they
340// were in the script. If a given name did not appear in the script,
341// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000342template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000343 int I = 0;
344 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
345 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
346 if (Cmd->Name == Name)
347 return I;
348 ++I;
349 }
350 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000351}
352
353// A compartor to sort output sections. Returns -1 or 1 if
354// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000355template <class ELFT>
356int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000357 int I = getSectionIndex(A);
358 int J = getSectionIndex(B);
359 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000360 return 0;
361 return I < J ? -1 : 1;
362}
363
Rui Ueyama8d083e62016-07-29 05:48:39 +0000364// Add symbols defined by linker scripts.
George Rimar076fe152016-07-21 06:43:01 +0000365template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000366 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
367 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
368 if (!Cmd || Cmd->Name == ".")
369 continue;
370
Rui Ueyama8d083e62016-07-29 05:48:39 +0000371 // If a symbol was in PROVIDE(), define it only when it is an
372 // undefined symbol.
Davide Italiano8ab41082016-07-23 22:09:04 +0000373 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000374 if (Cmd->Provide && !(B && B->isUndefined()))
375 continue;
376
377 // Define an absolute symbol. The symbol value will be assigned later.
378 // (At this point, we don't know the final address yet.)
379 Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
380 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
381 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
382 Cmd->Sym = Sym->body();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000383 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000384}
385
Eugene Leviantbbe38602016-07-19 09:25:43 +0000386template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
387 return !Opt.PhdrsCommands.empty();
388}
389
390// Returns indices of ELF headers containing specific section, identified
391// by Name. Each index is a zero based number of ELF header listed within
392// PHDRS {} script block.
393template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000394std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000395 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
396 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000397 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000398 continue;
399
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000400 std::vector<size_t> Ret;
401 for (StringRef PhdrName : Cmd->Phdrs)
402 Ret.push_back(getPhdrIndex(PhdrName));
403 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000404 }
George Rimar31d842f2016-07-20 16:43:03 +0000405 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000406}
407
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000408template <class ELFT>
409size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
410 size_t I = 0;
411 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
412 if (Cmd.Name == PhdrName)
413 return I;
414 ++I;
415 }
416 error("section header '" + PhdrName + "' is not listed in PHDRS");
417 return 0;
418}
419
Rui Ueyama07320e42016-04-20 20:13:41 +0000420class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000421 typedef void (ScriptParser::*Handler)();
422
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000423public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000424 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000425
Rui Ueyama4a465392016-04-22 22:59:24 +0000426 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000427
428private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000429 void addFile(StringRef Path);
430
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000431 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000432 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000433 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000434 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000435 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000436 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000437 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000438 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000439 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000440 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000441 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000442 void readSections();
443
Rui Ueyama113cdec2016-07-24 23:05:57 +0000444 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000445 void readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000446 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000447 std::vector<StringRef> readOutputSectionPhdrs();
George Rimar06598002016-07-28 21:51:30 +0000448 std::unique_ptr<InputSectionDescription> readInputSectionDescription();
449 void readInputSectionRules(InputSectionDescription *InCmd, bool Keep);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000450 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000451 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000452 void readAlign(OutputSectionCommand *Cmd);
George Rimar03fc0102016-07-28 07:18:23 +0000453 void readSort();
Rui Ueyama708019c2016-07-24 18:19:40 +0000454
455 Expr readExpr();
456 Expr readExpr1(Expr Lhs, int MinPrec);
457 Expr readPrimary();
458 Expr readTernary(Expr Cond);
459 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000460
George Rimarc3794e52016-02-24 09:21:47 +0000461 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000462 ScriptConfiguration &Opt = *ScriptConfig;
463 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000464 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000465};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000466
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000467const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000468 {"ENTRY", &ScriptParser::readEntry},
469 {"EXTERN", &ScriptParser::readExtern},
470 {"GROUP", &ScriptParser::readGroup},
471 {"INCLUDE", &ScriptParser::readInclude},
472 {"INPUT", &ScriptParser::readGroup},
473 {"OUTPUT", &ScriptParser::readOutput},
474 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
475 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000476 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000477 {"SEARCH_DIR", &ScriptParser::readSearchDir},
478 {"SECTIONS", &ScriptParser::readSections},
479 {";", &ScriptParser::readNothing}};
480
Rui Ueyama717677a2016-02-11 21:17:59 +0000481void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000482 while (!atEOF()) {
483 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000484 if (Handler Fn = Cmd.lookup(Tok))
485 (this->*Fn)();
486 else
George Rimar57610422016-03-11 14:43:02 +0000487 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000488 }
489}
490
Rui Ueyama717677a2016-02-11 21:17:59 +0000491void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000492 if (IsUnderSysroot && S.startswith("/")) {
493 SmallString<128> Path;
494 (Config->Sysroot + S).toStringRef(Path);
495 if (sys::fs::exists(Path)) {
496 Driver->addFile(Saver.save(Path.str()));
497 return;
498 }
499 }
500
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000501 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000502 Driver->addFile(S);
503 } else if (S.startswith("=")) {
504 if (Config->Sysroot.empty())
505 Driver->addFile(S.substr(1));
506 else
507 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
508 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000509 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000510 } else if (sys::fs::exists(S)) {
511 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000512 } else {
513 std::string Path = findFromSearchPaths(S);
514 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000515 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000516 else
517 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000518 }
519}
520
Rui Ueyama717677a2016-02-11 21:17:59 +0000521void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000522 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000523 bool Orig = Config->AsNeeded;
524 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000525 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000526 StringRef Tok = next();
527 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000528 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000529 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000530 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000531 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000532}
533
Rui Ueyama717677a2016-02-11 21:17:59 +0000534void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000535 // -e <symbol> takes predecence over ENTRY(<symbol>).
536 expect("(");
537 StringRef Tok = next();
538 if (Config->Entry.empty())
539 Config->Entry = Tok;
540 expect(")");
541}
542
Rui Ueyama717677a2016-02-11 21:17:59 +0000543void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000544 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000545 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000546 StringRef Tok = next();
547 if (Tok == ")")
548 return;
549 Config->Undefined.push_back(Tok);
550 }
551}
552
Rui Ueyama717677a2016-02-11 21:17:59 +0000553void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000554 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000555 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000556 StringRef Tok = next();
557 if (Tok == ")")
558 return;
559 if (Tok == "AS_NEEDED") {
560 readAsNeeded();
561 continue;
562 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000563 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000564 }
565}
566
Rui Ueyama717677a2016-02-11 21:17:59 +0000567void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000568 StringRef Tok = next();
569 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000570 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000571 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000572 return;
573 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000574 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000575 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
576 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000577 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000578}
579
Rui Ueyama717677a2016-02-11 21:17:59 +0000580void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000581 // -o <file> takes predecence over OUTPUT(<file>).
582 expect("(");
583 StringRef Tok = next();
584 if (Config->OutputFile.empty())
585 Config->OutputFile = Tok;
586 expect(")");
587}
588
Rui Ueyama717677a2016-02-11 21:17:59 +0000589void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000590 // Error checking only for now.
591 expect("(");
592 next();
593 expect(")");
594}
595
Rui Ueyama717677a2016-02-11 21:17:59 +0000596void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000597 // Error checking only for now.
598 expect("(");
599 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000600 StringRef Tok = next();
601 if (Tok == ")")
602 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000603 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000604 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000605 return;
606 }
Davide Italiano6836c612015-10-12 21:08:41 +0000607 next();
608 expect(",");
609 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000610 expect(")");
611}
612
Eugene Leviantbbe38602016-07-19 09:25:43 +0000613void ScriptParser::readPhdrs() {
614 expect("{");
615 while (!Error && !skip("}")) {
616 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000617 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000618 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
619
620 PhdrCmd.Type = readPhdrType();
621 do {
622 Tok = next();
623 if (Tok == ";")
624 break;
625 if (Tok == "FILEHDR")
626 PhdrCmd.HasFilehdr = true;
627 else if (Tok == "PHDRS")
628 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000629 else if (Tok == "FLAGS") {
630 expect("(");
631 next().getAsInteger(0, PhdrCmd.Flags);
632 expect(")");
633 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000634 setError("unexpected header attribute: " + Tok);
635 } while (!Error);
636 }
637}
638
Rui Ueyama717677a2016-02-11 21:17:59 +0000639void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000640 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000641 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000642 expect(")");
643}
644
Rui Ueyama717677a2016-02-11 21:17:59 +0000645void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000646 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000647 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000648 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000649 StringRef Tok = next();
George Rimar30835ea2016-07-28 21:08:56 +0000650 if (peek() == "=" || peek() == "+=") {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000651 readAssignment(Tok);
652 expect(";");
653 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000654 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000655 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000656 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000657 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000658 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000659 }
George Rimar652852c2016-04-16 10:10:32 +0000660 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000661}
662
Rui Ueyama708019c2016-07-24 18:19:40 +0000663static int precedence(StringRef Op) {
664 return StringSwitch<int>(Op)
665 .Case("*", 4)
666 .Case("/", 4)
667 .Case("+", 3)
668 .Case("-", 3)
669 .Case("<", 2)
670 .Case(">", 2)
671 .Case(">=", 2)
672 .Case("<=", 2)
673 .Case("==", 2)
674 .Case("!=", 2)
675 .Case("&", 1)
676 .Default(-1);
677}
678
George Rimar06598002016-07-28 21:51:30 +0000679void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd, bool Keep) {
680 InCmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000681 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000682
Davide Italianoe7282792016-07-27 01:44:01 +0000683 if (skip("EXCLUDE_FILE")) {
684 expect("(");
685 while (!Error && !skip(")"))
686 InCmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000687 }
George Rimar06598002016-07-28 21:51:30 +0000688
689 while (!Error && !skip(")")) {
690 if (Keep)
691 Opt.KeptSections.push_back(peek());
692 InCmd->SectionPatterns.push_back(next());
693 }
Davide Italianoe7282792016-07-27 01:44:01 +0000694}
695
George Rimar06598002016-07-28 21:51:30 +0000696std::unique_ptr<InputSectionDescription>
697ScriptParser::readInputSectionDescription() {
George Rimar352eac32016-07-28 22:10:50 +0000698 auto InCmd = llvm::make_unique<InputSectionDescription>();
George Rimar06598002016-07-28 21:51:30 +0000699
700 // Input section wildcard can be surrounded by KEEP.
701 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
702 if (skip("KEEP")) {
703 expect("(");
704 readInputSectionRules(InCmd.get(), true);
705 expect(")");
706 } else {
707 readInputSectionRules(InCmd.get(), false);
708 }
709
710 return InCmd;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000711}
712
George Rimar630c6172016-07-26 18:06:29 +0000713void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
714 expect("(");
715 Cmd->AlignExpr = readExpr();
716 expect(")");
717}
718
George Rimar03fc0102016-07-28 07:18:23 +0000719void ScriptParser::readSort() {
720 expect("(");
721 expect("CONSTRUCTORS");
722 expect(")");
723}
724
Eugene Levianteda81a12016-07-12 06:39:48 +0000725void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000726 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
727 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000728
729 // Read an address expression.
730 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
731 if (peek() != ":")
732 Cmd->AddrExpr = readExpr();
733
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000734 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000735
George Rimar630c6172016-07-26 18:06:29 +0000736 if (skip("ALIGN"))
737 readAlign(Cmd);
738
Davide Italiano246f6812016-07-22 03:36:24 +0000739 // Parse constraints.
740 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000741 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000742 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000743 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000744 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000745
Rui Ueyama025d59b2016-02-02 20:27:59 +0000746 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000747 if (peek().startswith("*") || peek() == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000748 Cmd->Commands.push_back(readInputSectionDescription());
749 continue;
750 }
751
George Rimar481c2ce2016-02-23 07:47:54 +0000752 StringRef Tok = next();
George Rimar06598002016-07-28 21:51:30 +0000753 if (Tok == "PROVIDE") {
Davide Italiano054a6792016-07-24 23:13:48 +0000754 readProvide(false);
755 } else if (Tok == "PROVIDE_HIDDEN") {
756 readProvide(true);
George Rimar03fc0102016-07-28 07:18:23 +0000757 } else if (Tok == "SORT") {
758 readSort();
George Rimar481c2ce2016-02-23 07:47:54 +0000759 } else {
George Rimar777f9632016-03-12 08:31:34 +0000760 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000761 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000762 }
George Rimar076fe152016-07-21 06:43:01 +0000763 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000764 Cmd->Filler = readOutputSectionFiller();
765}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000766
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000767std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000768 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000769 if (!Tok.startswith("="))
770 return {};
771 if (!Tok.startswith("=0x")) {
772 setError("filler should be a hexadecimal value");
773 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000774 }
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000775 Tok = Tok.substr(3);
776 next();
777 return parseHex(Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000778}
779
Eugene Levianta31c91b2016-07-22 07:38:40 +0000780void ScriptParser::readProvide(bool Hidden) {
781 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000782 SymbolAssignment *Cmd = readAssignment(next());
783 Cmd->Provide = true;
784 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000785 expect(")");
786 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000787}
788
George Rimar30835ea2016-07-28 21:08:56 +0000789static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
790 if (S == ".")
791 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000792
George Rimara9c5a522016-07-26 18:18:58 +0000793 switch (Config->EKind) {
794 case ELF32LEKind:
795 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
796 return B->getVA<ELF32LE>();
797 break;
798 case ELF32BEKind:
799 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
800 return B->getVA<ELF32BE>();
801 break;
802 case ELF64LEKind:
803 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
804 return B->getVA<ELF64LE>();
805 break;
806 case ELF64BEKind:
807 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
808 return B->getVA<ELF64BE>();
809 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000810 default:
George Rimarb567b622016-07-26 18:46:13 +0000811 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000812 }
813 error("symbol not found: " + S);
814 return 0;
815}
816
George Rimar30835ea2016-07-28 21:08:56 +0000817SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
818 StringRef Op = next();
819 assert(Op == "=" || Op == "+=");
820 Expr E = readExpr();
821 if (Op == "+=")
822 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
823 auto *Cmd = new SymbolAssignment(Name, E);
824 Opt.Commands.emplace_back(Cmd);
825 return Cmd;
826}
827
828// This is an operator-precedence parser to parse a linker
829// script expression.
830Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
831
Rui Ueyama708019c2016-07-24 18:19:40 +0000832// This is a part of the operator-precedence parser. This function
833// assumes that the remaining token stream starts with an operator.
834Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
835 while (!atEOF() && !Error) {
836 // Read an operator and an expression.
837 StringRef Op1 = peek();
838 if (Op1 == "?")
839 return readTernary(Lhs);
840 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000841 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000842 next();
843 Expr Rhs = readPrimary();
844
845 // Evaluate the remaining part of the expression first if the
846 // next operator has greater precedence than the previous one.
847 // For example, if we have read "+" and "3", and if the next
848 // operator is "*", then we'll evaluate 3 * ... part first.
849 while (!atEOF()) {
850 StringRef Op2 = peek();
851 if (precedence(Op2) <= precedence(Op1))
852 break;
853 Rhs = readExpr1(Rhs, precedence(Op2));
854 }
855
856 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000857 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000858 return Lhs;
859}
860
861uint64_t static getConstant(StringRef S) {
862 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
863 return Target->PageSize;
864 error("unknown constant: " + S);
865 return 0;
866}
867
868Expr ScriptParser::readPrimary() {
869 StringRef Tok = next();
870
Rui Ueyama708019c2016-07-24 18:19:40 +0000871 if (Tok == "(") {
872 Expr E = readExpr();
873 expect(")");
874 return E;
875 }
876
877 // Built-in functions are parsed here.
878 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
879 if (Tok == "ALIGN") {
880 expect("(");
881 Expr E = readExpr();
882 expect(")");
883 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
884 }
885 if (Tok == "CONSTANT") {
886 expect("(");
887 StringRef Tok = next();
888 expect(")");
889 return [=](uint64_t Dot) { return getConstant(Tok); };
890 }
Rafael Espindola54c145c2016-07-28 18:16:24 +0000891 if (Tok == "SEGMENT_START") {
892 expect("(");
893 next();
894 expect(",");
895 uint64_t Val;
896 next().getAsInteger(0, Val);
897 expect(")");
898 return [=](uint64_t Dot) { return Val; };
899 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000900 if (Tok == "DATA_SEGMENT_ALIGN") {
901 expect("(");
902 Expr E = readExpr();
903 expect(",");
904 readExpr();
905 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +0000906 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +0000907 }
908 if (Tok == "DATA_SEGMENT_END") {
909 expect("(");
910 expect(".");
911 expect(")");
912 return [](uint64_t Dot) { return Dot; };
913 }
George Rimar276b4e62016-07-26 17:58:44 +0000914 // GNU linkers implements more complicated logic to handle
915 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
916 // the next page boundary for simplicity.
917 if (Tok == "DATA_SEGMENT_RELRO_END") {
918 expect("(");
919 next();
920 expect(",");
921 readExpr();
922 expect(")");
923 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
924 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000925
George Rimara9c5a522016-07-26 18:18:58 +0000926 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +0000927 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +0000928 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +0000929 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +0000930 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +0000931 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +0000932 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000933 return [=](uint64_t Dot) { return V; };
934}
935
936Expr ScriptParser::readTernary(Expr Cond) {
937 next();
938 Expr L = readExpr();
939 expect(":");
940 Expr R = readExpr();
941 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
942}
943
944Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
945 if (Op == "*")
946 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
947 if (Op == "/") {
948 return [=](uint64_t Dot) -> uint64_t {
949 uint64_t RHS = R(Dot);
950 if (RHS == 0) {
951 error("division by zero");
952 return 0;
953 }
954 return L(Dot) / RHS;
955 };
956 }
957 if (Op == "+")
958 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
959 if (Op == "-")
960 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
961 if (Op == "<")
962 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
963 if (Op == ">")
964 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
965 if (Op == ">=")
966 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
967 if (Op == "<=")
968 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
969 if (Op == "==")
970 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
971 if (Op == "!=")
972 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
973 if (Op == "&")
974 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
975 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000976}
977
Eugene Leviantbbe38602016-07-19 09:25:43 +0000978std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
979 std::vector<StringRef> Phdrs;
980 while (!Error && peek().startswith(":")) {
981 StringRef Tok = next();
982 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
983 if (Tok.empty()) {
984 setError("section header name is empty");
985 break;
986 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000987 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000988 }
989 return Phdrs;
990}
991
992unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000993 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000994 unsigned Ret = StringSwitch<unsigned>(Tok)
995 .Case("PT_NULL", PT_NULL)
996 .Case("PT_LOAD", PT_LOAD)
997 .Case("PT_DYNAMIC", PT_DYNAMIC)
998 .Case("PT_INTERP", PT_INTERP)
999 .Case("PT_NOTE", PT_NOTE)
1000 .Case("PT_SHLIB", PT_SHLIB)
1001 .Case("PT_PHDR", PT_PHDR)
1002 .Case("PT_TLS", PT_TLS)
1003 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
1004 .Case("PT_GNU_STACK", PT_GNU_STACK)
1005 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1006 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001007
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001008 if (Ret == (unsigned)-1) {
1009 setError("invalid program header type: " + Tok);
1010 return PT_NULL;
1011 }
1012 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001013}
1014
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001015static bool isUnderSysroot(StringRef Path) {
1016 if (Config->Sysroot == "")
1017 return false;
1018 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1019 if (sys::fs::equivalent(Config->Sysroot, Path))
1020 return true;
1021 return false;
1022}
1023
Rui Ueyama07320e42016-04-20 20:13:41 +00001024// Entry point.
1025void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001026 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001027 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001028}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001029
Rui Ueyama07320e42016-04-20 20:13:41 +00001030template class elf::LinkerScript<ELF32LE>;
1031template class elf::LinkerScript<ELF32BE>;
1032template class elf::LinkerScript<ELF64LE>;
1033template class elf::LinkerScript<ELF64BE>;