blob: 339c06dde66f080f6ea08a131ddc9912db106475 [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
95// Returns input sections filtered by given glob patterns.
96template <class ELFT>
97std::vector<InputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +000098LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
Davide Italianoe7282792016-07-27 01:44:01 +000099 ArrayRef<StringRef> Patterns = I->Patterns;
100 ArrayRef<StringRef> ExcludedFiles = I->ExcludedFiles;
Rui Ueyama6b274812016-07-25 22:51:07 +0000101 std::vector<InputSectionBase<ELFT> *> Ret;
102 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
103 Symtab<ELFT>::X->getObjectFiles())
104 for (InputSectionBase<ELFT> *S : F->getSections())
105 if (!isDiscarded(S) && !S->OutSec && match(Patterns, S->getSectionName()))
Davide Italianoe7282792016-07-27 01:44:01 +0000106 if (ExcludedFiles.empty() ||
107 !match(ExcludedFiles, sys::path::filename(F->getName())))
108 Ret.push_back(S);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000109
110 if ((llvm::find(Patterns, "COMMON") != Patterns.end()))
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000111 Ret.push_back(CommonInputSection<ELFT>::X);
Eugene Leviant3e6b0272016-07-28 19:24:13 +0000112
Rui Ueyama6b274812016-07-25 22:51:07 +0000113 return Ret;
114}
115
George Rimar652852c2016-04-16 10:10:32 +0000116template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000117std::vector<OutputSectionBase<ELFT> *>
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000118LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000119 std::vector<OutputSectionBase<ELFT> *> Ret;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000120
Eugene Leviante63d81b2016-07-20 14:43:20 +0000121 // Add input section to output section. If there is no output section yet,
122 // then create it and add to output section list.
Rui Ueyama6b274812016-07-25 22:51:07 +0000123 auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000124 OutputSectionBase<ELFT> *Sec;
125 bool IsNew;
126 std::tie(Sec, IsNew) = Factory.create(C, Name);
127 if (IsNew)
Rui Ueyama6b274812016-07-25 22:51:07 +0000128 Ret.push_back(Sec);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000129 Sec->addSection(C);
130 };
131
Rui Ueyama6b274812016-07-25 22:51:07 +0000132 for (auto &P : getSectionMap()) {
133 StringRef OutputName = P.first;
Davide Italianoe7282792016-07-27 01:44:01 +0000134 const InputSectionDescription *I = P.second;
Rui Ueyamaad10c3d2016-07-28 21:05:04 +0000135 for (InputSectionBase<ELFT> *S : getInputSections(I)) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000136 if (OutputName == "/DISCARD/") {
137 S->Live = false;
138 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000139 continue;
George Rimareea31142016-07-21 14:26:59 +0000140 }
Rui Ueyama6b274812016-07-25 22:51:07 +0000141 Add(S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000142 }
143 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000144
145 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000146 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
147 Symtab<ELFT>::X->getObjectFiles())
148 for (InputSectionBase<ELFT> *S : F->getSections())
149 if (!isDiscarded(S) && !S->OutSec)
150 Add(S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000151
Rui Ueyama3c291e12016-07-25 21:30:00 +0000152 // Remove from the output all the sections which did not meet
153 // the optional constraints.
Rui Ueyama6b274812016-07-25 22:51:07 +0000154 return filter(Ret);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000155}
156
157// Process ONLY_IF_RO and ONLY_IF_RW.
158template <class ELFT>
159std::vector<OutputSectionBase<ELFT> *>
160LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000161 // In this loop, we remove output sections if they don't satisfy
162 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000163 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
164 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
165 if (!Cmd || Cmd->Name == "/DISCARD/")
166 continue;
167
George Rimarbfc4a4b2016-07-26 10:47:09 +0000168 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000169 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000170
171 auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
172 return S->getName() == Cmd->Name;
173 });
174 if (It == Sections.end())
175 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000176
177 OutputSectionBase<ELFT> *Sec = *It;
178 bool Writable = (Sec->getFlags() & SHF_WRITE);
179 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
180 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
181
182 if ((RO && Writable) || (RW && !Writable)) {
183 Sections.erase(It);
184 continue;
185 }
Rui Ueyama3c291e12016-07-25 21:30:00 +0000186 }
187 return Sections;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000188}
189
190template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000191void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
Rui Ueyama708019c2016-07-24 18:19:40 +0000192 uint64_t Val = Cmd->Expression(Dot);
George Rimar10e576e2016-07-21 16:07:40 +0000193 if (Cmd->Name == ".") {
194 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000195 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000196 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
197 D->Value = Val;
198 }
199}
200
201template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000202void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000203 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000204 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000205 // are not explicitly placed into the output file by the linker script.
206 // We place orphan sections at end of file.
207 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000208 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000209 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000210 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000211 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000212 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000213 }
George Rimar652852c2016-04-16 10:10:32 +0000214
Rui Ueyama7c18c282016-04-18 21:00:40 +0000215 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000216 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000217 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000218 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000219
George Rimar076fe152016-07-21 06:43:01 +0000220 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
221 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000222 dispatchAssignment(Cmd);
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
George Rimar076fe152016-07-21 06:43:01 +0000364template <class ELFT> void LinkerScript<ELFT>::addScriptedSymbols() {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000365 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
366 auto *Cmd = dyn_cast<SymbolAssignment>(Base.get());
367 if (!Cmd || Cmd->Name == ".")
368 continue;
369
Davide Italiano8ab41082016-07-23 22:09:04 +0000370 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Davide Italiano373a5332016-07-25 00:25:18 +0000371 // The semantic of PROVIDE is that of introducing a symbol only if
372 // it's not defined and there's at least a reference to it.
373 if ((!B && !Cmd->Provide) || (B && B->isUndefined()))
Eugene Levianta31c91b2016-07-22 07:38:40 +0000374 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
375 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
376 else
377 // Symbol already exists in symbol table. If it is provided
378 // then we can't override its value.
379 Cmd->Ignore = Cmd->Provide;
380 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000381}
382
Eugene Leviantbbe38602016-07-19 09:25:43 +0000383template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
384 return !Opt.PhdrsCommands.empty();
385}
386
387// Returns indices of ELF headers containing specific section, identified
388// by Name. Each index is a zero based number of ELF header listed within
389// PHDRS {} script block.
390template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000391std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000392 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
393 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000394 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000395 continue;
396
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000397 std::vector<size_t> Ret;
398 for (StringRef PhdrName : Cmd->Phdrs)
399 Ret.push_back(getPhdrIndex(PhdrName));
400 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000401 }
George Rimar31d842f2016-07-20 16:43:03 +0000402 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000403}
404
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000405template <class ELFT>
406size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
407 size_t I = 0;
408 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
409 if (Cmd.Name == PhdrName)
410 return I;
411 ++I;
412 }
413 error("section header '" + PhdrName + "' is not listed in PHDRS");
414 return 0;
415}
416
Rui Ueyama07320e42016-04-20 20:13:41 +0000417class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000418 typedef void (ScriptParser::*Handler)();
419
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000420public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000421 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000422
Rui Ueyama4a465392016-04-22 22:59:24 +0000423 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000424
425private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000426 void addFile(StringRef Path);
427
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000428 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000429 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000430 void readExtern();
Davide Italianoe7282792016-07-27 01:44:01 +0000431 std::unique_ptr<InputSectionDescription> readFilePattern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000432 void readGroup();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000433 void readKeep(OutputSectionCommand *Cmd);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000434 void readInclude();
George Rimarc3794e52016-02-24 09:21:47 +0000435 void readNothing() {}
Rui Ueyamaee592822015-10-07 00:25:09 +0000436 void readOutput();
Davide Italiano9159ce92015-10-12 21:50:08 +0000437 void readOutputArch();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000438 void readOutputFormat();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000439 void readPhdrs();
Davide Italiano68a39a62015-10-08 17:51:41 +0000440 void readSearchDir();
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000441 void readSections();
442
Rui Ueyama113cdec2016-07-24 23:05:57 +0000443 SymbolAssignment *readAssignment(StringRef Name);
Eugene Levianteda81a12016-07-12 06:39:48 +0000444 void readOutputSectionDescription(StringRef OutSec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000445 std::vector<StringRef> readOutputSectionPhdrs();
446 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000447 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000448 void readAlign(OutputSectionCommand *Cmd);
George Rimar03fc0102016-07-28 07:18:23 +0000449 void readSort();
Rui Ueyama708019c2016-07-24 18:19:40 +0000450
451 Expr readExpr();
452 Expr readExpr1(Expr Lhs, int MinPrec);
453 Expr readPrimary();
454 Expr readTernary(Expr Cond);
455 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000456
George Rimarc3794e52016-02-24 09:21:47 +0000457 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000458 ScriptConfiguration &Opt = *ScriptConfig;
459 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000460 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000461};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000462
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000463const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000464 {"ENTRY", &ScriptParser::readEntry},
465 {"EXTERN", &ScriptParser::readExtern},
466 {"GROUP", &ScriptParser::readGroup},
467 {"INCLUDE", &ScriptParser::readInclude},
468 {"INPUT", &ScriptParser::readGroup},
469 {"OUTPUT", &ScriptParser::readOutput},
470 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
471 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000472 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000473 {"SEARCH_DIR", &ScriptParser::readSearchDir},
474 {"SECTIONS", &ScriptParser::readSections},
475 {";", &ScriptParser::readNothing}};
476
Rui Ueyama717677a2016-02-11 21:17:59 +0000477void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000478 while (!atEOF()) {
479 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000480 if (Handler Fn = Cmd.lookup(Tok))
481 (this->*Fn)();
482 else
George Rimar57610422016-03-11 14:43:02 +0000483 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000484 }
485}
486
Rui Ueyama717677a2016-02-11 21:17:59 +0000487void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000488 if (IsUnderSysroot && S.startswith("/")) {
489 SmallString<128> Path;
490 (Config->Sysroot + S).toStringRef(Path);
491 if (sys::fs::exists(Path)) {
492 Driver->addFile(Saver.save(Path.str()));
493 return;
494 }
495 }
496
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000497 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000498 Driver->addFile(S);
499 } else if (S.startswith("=")) {
500 if (Config->Sysroot.empty())
501 Driver->addFile(S.substr(1));
502 else
503 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
504 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000505 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000506 } else if (sys::fs::exists(S)) {
507 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000508 } else {
509 std::string Path = findFromSearchPaths(S);
510 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000511 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000512 else
513 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000514 }
515}
516
Rui Ueyama717677a2016-02-11 21:17:59 +0000517void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000518 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000519 bool Orig = Config->AsNeeded;
520 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000521 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000522 StringRef Tok = next();
523 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000524 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000525 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000526 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000527 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000528}
529
Rui Ueyama717677a2016-02-11 21:17:59 +0000530void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000531 // -e <symbol> takes predecence over ENTRY(<symbol>).
532 expect("(");
533 StringRef Tok = next();
534 if (Config->Entry.empty())
535 Config->Entry = Tok;
536 expect(")");
537}
538
Rui Ueyama717677a2016-02-11 21:17:59 +0000539void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000540 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000541 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000542 StringRef Tok = next();
543 if (Tok == ")")
544 return;
545 Config->Undefined.push_back(Tok);
546 }
547}
548
Rui Ueyama717677a2016-02-11 21:17:59 +0000549void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000550 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000551 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000552 StringRef Tok = next();
553 if (Tok == ")")
554 return;
555 if (Tok == "AS_NEEDED") {
556 readAsNeeded();
557 continue;
558 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000559 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000560 }
561}
562
Rui Ueyama717677a2016-02-11 21:17:59 +0000563void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000564 StringRef Tok = next();
565 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000566 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000567 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000568 return;
569 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000570 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000571 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
572 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000573 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000574}
575
Rui Ueyama717677a2016-02-11 21:17:59 +0000576void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000577 // -o <file> takes predecence over OUTPUT(<file>).
578 expect("(");
579 StringRef Tok = next();
580 if (Config->OutputFile.empty())
581 Config->OutputFile = Tok;
582 expect(")");
583}
584
Rui Ueyama717677a2016-02-11 21:17:59 +0000585void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000586 // Error checking only for now.
587 expect("(");
588 next();
589 expect(")");
590}
591
Rui Ueyama717677a2016-02-11 21:17:59 +0000592void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000593 // Error checking only for now.
594 expect("(");
595 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000596 StringRef Tok = next();
597 if (Tok == ")")
598 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000599 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000600 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000601 return;
602 }
Davide Italiano6836c612015-10-12 21:08:41 +0000603 next();
604 expect(",");
605 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000606 expect(")");
607}
608
Eugene Leviantbbe38602016-07-19 09:25:43 +0000609void ScriptParser::readPhdrs() {
610 expect("{");
611 while (!Error && !skip("}")) {
612 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000613 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000614 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
615
616 PhdrCmd.Type = readPhdrType();
617 do {
618 Tok = next();
619 if (Tok == ";")
620 break;
621 if (Tok == "FILEHDR")
622 PhdrCmd.HasFilehdr = true;
623 else if (Tok == "PHDRS")
624 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000625 else if (Tok == "FLAGS") {
626 expect("(");
627 next().getAsInteger(0, PhdrCmd.Flags);
628 expect(")");
629 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000630 setError("unexpected header attribute: " + Tok);
631 } while (!Error);
632 }
633}
634
Rui Ueyama717677a2016-02-11 21:17:59 +0000635void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000636 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000637 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000638 expect(")");
639}
640
Rui Ueyama717677a2016-02-11 21:17:59 +0000641void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000642 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000643 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000644 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000645 StringRef Tok = next();
George Rimar30835ea2016-07-28 21:08:56 +0000646 if (peek() == "=" || peek() == "+=") {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000647 readAssignment(Tok);
648 expect(";");
649 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000650 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000651 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000652 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000653 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000654 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000655 }
George Rimar652852c2016-04-16 10:10:32 +0000656 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000657}
658
Rui Ueyama708019c2016-07-24 18:19:40 +0000659static int precedence(StringRef Op) {
660 return StringSwitch<int>(Op)
661 .Case("*", 4)
662 .Case("/", 4)
663 .Case("+", 3)
664 .Case("-", 3)
665 .Case("<", 2)
666 .Case(">", 2)
667 .Case(">=", 2)
668 .Case("<=", 2)
669 .Case("==", 2)
670 .Case("!=", 2)
671 .Case("&", 1)
672 .Default(-1);
673}
674
Davide Italianoe7282792016-07-27 01:44:01 +0000675std::unique_ptr<InputSectionDescription> ScriptParser::readFilePattern() {
Davide Italiano0ed42b02016-07-25 21:47:13 +0000676 expect("*");
677 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000678
679 auto InCmd = llvm::make_unique<InputSectionDescription>();
680
681 if (skip("EXCLUDE_FILE")) {
682 expect("(");
683 while (!Error && !skip(")"))
684 InCmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000685 InCmd->Patterns.push_back(next());
Davide Italianoe7282792016-07-27 01:44:01 +0000686 expect(")");
687 } else {
688 while (!Error && !skip(")"))
689 InCmd->Patterns.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000690 }
Davide Italianoe7282792016-07-27 01:44:01 +0000691 return InCmd;
692}
693
694void ScriptParser::readKeep(OutputSectionCommand *Cmd) {
695 expect("(");
696 std::unique_ptr<InputSectionDescription> InCmd = readFilePattern();
697 Opt.KeptSections.insert(Opt.KeptSections.end(), InCmd->Patterns.begin(),
698 InCmd->Patterns.end());
699 Cmd->Commands.push_back(std::move(InCmd));
Davide Italiano0ed42b02016-07-25 21:47:13 +0000700 expect(")");
701}
702
George Rimar630c6172016-07-26 18:06:29 +0000703void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
704 expect("(");
705 Cmd->AlignExpr = readExpr();
706 expect(")");
707}
708
George Rimar03fc0102016-07-28 07:18:23 +0000709void ScriptParser::readSort() {
710 expect("(");
711 expect("CONSTRUCTORS");
712 expect(")");
713}
714
Eugene Levianteda81a12016-07-12 06:39:48 +0000715void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000716 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
717 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000718
719 // Read an address expression.
720 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
721 if (peek() != ":")
722 Cmd->AddrExpr = readExpr();
723
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000724 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000725
George Rimar630c6172016-07-26 18:06:29 +0000726 if (skip("ALIGN"))
727 readAlign(Cmd);
728
Davide Italiano246f6812016-07-22 03:36:24 +0000729 // Parse constraints.
730 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000731 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000732 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000733 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000734 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000735
Rui Ueyama025d59b2016-02-02 20:27:59 +0000736 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000737 StringRef Tok = next();
738 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000739 auto *InCmd = new InputSectionDescription();
740 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000741 expect("(");
742 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000743 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000744 } else if (Tok == "KEEP") {
Davide Italiano0ed42b02016-07-25 21:47:13 +0000745 readKeep(Cmd);
Davide Italiano054a6792016-07-24 23:13:48 +0000746 } else if (Tok == "PROVIDE") {
747 readProvide(false);
748 } else if (Tok == "PROVIDE_HIDDEN") {
749 readProvide(true);
George Rimar03fc0102016-07-28 07:18:23 +0000750 } else if (Tok == "SORT") {
751 readSort();
George Rimar481c2ce2016-02-23 07:47:54 +0000752 } else {
George Rimar777f9632016-03-12 08:31:34 +0000753 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000754 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000755 }
George Rimar076fe152016-07-21 06:43:01 +0000756 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000757
George Rimare2ee72b2016-02-26 14:48:31 +0000758 StringRef Tok = peek();
759 if (Tok.startswith("=")) {
760 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000761 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000762 return;
763 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000764 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000765 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000766 next();
767 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000768}
769
Eugene Levianta31c91b2016-07-22 07:38:40 +0000770void ScriptParser::readProvide(bool Hidden) {
771 expect("(");
Rui Ueyama113cdec2016-07-24 23:05:57 +0000772 if (SymbolAssignment *Assignment = readAssignment(next())) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000773 Assignment->Provide = true;
774 Assignment->Hidden = Hidden;
775 }
776 expect(")");
777 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000778}
779
George Rimar30835ea2016-07-28 21:08:56 +0000780static uint64_t getSymbolValue(StringRef S, uint64_t Dot) {
781 if (S == ".")
782 return Dot;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000783
George Rimara9c5a522016-07-26 18:18:58 +0000784 switch (Config->EKind) {
785 case ELF32LEKind:
786 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
787 return B->getVA<ELF32LE>();
788 break;
789 case ELF32BEKind:
790 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
791 return B->getVA<ELF32BE>();
792 break;
793 case ELF64LEKind:
794 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
795 return B->getVA<ELF64LE>();
796 break;
797 case ELF64BEKind:
798 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
799 return B->getVA<ELF64BE>();
800 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000801 default:
George Rimarb567b622016-07-26 18:46:13 +0000802 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000803 }
804 error("symbol not found: " + S);
805 return 0;
806}
807
George Rimar30835ea2016-07-28 21:08:56 +0000808SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
809 StringRef Op = next();
810 assert(Op == "=" || Op == "+=");
811 Expr E = readExpr();
812 if (Op == "+=")
813 E = [=](uint64_t Dot) { return getSymbolValue(Name, Dot) + E(Dot); };
814 auto *Cmd = new SymbolAssignment(Name, E);
815 Opt.Commands.emplace_back(Cmd);
816 return Cmd;
817}
818
819// This is an operator-precedence parser to parse a linker
820// script expression.
821Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
822
Rui Ueyama708019c2016-07-24 18:19:40 +0000823// This is a part of the operator-precedence parser. This function
824// assumes that the remaining token stream starts with an operator.
825Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
826 while (!atEOF() && !Error) {
827 // Read an operator and an expression.
828 StringRef Op1 = peek();
829 if (Op1 == "?")
830 return readTernary(Lhs);
831 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000832 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000833 next();
834 Expr Rhs = readPrimary();
835
836 // Evaluate the remaining part of the expression first if the
837 // next operator has greater precedence than the previous one.
838 // For example, if we have read "+" and "3", and if the next
839 // operator is "*", then we'll evaluate 3 * ... part first.
840 while (!atEOF()) {
841 StringRef Op2 = peek();
842 if (precedence(Op2) <= precedence(Op1))
843 break;
844 Rhs = readExpr1(Rhs, precedence(Op2));
845 }
846
847 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000848 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000849 return Lhs;
850}
851
852uint64_t static getConstant(StringRef S) {
853 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
854 return Target->PageSize;
855 error("unknown constant: " + S);
856 return 0;
857}
858
859Expr ScriptParser::readPrimary() {
860 StringRef Tok = next();
861
Rui Ueyama708019c2016-07-24 18:19:40 +0000862 if (Tok == "(") {
863 Expr E = readExpr();
864 expect(")");
865 return E;
866 }
867
868 // Built-in functions are parsed here.
869 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
870 if (Tok == "ALIGN") {
871 expect("(");
872 Expr E = readExpr();
873 expect(")");
874 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
875 }
876 if (Tok == "CONSTANT") {
877 expect("(");
878 StringRef Tok = next();
879 expect(")");
880 return [=](uint64_t Dot) { return getConstant(Tok); };
881 }
Rafael Espindola54c145c2016-07-28 18:16:24 +0000882 if (Tok == "SEGMENT_START") {
883 expect("(");
884 next();
885 expect(",");
886 uint64_t Val;
887 next().getAsInteger(0, Val);
888 expect(")");
889 return [=](uint64_t Dot) { return Val; };
890 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000891 if (Tok == "DATA_SEGMENT_ALIGN") {
892 expect("(");
893 Expr E = readExpr();
894 expect(",");
895 readExpr();
896 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +0000897 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +0000898 }
899 if (Tok == "DATA_SEGMENT_END") {
900 expect("(");
901 expect(".");
902 expect(")");
903 return [](uint64_t Dot) { return Dot; };
904 }
George Rimar276b4e62016-07-26 17:58:44 +0000905 // GNU linkers implements more complicated logic to handle
906 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
907 // the next page boundary for simplicity.
908 if (Tok == "DATA_SEGMENT_RELRO_END") {
909 expect("(");
910 next();
911 expect(",");
912 readExpr();
913 expect(")");
914 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
915 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000916
George Rimara9c5a522016-07-26 18:18:58 +0000917 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +0000918 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +0000919 if (Tok.getAsInteger(0, V)) {
George Rimar30835ea2016-07-28 21:08:56 +0000920 if (Tok != "." && !isValidCIdentifier(Tok))
George Rimara9c5a522016-07-26 18:18:58 +0000921 setError("malformed number: " + Tok);
George Rimar30835ea2016-07-28 21:08:56 +0000922 return [=](uint64_t Dot) { return getSymbolValue(Tok, Dot); };
George Rimara9c5a522016-07-26 18:18:58 +0000923 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000924 return [=](uint64_t Dot) { return V; };
925}
926
927Expr ScriptParser::readTernary(Expr Cond) {
928 next();
929 Expr L = readExpr();
930 expect(":");
931 Expr R = readExpr();
932 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
933}
934
935Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
936 if (Op == "*")
937 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
938 if (Op == "/") {
939 return [=](uint64_t Dot) -> uint64_t {
940 uint64_t RHS = R(Dot);
941 if (RHS == 0) {
942 error("division by zero");
943 return 0;
944 }
945 return L(Dot) / RHS;
946 };
947 }
948 if (Op == "+")
949 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
950 if (Op == "-")
951 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
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 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000967}
968
Eugene Leviantbbe38602016-07-19 09:25:43 +0000969std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
970 std::vector<StringRef> Phdrs;
971 while (!Error && peek().startswith(":")) {
972 StringRef Tok = next();
973 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
974 if (Tok.empty()) {
975 setError("section header name is empty");
976 break;
977 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000978 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000979 }
980 return Phdrs;
981}
982
983unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000984 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000985 unsigned Ret = StringSwitch<unsigned>(Tok)
986 .Case("PT_NULL", PT_NULL)
987 .Case("PT_LOAD", PT_LOAD)
988 .Case("PT_DYNAMIC", PT_DYNAMIC)
989 .Case("PT_INTERP", PT_INTERP)
990 .Case("PT_NOTE", PT_NOTE)
991 .Case("PT_SHLIB", PT_SHLIB)
992 .Case("PT_PHDR", PT_PHDR)
993 .Case("PT_TLS", PT_TLS)
994 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
995 .Case("PT_GNU_STACK", PT_GNU_STACK)
996 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
997 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000998
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000999 if (Ret == (unsigned)-1) {
1000 setError("invalid program header type: " + Tok);
1001 return PT_NULL;
1002 }
1003 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001004}
1005
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001006static bool isUnderSysroot(StringRef Path) {
1007 if (Config->Sysroot == "")
1008 return false;
1009 for (; !Path.empty(); Path = sys::path::parent_path(Path))
1010 if (sys::fs::equivalent(Config->Sysroot, Path))
1011 return true;
1012 return false;
1013}
1014
Rui Ueyama07320e42016-04-20 20:13:41 +00001015// Entry point.
1016void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +00001017 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +00001018 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +00001019}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +00001020
Rui Ueyama07320e42016-04-20 20:13:41 +00001021template class elf::LinkerScript<ELF32LE>;
1022template class elf::LinkerScript<ELF32BE>;
1023template class elf::LinkerScript<ELF64LE>;
1024template class elf::LinkerScript<ELF64BE>;