blob: e040155de75c9bed9ed631a60de2064d3ddd1922 [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 Rimar652852c2016-04-16 10:10:32 +0000120template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000121std::vector<OutputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000122LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000123 std::vector<OutputSectionBase<ELFT> *> Ret;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000124
Eugene Leviante63d81b2016-07-20 14:43:20 +0000125 // Add input section to output section. If there is no output section yet,
126 // then create it and add to output section list.
Rui Ueyama6b274812016-07-25 22:51:07 +0000127 auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000128 OutputSectionBase<ELFT> *Sec;
129 bool IsNew;
130 std::tie(Sec, IsNew) = Factory.create(C, Name);
131 if (IsNew)
Rui Ueyama6b274812016-07-25 22:51:07 +0000132 Ret.push_back(Sec);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000133 Sec->addSection(C);
134 };
135
Rui Ueyama6b274812016-07-25 22:51:07 +0000136 for (auto &P : getSectionMap()) {
137 StringRef OutputName = P.first;
Davide Italianoe7282792016-07-27 01:44:01 +0000138 const InputSectionDescription *I = P.second;
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000139 for (InputSectionBase<ELFT> *S : getInputSections(I)) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000140 if (OutputName == "/DISCARD/") {
141 S->Live = false;
142 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000143 continue;
George Rimareea31142016-07-21 14:26:59 +0000144 }
Rui Ueyama6b274812016-07-25 22:51:07 +0000145 Add(S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000146 }
147 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000148
149 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000150 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
151 Symtab<ELFT>::X->getObjectFiles())
152 for (InputSectionBase<ELFT> *S : F->getSections())
153 if (!isDiscarded(S) && !S->OutSec)
154 Add(S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000155
Rui Ueyama3c291e12016-07-25 21:30:00 +0000156 // Remove from the output all the sections which did not meet
157 // the optional constraints.
Rui Ueyama6b274812016-07-25 22:51:07 +0000158 return filter(Ret);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000159}
160
161// Process ONLY_IF_RO and ONLY_IF_RW.
162template <class ELFT>
163std::vector<OutputSectionBase<ELFT> *>
164LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000165 // In this loop, we remove output sections if they don't satisfy
166 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000167 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
168 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
169 if (!Cmd || Cmd->Name == "/DISCARD/")
170 continue;
171
George Rimarbfc4a4b2016-07-26 10:47:09 +0000172 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000173 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000174
175 auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
176 return S->getName() == Cmd->Name;
177 });
178 if (It == Sections.end())
179 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000180
181 OutputSectionBase<ELFT> *Sec = *It;
182 bool Writable = (Sec->getFlags() & SHF_WRITE);
183 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
184 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
185
Rui Ueyamaed942712016-07-29 06:21:06 +0000186 if ((RO && Writable) || (RW && !Writable))
Rui Ueyama3c291e12016-07-25 21:30:00 +0000187 Sections.erase(It);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000188 }
189 return Sections;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000190}
191
192template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000193void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000194 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000195 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000196 // are not explicitly placed into the output file by the linker script.
197 // We place orphan sections at end of file.
198 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000199 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000200 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000201 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000202 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000203 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000204 }
George Rimar652852c2016-04-16 10:10:32 +0000205
Rui Ueyama7c18c282016-04-18 21:00:40 +0000206 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000207 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000208 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000209 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000210
George Rimar076fe152016-07-21 06:43:01 +0000211 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
212 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
Rui Ueyama8d083e62016-07-29 05:48:39 +0000213 if (Cmd->Name == ".") {
214 Dot = Cmd->Expression(Dot);
215 } else if (Cmd->Sym) {
216 cast<DefinedRegular<ELFT>>(Cmd->Sym)->Value = Cmd->Expression(Dot);
217 }
George Rimar652852c2016-04-16 10:10:32 +0000218 continue;
219 }
220
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000221 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000222 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000223 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000224 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000225 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000226 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000227 continue;
George Rimar652852c2016-04-16 10:10:32 +0000228
George Rimar58e5c4d2016-07-25 08:29:46 +0000229 if (Cmd->AddrExpr)
230 Dot = Cmd->AddrExpr(Dot);
231
George Rimar630c6172016-07-26 18:06:29 +0000232 if (Cmd->AlignExpr)
233 Sec->updateAlignment(Cmd->AlignExpr(Dot));
234
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000235 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
236 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000237 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000238 Sec->setVA(TVA);
239 ThreadBssOffset = TVA - Dot + Sec->getSize();
240 continue;
241 }
George Rimar652852c2016-04-16 10:10:32 +0000242
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000243 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000244 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000245 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000246 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000247 Dot += Sec->getSize();
248 continue;
249 }
George Rimar652852c2016-04-16 10:10:32 +0000250 }
251 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000252
Rafael Espindola64c32d62016-07-07 14:28:47 +0000253 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000254 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000255 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
256 Out<ELFT>::ProgramHeaders->getSize(),
257 Target->PageSize);
258 Out<ELFT>::ElfHeader->setVA(MinVA);
259 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000260}
261
Rui Ueyama07320e42016-04-20 20:13:41 +0000262template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000263std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000264LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000265 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000266
267 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000268 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
269 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000270
271 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000272 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000273 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000274 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000275
276 switch (Cmd.Type) {
277 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000278 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000279 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000280 break;
281 case PT_DYNAMIC:
282 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000283 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000284 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000285 }
286 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000287 case PT_GNU_EH_FRAME:
288 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000289 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000290 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000291 }
292 break;
293 }
294 }
295
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000296 PhdrEntry<ELFT> *Load = nullptr;
297 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000298 for (OutputSectionBase<ELFT> *Sec : Sections) {
299 if (!(Sec->getFlags() & SHF_ALLOC))
300 break;
301
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000302 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000303 if (!PhdrIds.empty()) {
304 // Assign headers specified by linker script
305 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000306 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000307 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000308 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000309 }
310 } else {
311 // If we have no load segment or flags've changed then we want new load
312 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000313 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000314 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000315 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000316 Flags = NewFlags;
317 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000318 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000319 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000320 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000321 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000322}
323
324template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000325ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000326 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
327 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
328 if (Cmd->Name == Name)
329 return Cmd->Filler;
330 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000331}
332
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000333// Returns the index of the given section name in linker script
334// SECTIONS commands. Sections are laid out as the same order as they
335// were in the script. If a given name did not appear in the script,
336// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000337template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000338 int I = 0;
339 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
340 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
341 if (Cmd->Name == Name)
342 return I;
343 ++I;
344 }
345 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000346}
347
348// A compartor to sort output sections. Returns -1 or 1 if
349// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000350template <class ELFT>
351int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000352 int I = getSectionIndex(A);
353 int J = getSectionIndex(B);
354 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000355 return 0;
356 return I < J ? -1 : 1;
357}
358
Rui Ueyama8d083e62016-07-29 05:48:39 +0000359// Add symbols defined by linker scripts.
George Rimar076fe152016-07-21 06:43:01 +0000360template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000361 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
362 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
363 if (!Cmd || Cmd->Name == ".")
364 continue;
365
Rui Ueyama8d083e62016-07-29 05:48:39 +0000366 // If a symbol was in PROVIDE(), define it only when it is an
367 // undefined symbol.
Davide Italiano8ab41082016-07-23 22:09:04 +0000368 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Rui Ueyama8d083e62016-07-29 05:48:39 +0000369 if (Cmd->Provide && !(B && B->isUndefined()))
370 continue;
371
372 // Define an absolute symbol. The symbol value will be assigned later.
373 // (At this point, we don't know the final address yet.)
374 Symbol *Sym = Symtab<ELFT>::X->addUndefined(Cmd->Name);
375 replaceBody<DefinedRegular<ELFT>>(Sym, Cmd->Name, STV_DEFAULT);
376 Sym->Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
377 Cmd->Sym = Sym->body();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000378 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000379}
380
Eugene Leviantbbe38602016-07-19 09:25:43 +0000381template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
382 return !Opt.PhdrsCommands.empty();
383}
384
385// Returns indices of ELF headers containing specific section, identified
386// by Name. Each index is a zero based number of ELF header listed within
387// PHDRS {} script block.
388template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000389std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000390 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
391 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000392 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000393 continue;
394
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000395 std::vector<size_t> Ret;
396 for (StringRef PhdrName : Cmd->Phdrs)
397 Ret.push_back(getPhdrIndex(PhdrName));
398 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000399 }
George Rimar31d842f2016-07-20 16:43:03 +0000400 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000401}
402
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000403template <class ELFT>
404size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
405 size_t I = 0;
406 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
407 if (Cmd.Name == PhdrName)
408 return I;
409 ++I;
410 }
411 error("section header '" + PhdrName + "' is not listed in PHDRS");
412 return 0;
413}
414
Rui Ueyama07320e42016-04-20 20:13:41 +0000415class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000416 typedef void (ScriptParser::*Handler)();
417
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000418public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000419 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000420
Rui Ueyama4a465392016-04-22 22:59:24 +0000421 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000422
423private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000424 void addFile(StringRef Path);
425
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000426 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000427 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000428 void readExtern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000429 void readGroup();
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000430 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000431 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000432 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000433 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000434 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000435 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000436 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000437 void readSections();
438
Rui Ueyama113cdec2016-07-24 23:05:57 +0000439 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000440 void readOutputSectionDescription(StringRef OutSec);
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000441 std::vector<uint8_t> readOutputSectionFiller();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000442 std::vector<StringRef> readOutputSectionPhdrs();
George Rimar06598002016-07-28 21:51:30 +0000443 std::unique_ptr<InputSectionDescription> readInputSectionDescription();
444 void readInputSectionRules(InputSectionDescription *InCmd, bool Keep);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000445 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000446 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000447 void readAlign(OutputSectionCommand *Cmd);
George Rimar03fc0102016-07-28 07:18:23 +0000448 void readSort();
Rui Ueyama708019c2016-07-24 18:19:40 +0000449
450 Expr readExpr();
451 Expr readExpr1(Expr Lhs, int MinPrec);
452 Expr readPrimary();
453 Expr readTernary(Expr Cond);
454 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000455
George Rimarc3794e52016-02-24 09:21:47 +0000456 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000457 ScriptConfiguration &Opt = *ScriptConfig;
458 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000459 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000460};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000461
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000462const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000463 {"ENTRY", &ScriptParser::readEntry},
464 {"EXTERN", &ScriptParser::readExtern},
465 {"GROUP", &ScriptParser::readGroup},
466 {"INCLUDE", &ScriptParser::readInclude},
467 {"INPUT", &ScriptParser::readGroup},
468 {"OUTPUT", &ScriptParser::readOutput},
469 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
470 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000471 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000472 {"SEARCH_DIR", &ScriptParser::readSearchDir},
473 {"SECTIONS", &ScriptParser::readSections},
474 {";", &ScriptParser::readNothing}};
475
Rui Ueyama717677a2016-02-11 21:17:59 +0000476void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000477 while (!atEOF()) {
478 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000479 if (Handler Fn = Cmd.lookup(Tok))
480 (this->*Fn)();
481 else
George Rimar57610422016-03-11 14:43:02 +0000482 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000483 }
484}
485
Rui Ueyama717677a2016-02-11 21:17:59 +0000486void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000487 if (IsUnderSysroot && S.startswith("/")) {
488 SmallString<128> Path;
489 (Config->Sysroot + S).toStringRef(Path);
490 if (sys::fs::exists(Path)) {
491 Driver->addFile(Saver.save(Path.str()));
492 return;
493 }
494 }
495
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000496 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000497 Driver->addFile(S);
498 } else if (S.startswith("=")) {
499 if (Config->Sysroot.empty())
500 Driver->addFile(S.substr(1));
501 else
502 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
503 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000504 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000505 } else if (sys::fs::exists(S)) {
506 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000507 } else {
508 std::string Path = findFromSearchPaths(S);
509 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000510 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000511 else
512 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000513 }
514}
515
Rui Ueyama717677a2016-02-11 21:17:59 +0000516void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000517 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000518 bool Orig = Config->AsNeeded;
519 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000520 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000521 StringRef Tok = next();
522 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000523 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000524 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000525 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000526 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000527}
528
Rui Ueyama717677a2016-02-11 21:17:59 +0000529void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000530 // -e <symbol> takes predecence over ENTRY(<symbol>).
531 expect("(");
532 StringRef Tok = next();
533 if (Config->Entry.empty())
534 Config->Entry = Tok;
535 expect(")");
536}
537
Rui Ueyama717677a2016-02-11 21:17:59 +0000538void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000539 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000540 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000541 StringRef Tok = next();
542 if (Tok == ")")
543 return;
544 Config->Undefined.push_back(Tok);
545 }
546}
547
Rui Ueyama717677a2016-02-11 21:17:59 +0000548void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000549 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000550 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000551 StringRef Tok = next();
552 if (Tok == ")")
553 return;
554 if (Tok == "AS_NEEDED") {
555 readAsNeeded();
556 continue;
557 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000558 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000559 }
560}
561
Rui Ueyama717677a2016-02-11 21:17:59 +0000562void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000563 StringRef Tok = next();
564 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000565 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000566 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000567 return;
568 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000569 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000570 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
571 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000572 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000573}
574
Rui Ueyama717677a2016-02-11 21:17:59 +0000575void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000576 // -o <file> takes predecence over OUTPUT(<file>).
577 expect("(");
578 StringRef Tok = next();
579 if (Config->OutputFile.empty())
580 Config->OutputFile = Tok;
581 expect(")");
582}
583
Rui Ueyama717677a2016-02-11 21:17:59 +0000584void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000585 // Error checking only for now.
586 expect("(");
587 next();
588 expect(")");
589}
590
Rui Ueyama717677a2016-02-11 21:17:59 +0000591void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000592 // Error checking only for now.
593 expect("(");
594 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000595 StringRef Tok = next();
596 if (Tok == ")")
597 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000598 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000599 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000600 return;
601 }
Davide Italiano6836c612015-10-12 21:08:41 +0000602 next();
603 expect(",");
604 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000605 expect(")");
606}
607
Eugene Leviantbbe38602016-07-19 09:25:43 +0000608void ScriptParser::readPhdrs() {
609 expect("{");
610 while (!Error && !skip("}")) {
611 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000612 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000613 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
614
615 PhdrCmd.Type = readPhdrType();
616 do {
617 Tok = next();
618 if (Tok == ";")
619 break;
620 if (Tok == "FILEHDR")
621 PhdrCmd.HasFilehdr = true;
622 else if (Tok == "PHDRS")
623 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000624 else if (Tok == "FLAGS") {
625 expect("(");
626 next().getAsInteger(0, PhdrCmd.Flags);
627 expect(")");
628 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000629 setError("unexpected header attribute: " + Tok);
630 } while (!Error);
631 }
632}
633
Rui Ueyama717677a2016-02-11 21:17:59 +0000634void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000635 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000636 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000637 expect(")");
638}
639
Rui Ueyama717677a2016-02-11 21:17:59 +0000640void ScriptParser::readSections() {
Rui Ueyama3de0a332016-07-29 03:31:09 +0000641 Opt.HasContents = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000642 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000643 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000644 StringRef Tok = next();
George Rimar30835ea2016-07-28 21:08:56 +0000645 if (peek() == "=" || peek() == "+=") {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000646 readAssignment(Tok);
647 expect(";");
648 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000649 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000650 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000651 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000652 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000653 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000654 }
George Rimar652852c2016-04-16 10:10:32 +0000655 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000656}
657
Rui Ueyama708019c2016-07-24 18:19:40 +0000658static int precedence(StringRef Op) {
659 return StringSwitch<int>(Op)
660 .Case("*", 4)
661 .Case("/", 4)
662 .Case("+", 3)
663 .Case("-", 3)
664 .Case("<", 2)
665 .Case(">", 2)
666 .Case(">=", 2)
667 .Case("<=", 2)
668 .Case("==", 2)
669 .Case("!=", 2)
670 .Case("&", 1)
671 .Default(-1);
672}
673
George Rimar06598002016-07-28 21:51:30 +0000674void ScriptParser::readInputSectionRules(InputSectionDescription *InCmd, bool Keep) {
675 InCmd->FilePattern = next();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000676 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000677
Davide Italianoe7282792016-07-27 01:44:01 +0000678 if (skip("EXCLUDE_FILE")) {
679 expect("(");
680 while (!Error && !skip(")"))
681 InCmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000682 }
George Rimar06598002016-07-28 21:51:30 +0000683
684 while (!Error && !skip(")")) {
685 if (Keep)
686 Opt.KeptSections.push_back(peek());
687 InCmd->SectionPatterns.push_back(next());
688 }
Davide Italianoe7282792016-07-27 01:44:01 +0000689}
690
George Rimar06598002016-07-28 21:51:30 +0000691std::unique_ptr<InputSectionDescription>
692ScriptParser::readInputSectionDescription() {
George Rimar352eac32016-07-28 22:10:50 +0000693 auto InCmd = llvm::make_unique<InputSectionDescription>();
George Rimar06598002016-07-28 21:51:30 +0000694
695 // Input section wildcard can be surrounded by KEEP.
696 // https://sourceware.org/binutils/docs/ld/Input-Section-Keep.html#Input-Section-Keep
697 if (skip("KEEP")) {
698 expect("(");
699 readInputSectionRules(InCmd.get(), true);
700 expect(")");
701 } else {
702 readInputSectionRules(InCmd.get(), false);
703 }
704
705 return InCmd;
Davide Italiano0ed42b02016-07-25 21:47:13 +0000706}
707
George Rimar630c6172016-07-26 18:06:29 +0000708void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
709 expect("(");
710 Cmd->AlignExpr = readExpr();
711 expect(")");
712}
713
George Rimar03fc0102016-07-28 07:18:23 +0000714void ScriptParser::readSort() {
715 expect("(");
716 expect("CONSTRUCTORS");
717 expect(")");
718}
719
Eugene Levianteda81a12016-07-12 06:39:48 +0000720void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000721 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
722 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000723
724 // Read an address expression.
725 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
726 if (peek() != ":")
727 Cmd->AddrExpr = readExpr();
728
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000729 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000730
George Rimar630c6172016-07-26 18:06:29 +0000731 if (skip("ALIGN"))
732 readAlign(Cmd);
733
Davide Italiano246f6812016-07-22 03:36:24 +0000734 // Parse constraints.
735 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000736 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000737 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000738 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000739 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000740
Rui Ueyama025d59b2016-02-02 20:27:59 +0000741 while (!Error && !skip("}")) {
George Rimarf586ff72016-07-28 22:15:44 +0000742 if (peek().startswith("*") || peek() == "KEEP") {
George Rimar06598002016-07-28 21:51:30 +0000743 Cmd->Commands.push_back(readInputSectionDescription());
744 continue;
745 }
746
George Rimar481c2ce2016-02-23 07:47:54 +0000747 StringRef Tok = next();
George Rimar06598002016-07-28 21:51:30 +0000748 if (Tok == "PROVIDE") {
Davide Italiano054a6792016-07-24 23:13:48 +0000749 readProvide(false);
750 } else if (Tok == "PROVIDE_HIDDEN") {
751 readProvide(true);
George Rimar03fc0102016-07-28 07:18:23 +0000752 } else if (Tok == "SORT") {
753 readSort();
George Rimar481c2ce2016-02-23 07:47:54 +0000754 } else {
George Rimar777f9632016-03-12 08:31:34 +0000755 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000756 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000757 }
George Rimar076fe152016-07-21 06:43:01 +0000758 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000759 Cmd->Filler = readOutputSectionFiller();
760}
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000761
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000762std::vector<uint8_t> ScriptParser::readOutputSectionFiller() {
George Rimare2ee72b2016-02-26 14:48:31 +0000763 StringRef Tok = peek();
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000764 if (!Tok.startswith("="))
765 return {};
766 if (!Tok.startswith("=0x")) {
767 setError("filler should be a hexadecimal value");
768 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000769 }
Rui Ueyamaf71caa22016-07-29 06:14:07 +0000770 Tok = Tok.substr(3);
771 next();
772 return parseHex(Tok);
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000773}
774
Eugene Levianta31c91b2016-07-22 07:38:40 +0000775void ScriptParser::readProvide(bool Hidden) {
776 expect("(");
Rui Ueyama174e0a12016-07-29 00:29:25 +0000777 SymbolAssignment *Cmd = readAssignment(next());
778 Cmd->Provide = true;
779 Cmd->Hidden = Hidden;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000780 expect(")");
781 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000782}
783
George Rimar30835ea2016-07-28 21:08:56 +0000784static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
785 if (S == ".")
786 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000787
George Rimara9c5a522016-07-26 18:18:58 +0000788 switch (Config->EKind) {
789 case ELF32LEKind:
790 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
791 return B->getVA<ELF32LE>();
792 break;
793 case ELF32BEKind:
794 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
795 return B->getVA<ELF32BE>();
796 break;
797 case ELF64LEKind:
798 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
799 return B->getVA<ELF64LE>();
800 break;
801 case ELF64BEKind:
802 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
803 return B->getVA<ELF64BE>();
804 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000805 default:
George Rimarb567b622016-07-26 18:46:13 +0000806 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000807 }
808 error("symbol not found: " + S);
809 return 0;
810}
811
George Rimar30835ea2016-07-28 21:08:56 +0000812SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
813 StringRef Op = next();
814 assert(Op == "=" || Op == "+=");
815 Expr E = readExpr();
816 if (Op == "+=")
817 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
818 auto *Cmd = new SymbolAssignment(Name, E);
819 Opt.Commands.emplace_back(Cmd);
820 return Cmd;
821}
822
823// This is an operator-precedence parser to parse a linker
824// script expression.
825Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
826
Rui Ueyama708019c2016-07-24 18:19:40 +0000827// This is a part of the operator-precedence parser. This function
828// assumes that the remaining token stream starts with an operator.
829Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
830 while (!atEOF() && !Error) {
831 // Read an operator and an expression.
832 StringRef Op1 = peek();
833 if (Op1 == "?")
834 return readTernary(Lhs);
835 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000836 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000837 next();
838 Expr Rhs = readPrimary();
839
840 // Evaluate the remaining part of the expression first if the
841 // next operator has greater precedence than the previous one.
842 // For example, if we have read "+" and "3", and if the next
843 // operator is "*", then we'll evaluate 3 * ... part first.
844 while (!atEOF()) {
845 StringRef Op2 = peek();
846 if (precedence(Op2) <= precedence(Op1))
847 break;
848 Rhs = readExpr1(Rhs, precedence(Op2));
849 }
850
851 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000852 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000853 return Lhs;
854}
855
856uint64_t static getConstant(StringRef S) {
857 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
858 return Target->PageSize;
859 error("unknown constant: " + S);
860 return 0;
861}
862
863Expr ScriptParser::readPrimary() {
864 StringRef Tok = next();
865
Rui Ueyama708019c2016-07-24 18:19:40 +0000866 if (Tok == "(") {
867 Expr E = readExpr();
868 expect(")");
869 return E;
870 }
871
872 // Built-in functions are parsed here.
873 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
874 if (Tok == "ALIGN") {
875 expect("(");
876 Expr E = readExpr();
877 expect(")");
878 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
879 }
880 if (Tok == "CONSTANT") {
881 expect("(");
882 StringRef Tok = next();
883 expect(")");
884 return [=](uint64_t Dot) { return getConstant(Tok); };
885 }
Rafael Espindola54c145c2016-07-28 18:16:24 +0000886 if (Tok == "SEGMENT_START") {
887 expect("(");
888 next();
889 expect(",");
890 uint64_t Val;
891 next().getAsInteger(0, Val);
892 expect(")");
893 return [=](uint64_t Dot) { return Val; };
894 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000895 if (Tok == "DATA_SEGMENT_ALIGN") {
896 expect("(");
897 Expr E = readExpr();
898 expect(",");
899 readExpr();
900 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +0000901 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +0000902 }
903 if (Tok == "DATA_SEGMENT_END") {
904 expect("(");
905 expect(".");
906 expect(")");
907 return [](uint64_t Dot) { return Dot; };
908 }
George Rimar276b4e62016-07-26 17:58:44 +0000909 // GNU linkers implements more complicated logic to handle
910 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
911 // the next page boundary for simplicity.
912 if (Tok == "DATA_SEGMENT_RELRO_END") {
913 expect("(");
914 next();
915 expect(",");
916 readExpr();
917 expect(")");
918 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
919 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000920
George Rimara9c5a522016-07-26 18:18:58 +0000921 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +0000922 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +0000923 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +0000924 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +0000925 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +0000926 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +0000927 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000928 return [=](uint64_t Dot) { return V; };
929}
930
931Expr ScriptParser::readTernary(Expr Cond) {
932 next();
933 Expr L = readExpr();
934 expect(":");
935 Expr R = readExpr();
936 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
937}
938
939Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
940 if (Op == "*")
941 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
942 if (Op == "/") {
943 return [=](uint64_t Dot) -> uint64_t {
944 uint64_t RHS = R(Dot);
945 if (RHS == 0) {
946 error("division by zero");
947 return 0;
948 }
949 return L(Dot) / RHS;
950 };
951 }
952 if (Op == "+")
953 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
954 if (Op == "-")
955 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
956 if (Op == "<")
957 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
958 if (Op == ">")
959 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
960 if (Op == ">=")
961 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
962 if (Op == "<=")
963 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
964 if (Op == "==")
965 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
966 if (Op == "!=")
967 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
968 if (Op == "&")
969 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
970 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000971}
972
Eugene Leviantbbe38602016-07-19 09:25:43 +0000973std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
974 std::vector<StringRef> Phdrs;
975 while (!Error && peek().startswith(":")) {
976 StringRef Tok = next();
977 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
978 if (Tok.empty()) {
979 setError("section header name is empty");
980 break;
981 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000982 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000983 }
984 return Phdrs;
985}
986
987unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000988 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000989 unsigned Ret = StringSwitch<unsigned>(Tok)
990 .Case("PT_NULL", PT_NULL)
991 .Case("PT_LOAD", PT_LOAD)
992 .Case("PT_DYNAMIC", PT_DYNAMIC)
993 .Case("PT_INTERP", PT_INTERP)
994 .Case("PT_NOTE", PT_NOTE)
995 .Case("PT_SHLIB", PT_SHLIB)
996 .Case("PT_PHDR", PT_PHDR)
997 .Case("PT_TLS", PT_TLS)
998 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
999 .Case("PT_GNU_STACK", PT_GNU_STACK)
1000 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
1001 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001002
Rui Ueyamab0f6c592016-07-20 19:36:38 +00001003 if (Ret == (unsigned)-1) {
1004 setError("invalid program header type: " + Tok);
1005 return PT_NULL;
1006 }
1007 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001008}
1009
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001010static bool isUnderSysroot(StringRef Path) {
1011 if (Config->Sysroot == "")
1012 return false;
1013 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1014 if (sys::fs::equivalent(Config->Sysroot, Path))
1015 return true;
1016 return false;
1017}
1018
Rui Ueyama07320e42016-04-20 20:13:41 +00001019// Entry point.
1020void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001021 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001022 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001023}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001024
Rui Ueyama07320e42016-04-20 20:13:41 +00001025template class elf::LinkerScript<ELF32LE>;
1026template class elf::LinkerScript<ELF32BE>;
1027template class elf::LinkerScript<ELF64LE>;
1028template class elf::LinkerScript<ELF64BE>;