blob: 0c54de24fae19afddc5bff062444c74c9b15a15f [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> *>
Davide Italianoe7282792016-07-27 01:44:01 +000098LinkerScript<ELFT>::getInputSections(const InputSectionDescription *I) {
99 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);
Rui Ueyama6b274812016-07-25 22:51:07 +0000109 return Ret;
110}
111
George Rimar652852c2016-04-16 10:10:32 +0000112template <class ELFT>
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000113std::vector<OutputSectionBase<ELFT> *>
Eugene Leviante63d81b2016-07-20 14:43:20 +0000114LinkerScript<ELFT>::createSections(OutputSectionFactory<ELFT> &Factory) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000115 std::vector<OutputSectionBase<ELFT> *> Ret;
Rui Ueyamaa7f78842016-07-20 17:19:03 +0000116
Eugene Leviante63d81b2016-07-20 14:43:20 +0000117 // Add input section to output section. If there is no output section yet,
118 // then create it and add to output section list.
Rui Ueyama6b274812016-07-25 22:51:07 +0000119 auto Add = [&](InputSectionBase<ELFT> *C, StringRef Name) {
Eugene Leviante63d81b2016-07-20 14:43:20 +0000120 OutputSectionBase<ELFT> *Sec;
121 bool IsNew;
122 std::tie(Sec, IsNew) = Factory.create(C, Name);
123 if (IsNew)
Rui Ueyama6b274812016-07-25 22:51:07 +0000124 Ret.push_back(Sec);
Eugene Leviante63d81b2016-07-20 14:43:20 +0000125 Sec->addSection(C);
126 };
127
Rui Ueyama6b274812016-07-25 22:51:07 +0000128 for (auto &P : getSectionMap()) {
129 StringRef OutputName = P.first;
Davide Italianoe7282792016-07-27 01:44:01 +0000130 const InputSectionDescription *I = P.second;
131 for (InputSectionBase<ELFT> *S : getInputSections(I)) {
Rui Ueyama6b274812016-07-25 22:51:07 +0000132 if (OutputName == "/DISCARD/") {
133 S->Live = false;
134 reportDiscarded(S);
George Rimareea31142016-07-21 14:26:59 +0000135 continue;
George Rimareea31142016-07-21 14:26:59 +0000136 }
Rui Ueyama6b274812016-07-25 22:51:07 +0000137 Add(S, OutputName);
George Rimareea31142016-07-21 14:26:59 +0000138 }
139 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000140
141 // Add all other input sections, which are not listed in script.
Rui Ueyama6b274812016-07-25 22:51:07 +0000142 for (const std::unique_ptr<ObjectFile<ELFT>> &F :
143 Symtab<ELFT>::X->getObjectFiles())
144 for (InputSectionBase<ELFT> *S : F->getSections())
145 if (!isDiscarded(S) && !S->OutSec)
146 Add(S, getOutputSectionName(S));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000147
Rui Ueyama3c291e12016-07-25 21:30:00 +0000148 // Remove from the output all the sections which did not meet
149 // the optional constraints.
Rui Ueyama6b274812016-07-25 22:51:07 +0000150 return filter(Ret);
Rui Ueyama3c291e12016-07-25 21:30:00 +0000151}
152
153// Process ONLY_IF_RO and ONLY_IF_RW.
154template <class ELFT>
155std::vector<OutputSectionBase<ELFT> *>
156LinkerScript<ELFT>::filter(std::vector<OutputSectionBase<ELFT> *> &Sections) {
Rui Ueyama3c291e12016-07-25 21:30:00 +0000157 // In this loop, we remove output sections if they don't satisfy
158 // requested properties.
Rui Ueyama3c291e12016-07-25 21:30:00 +0000159 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
160 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
161 if (!Cmd || Cmd->Name == "/DISCARD/")
162 continue;
163
George Rimarbfc4a4b2016-07-26 10:47:09 +0000164 if (Cmd->Constraint == ConstraintKind::NoConstraint)
Rui Ueyama3c291e12016-07-25 21:30:00 +0000165 continue;
George Rimarbfc4a4b2016-07-26 10:47:09 +0000166
167 auto It = llvm::find_if(Sections, [&](OutputSectionBase<ELFT> *S) {
168 return S->getName() == Cmd->Name;
169 });
170 if (It == Sections.end())
171 continue;
Rui Ueyama3c291e12016-07-25 21:30:00 +0000172
173 OutputSectionBase<ELFT> *Sec = *It;
174 bool Writable = (Sec->getFlags() & SHF_WRITE);
175 bool RO = (Cmd->Constraint == ConstraintKind::ReadOnly);
176 bool RW = (Cmd->Constraint == ConstraintKind::ReadWrite);
177
178 if ((RO && Writable) || (RW && !Writable)) {
179 Sections.erase(It);
180 continue;
181 }
Rui Ueyama3c291e12016-07-25 21:30:00 +0000182 }
183 return Sections;
Eugene Leviante63d81b2016-07-20 14:43:20 +0000184}
185
186template <class ELFT>
George Rimar10e576e2016-07-21 16:07:40 +0000187void LinkerScript<ELFT>::dispatchAssignment(SymbolAssignment *Cmd) {
Rui Ueyama708019c2016-07-24 18:19:40 +0000188 uint64_t Val = Cmd->Expression(Dot);
George Rimar10e576e2016-07-21 16:07:40 +0000189 if (Cmd->Name == ".") {
190 Dot = Val;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000191 } else if (!Cmd->Ignore) {
George Rimar10e576e2016-07-21 16:07:40 +0000192 auto *D = cast<DefinedRegular<ELFT>>(Symtab<ELFT>::X->find(Cmd->Name));
193 D->Value = Val;
194 }
195}
196
197template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000198void LinkerScript<ELFT>::assignAddresses(
George Rimardbbd8b12016-04-21 11:21:48 +0000199 ArrayRef<OutputSectionBase<ELFT> *> Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000200 // Orphan sections are sections present in the input files which
Rui Ueyama7c18c282016-04-18 21:00:40 +0000201 // are not explicitly placed into the output file by the linker script.
202 // We place orphan sections at end of file.
203 // Other linkers places them using some heuristics as described in
George Rimar652852c2016-04-16 10:10:32 +0000204 // https://sourceware.org/binutils/docs/ld/Orphan-Sections.html#Orphan-Sections.
Rui Ueyama7c18c282016-04-18 21:00:40 +0000205 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar652852c2016-04-16 10:10:32 +0000206 StringRef Name = Sec->getName();
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000207 if (getSectionIndex(Name) == INT_MAX)
George Rimar076fe152016-07-21 06:43:01 +0000208 Opt.Commands.push_back(llvm::make_unique<OutputSectionCommand>(Name));
George Rimar652852c2016-04-16 10:10:32 +0000209 }
George Rimar652852c2016-04-16 10:10:32 +0000210
Rui Ueyama7c18c282016-04-18 21:00:40 +0000211 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rui Ueyama52c4e172016-07-01 10:42:25 +0000212 Dot = Out<ELFT>::ElfHeader->getSize() + Out<ELFT>::ProgramHeaders->getSize();
Eugene Leviant467c4d52016-07-01 10:27:36 +0000213 uintX_t MinVA = std::numeric_limits<uintX_t>::max();
George Rimar652852c2016-04-16 10:10:32 +0000214 uintX_t ThreadBssOffset = 0;
George Rimar652852c2016-04-16 10:10:32 +0000215
George Rimar076fe152016-07-21 06:43:01 +0000216 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
217 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base.get())) {
George Rimar10e576e2016-07-21 16:07:40 +0000218 dispatchAssignment(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000219 continue;
220 }
221
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000222 // Find all the sections with required name. There can be more than
George Rimar6ad330a2016-07-19 07:39:07 +0000223 // one section with such name, if the alignment, flags or type
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000224 // attribute differs.
George Rimar076fe152016-07-21 06:43:01 +0000225 auto *Cmd = cast<OutputSectionCommand>(Base.get());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000226 for (OutputSectionBase<ELFT> *Sec : Sections) {
George Rimar076fe152016-07-21 06:43:01 +0000227 if (Sec->getName() != Cmd->Name)
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000228 continue;
George Rimar652852c2016-04-16 10:10:32 +0000229
George Rimar58e5c4d2016-07-25 08:29:46 +0000230 if (Cmd->AddrExpr)
231 Dot = Cmd->AddrExpr(Dot);
232
George Rimar630c6172016-07-26 18:06:29 +0000233 if (Cmd->AlignExpr)
234 Sec->updateAlignment(Cmd->AlignExpr(Dot));
235
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000236 if ((Sec->getFlags() & SHF_TLS) && Sec->getType() == SHT_NOBITS) {
237 uintX_t TVA = Dot + ThreadBssOffset;
Rui Ueyama424b4082016-06-17 01:18:46 +0000238 TVA = alignTo(TVA, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000239 Sec->setVA(TVA);
240 ThreadBssOffset = TVA - Dot + Sec->getSize();
241 continue;
242 }
George Rimar652852c2016-04-16 10:10:32 +0000243
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000244 if (Sec->getFlags() & SHF_ALLOC) {
Rui Ueyama424b4082016-06-17 01:18:46 +0000245 Dot = alignTo(Dot, Sec->getAlignment());
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000246 Sec->setVA(Dot);
Rui Ueyama52c4e172016-07-01 10:42:25 +0000247 MinVA = std::min(MinVA, Dot);
Dima Stepanovfb8978f2016-05-19 18:15:54 +0000248 Dot += Sec->getSize();
249 continue;
250 }
George Rimar652852c2016-04-16 10:10:32 +0000251 }
252 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000253
Rafael Espindola64c32d62016-07-07 14:28:47 +0000254 // ELF and Program headers need to be right before the first section in
George Rimarb91e7112016-07-19 07:42:07 +0000255 // memory. Set their addresses accordingly.
Eugene Leviant467c4d52016-07-01 10:27:36 +0000256 MinVA = alignDown(MinVA - Out<ELFT>::ElfHeader->getSize() -
257 Out<ELFT>::ProgramHeaders->getSize(),
258 Target->PageSize);
259 Out<ELFT>::ElfHeader->setVA(MinVA);
260 Out<ELFT>::ProgramHeaders->setVA(Out<ELFT>::ElfHeader->getSize() + MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000261}
262
Rui Ueyama07320e42016-04-20 20:13:41 +0000263template <class ELFT>
Rafael Espindola74df5c72016-07-19 12:33:46 +0000264std::vector<PhdrEntry<ELFT>>
Eugene Leviantbbe38602016-07-19 09:25:43 +0000265LinkerScript<ELFT>::createPhdrs(ArrayRef<OutputSectionBase<ELFT> *> Sections) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000266 std::vector<PhdrEntry<ELFT>> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000267
268 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000269 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
270 PhdrEntry<ELFT> &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000271
272 if (Cmd.HasFilehdr)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000273 Phdr.add(Out<ELFT>::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000274 if (Cmd.HasPhdrs)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000275 Phdr.add(Out<ELFT>::ProgramHeaders);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000276
277 switch (Cmd.Type) {
278 case PT_INTERP:
Rui Ueyamafd03cfd2016-07-21 11:01:23 +0000279 if (Out<ELFT>::Interp)
Rui Ueyamaadca2452016-07-23 14:18:48 +0000280 Phdr.add(Out<ELFT>::Interp);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000281 break;
282 case PT_DYNAMIC:
283 if (isOutputDynamic<ELFT>()) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000284 Phdr.H.p_flags = Out<ELFT>::Dynamic->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000285 Phdr.add(Out<ELFT>::Dynamic);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000286 }
287 break;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000288 case PT_GNU_EH_FRAME:
289 if (!Out<ELFT>::EhFrame->empty() && Out<ELFT>::EhFrameHdr) {
Rafael Espindola0b113672016-07-27 14:10:56 +0000290 Phdr.H.p_flags = Out<ELFT>::EhFrameHdr->getPhdrFlags();
Rui Ueyamaadca2452016-07-23 14:18:48 +0000291 Phdr.add(Out<ELFT>::EhFrameHdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000292 }
293 break;
294 }
295 }
296
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000297 PhdrEntry<ELFT> *Load = nullptr;
298 uintX_t Flags = PF_R;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000299 for (OutputSectionBase<ELFT> *Sec : Sections) {
300 if (!(Sec->getFlags() & SHF_ALLOC))
301 break;
302
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000303 std::vector<size_t> PhdrIds = getPhdrIndices(Sec->getName());
Eugene Leviantbbe38602016-07-19 09:25:43 +0000304 if (!PhdrIds.empty()) {
305 // Assign headers specified by linker script
306 for (size_t Id : PhdrIds) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000307 Ret[Id].add(Sec);
Eugene Leviant865bf862016-07-21 10:43:25 +0000308 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola0b113672016-07-27 14:10:56 +0000309 Ret[Id].H.p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000310 }
311 } else {
312 // If we have no load segment or flags've changed then we want new load
313 // segment.
Rafael Espindola0b113672016-07-27 14:10:56 +0000314 uintX_t NewFlags = Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000315 if (Load == nullptr || Flags != NewFlags) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000316 Load = &*Ret.emplace(Ret.end(), PT_LOAD, NewFlags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000317 Flags = NewFlags;
318 }
Rui Ueyama18f084f2016-07-20 19:36:41 +0000319 Load->add(Sec);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000320 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000321 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000322 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000323}
324
325template <class ELFT>
Rui Ueyama07320e42016-04-20 20:13:41 +0000326ArrayRef<uint8_t> LinkerScript<ELFT>::getFiller(StringRef Name) {
George Rimarf6c3cce2016-07-21 07:48:54 +0000327 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands)
328 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
329 if (Cmd->Name == Name)
330 return Cmd->Filler;
331 return {};
George Rimare2ee72b2016-02-26 14:48:31 +0000332}
333
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000334// Returns the index of the given section name in linker script
335// SECTIONS commands. Sections are laid out as the same order as they
336// were in the script. If a given name did not appear in the script,
337// it returns INT_MAX, so that it will be laid out at end of file.
George Rimar076fe152016-07-21 06:43:01 +0000338template <class ELFT> int LinkerScript<ELFT>::getSectionIndex(StringRef Name) {
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000339 int I = 0;
340 for (std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
341 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get()))
342 if (Cmd->Name == Name)
343 return I;
344 ++I;
345 }
346 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000347}
348
349// A compartor to sort output sections. Returns -1 or 1 if
350// A or B are mentioned in linker script. Otherwise, returns 0.
Rui Ueyama07320e42016-04-20 20:13:41 +0000351template <class ELFT>
352int LinkerScript<ELFT>::compareSections(StringRef A, StringRef B) {
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000353 int I = getSectionIndex(A);
354 int J = getSectionIndex(B);
355 if (I == INT_MAX && J == INT_MAX)
Rui Ueyama717677a2016-02-11 21:17:59 +0000356 return 0;
357 return I < J ? -1 : 1;
358}
359
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
Davide Italiano8ab41082016-07-23 22:09:04 +0000366 SymbolBody *B = Symtab<ELFT>::X->find(Cmd->Name);
Davide Italiano373a5332016-07-25 00:25:18 +0000367 // The semantic of PROVIDE is that of introducing a symbol only if
368 // it's not defined and there's at least a reference to it.
369 if ((!B && !Cmd->Provide) || (B && B->isUndefined()))
Eugene Levianta31c91b2016-07-22 07:38:40 +0000370 Symtab<ELFT>::X->addAbsolute(Cmd->Name,
371 Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT);
372 else
373 // Symbol already exists in symbol table. If it is provided
374 // then we can't override its value.
375 Cmd->Ignore = Cmd->Provide;
376 }
Eugene Levianteda81a12016-07-12 06:39:48 +0000377}
378
Eugene Leviantbbe38602016-07-19 09:25:43 +0000379template <class ELFT> bool LinkerScript<ELFT>::hasPhdrsCommands() {
380 return !Opt.PhdrsCommands.empty();
381}
382
383// Returns indices of ELF headers containing specific section, identified
384// by Name. Each index is a zero based number of ELF header listed within
385// PHDRS {} script block.
386template <class ELFT>
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000387std::vector<size_t> LinkerScript<ELFT>::getPhdrIndices(StringRef SectionName) {
George Rimar076fe152016-07-21 06:43:01 +0000388 for (const std::unique_ptr<BaseCommand> &Base : Opt.Commands) {
389 auto *Cmd = dyn_cast<OutputSectionCommand>(Base.get());
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000390 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000391 continue;
392
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000393 std::vector<size_t> Ret;
394 for (StringRef PhdrName : Cmd->Phdrs)
395 Ret.push_back(getPhdrIndex(PhdrName));
396 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000397 }
George Rimar31d842f2016-07-20 16:43:03 +0000398 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000399}
400
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000401template <class ELFT>
402size_t LinkerScript<ELFT>::getPhdrIndex(StringRef PhdrName) {
403 size_t I = 0;
404 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
405 if (Cmd.Name == PhdrName)
406 return I;
407 ++I;
408 }
409 error("section header '" + PhdrName + "' is not listed in PHDRS");
410 return 0;
411}
412
Rui Ueyama07320e42016-04-20 20:13:41 +0000413class elf::ScriptParser : public ScriptParserBase {
George Rimarc3794e52016-02-24 09:21:47 +0000414 typedef void (ScriptParser::*Handler)();
415
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000416public:
Rui Ueyama07320e42016-04-20 20:13:41 +0000417 ScriptParser(StringRef S, bool B) : ScriptParserBase(S), IsUnderSysroot(B) {}
George Rimarf23b2322016-02-19 10:45:45 +0000418
Rui Ueyama4a465392016-04-22 22:59:24 +0000419 void run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000420
421private:
Rui Ueyama52a15092015-10-11 03:28:42 +0000422 void addFile(StringRef Path);
423
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000424 void readAsNeeded();
Denis Protivensky90c50992015-10-08 06:48:38 +0000425 void readEntry();
George Rimar83f406c2015-10-19 17:35:12 +0000426 void readExtern();
Davide Italianoe7282792016-07-27 01:44:01 +0000427 std::unique_ptr<InputSectionDescription> readFilePattern();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000428 void readGroup();
Davide Italiano0ed42b02016-07-25 21:47:13 +0000429 void readKeep(OutputSectionCommand *Cmd);
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);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000441 std::vector<StringRef> readOutputSectionPhdrs();
442 unsigned readPhdrType();
Eugene Levianta31c91b2016-07-22 07:38:40 +0000443 void readProvide(bool Hidden);
George Rimar630c6172016-07-26 18:06:29 +0000444 void readAlign(OutputSectionCommand *Cmd);
Rui Ueyama708019c2016-07-24 18:19:40 +0000445
446 Expr readExpr();
447 Expr readExpr1(Expr Lhs, int MinPrec);
448 Expr readPrimary();
449 Expr readTernary(Expr Cond);
450 Expr combine(StringRef Op, Expr Lhs, Expr Rhs);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000451
George Rimarc3794e52016-02-24 09:21:47 +0000452 const static StringMap<Handler> Cmd;
Rui Ueyama07320e42016-04-20 20:13:41 +0000453 ScriptConfiguration &Opt = *ScriptConfig;
454 StringSaver Saver = {ScriptConfig->Alloc};
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000455 bool IsUnderSysroot;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000456};
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000457
Rafael Espindolae0df00b2016-02-28 00:25:54 +0000458const StringMap<elf::ScriptParser::Handler> elf::ScriptParser::Cmd = {
George Rimarc3794e52016-02-24 09:21:47 +0000459 {"ENTRY", &ScriptParser::readEntry},
460 {"EXTERN", &ScriptParser::readExtern},
461 {"GROUP", &ScriptParser::readGroup},
462 {"INCLUDE", &ScriptParser::readInclude},
463 {"INPUT", &ScriptParser::readGroup},
464 {"OUTPUT", &ScriptParser::readOutput},
465 {"OUTPUT_ARCH", &ScriptParser::readOutputArch},
466 {"OUTPUT_FORMAT", &ScriptParser::readOutputFormat},
Eugene Leviantbbe38602016-07-19 09:25:43 +0000467 {"PHDRS", &ScriptParser::readPhdrs},
George Rimarc3794e52016-02-24 09:21:47 +0000468 {"SEARCH_DIR", &ScriptParser::readSearchDir},
469 {"SECTIONS", &ScriptParser::readSections},
470 {";", &ScriptParser::readNothing}};
471
Rui Ueyama717677a2016-02-11 21:17:59 +0000472void ScriptParser::run() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000473 while (!atEOF()) {
474 StringRef Tok = next();
George Rimarc3794e52016-02-24 09:21:47 +0000475 if (Handler Fn = Cmd.lookup(Tok))
476 (this->*Fn)();
477 else
George Rimar57610422016-03-11 14:43:02 +0000478 setError("unknown directive: " + Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000479 }
480}
481
Rui Ueyama717677a2016-02-11 21:17:59 +0000482void ScriptParser::addFile(StringRef S) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000483 if (IsUnderSysroot && S.startswith("/")) {
484 SmallString<128> Path;
485 (Config->Sysroot + S).toStringRef(Path);
486 if (sys::fs::exists(Path)) {
487 Driver->addFile(Saver.save(Path.str()));
488 return;
489 }
490 }
491
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +0000492 if (sys::path::is_absolute(S)) {
Rui Ueyama52a15092015-10-11 03:28:42 +0000493 Driver->addFile(S);
494 } else if (S.startswith("=")) {
495 if (Config->Sysroot.empty())
496 Driver->addFile(S.substr(1));
497 else
498 Driver->addFile(Saver.save(Config->Sysroot + "/" + S.substr(1)));
499 } else if (S.startswith("-l")) {
Rui Ueyama21eecb42016-02-02 21:13:09 +0000500 Driver->addLibrary(S.substr(2));
Simon Atanasyana1b8fc32015-11-26 20:23:46 +0000501 } else if (sys::fs::exists(S)) {
502 Driver->addFile(S);
Rui Ueyama52a15092015-10-11 03:28:42 +0000503 } else {
504 std::string Path = findFromSearchPaths(S);
505 if (Path.empty())
George Rimar777f9632016-03-12 08:31:34 +0000506 setError("unable to find " + S);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000507 else
508 Driver->addFile(Saver.save(Path));
Rui Ueyama52a15092015-10-11 03:28:42 +0000509 }
510}
511
Rui Ueyama717677a2016-02-11 21:17:59 +0000512void ScriptParser::readAsNeeded() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000513 expect("(");
Rui Ueyama35da9b62015-10-11 20:59:12 +0000514 bool Orig = Config->AsNeeded;
515 Config->AsNeeded = true;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000516 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000517 StringRef Tok = next();
518 if (Tok == ")")
Rui Ueyama35da9b62015-10-11 20:59:12 +0000519 break;
Rui Ueyama52a15092015-10-11 03:28:42 +0000520 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000521 }
Rui Ueyama35da9b62015-10-11 20:59:12 +0000522 Config->AsNeeded = Orig;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000523}
524
Rui Ueyama717677a2016-02-11 21:17:59 +0000525void ScriptParser::readEntry() {
Denis Protivensky90c50992015-10-08 06:48:38 +0000526 // -e <symbol> takes predecence over ENTRY(<symbol>).
527 expect("(");
528 StringRef Tok = next();
529 if (Config->Entry.empty())
530 Config->Entry = Tok;
531 expect(")");
532}
533
Rui Ueyama717677a2016-02-11 21:17:59 +0000534void ScriptParser::readExtern() {
George Rimar83f406c2015-10-19 17:35:12 +0000535 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000536 while (!Error) {
George Rimar83f406c2015-10-19 17:35:12 +0000537 StringRef Tok = next();
538 if (Tok == ")")
539 return;
540 Config->Undefined.push_back(Tok);
541 }
542}
543
Rui Ueyama717677a2016-02-11 21:17:59 +0000544void ScriptParser::readGroup() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000545 expect("(");
Rui Ueyama025d59b2016-02-02 20:27:59 +0000546 while (!Error) {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000547 StringRef Tok = next();
548 if (Tok == ")")
549 return;
550 if (Tok == "AS_NEEDED") {
551 readAsNeeded();
552 continue;
553 }
Rui Ueyama52a15092015-10-11 03:28:42 +0000554 addFile(Tok);
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000555 }
556}
557
Rui Ueyama717677a2016-02-11 21:17:59 +0000558void ScriptParser::readInclude() {
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000559 StringRef Tok = next();
560 auto MBOrErr = MemoryBuffer::getFile(Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000561 if (!MBOrErr) {
George Rimar57610422016-03-11 14:43:02 +0000562 setError("cannot open " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000563 return;
564 }
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000565 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamaa47ee682015-10-11 01:53:04 +0000566 StringRef S = Saver.save(MB->getMemBufferRef().getBuffer());
567 std::vector<StringRef> V = tokenize(S);
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000568 Tokens.insert(Tokens.begin() + Pos, V.begin(), V.end());
Rui Ueyama31aa1f82015-10-11 01:31:55 +0000569}
570
Rui Ueyama717677a2016-02-11 21:17:59 +0000571void ScriptParser::readOutput() {
Rui Ueyamaee592822015-10-07 00:25:09 +0000572 // -o <file> takes predecence over OUTPUT(<file>).
573 expect("(");
574 StringRef Tok = next();
575 if (Config->OutputFile.empty())
576 Config->OutputFile = Tok;
577 expect(")");
578}
579
Rui Ueyama717677a2016-02-11 21:17:59 +0000580void ScriptParser::readOutputArch() {
Davide Italiano9159ce92015-10-12 21:50:08 +0000581 // Error checking only for now.
582 expect("(");
583 next();
584 expect(")");
585}
586
Rui Ueyama717677a2016-02-11 21:17:59 +0000587void ScriptParser::readOutputFormat() {
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000588 // Error checking only for now.
589 expect("(");
590 next();
Davide Italiano6836c612015-10-12 21:08:41 +0000591 StringRef Tok = next();
592 if (Tok == ")")
593 return;
Rui Ueyama025d59b2016-02-02 20:27:59 +0000594 if (Tok != ",") {
George Rimar57610422016-03-11 14:43:02 +0000595 setError("unexpected token: " + Tok);
Rui Ueyama025d59b2016-02-02 20:27:59 +0000596 return;
597 }
Davide Italiano6836c612015-10-12 21:08:41 +0000598 next();
599 expect(",");
600 next();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000601 expect(")");
602}
603
Eugene Leviantbbe38602016-07-19 09:25:43 +0000604void ScriptParser::readPhdrs() {
605 expect("{");
606 while (!Error && !skip("}")) {
607 StringRef Tok = next();
Eugene Leviant865bf862016-07-21 10:43:25 +0000608 Opt.PhdrsCommands.push_back({Tok, PT_NULL, false, false, UINT_MAX});
Eugene Leviantbbe38602016-07-19 09:25:43 +0000609 PhdrsCommand &PhdrCmd = Opt.PhdrsCommands.back();
610
611 PhdrCmd.Type = readPhdrType();
612 do {
613 Tok = next();
614 if (Tok == ";")
615 break;
616 if (Tok == "FILEHDR")
617 PhdrCmd.HasFilehdr = true;
618 else if (Tok == "PHDRS")
619 PhdrCmd.HasPhdrs = true;
Eugene Leviant865bf862016-07-21 10:43:25 +0000620 else if (Tok == "FLAGS") {
621 expect("(");
622 next().getAsInteger(0, PhdrCmd.Flags);
623 expect(")");
624 } else
Eugene Leviantbbe38602016-07-19 09:25:43 +0000625 setError("unexpected header attribute: " + Tok);
626 } while (!Error);
627 }
628}
629
Rui Ueyama717677a2016-02-11 21:17:59 +0000630void ScriptParser::readSearchDir() {
Davide Italiano68a39a62015-10-08 17:51:41 +0000631 expect("(");
Rafael Espindola06501922016-03-08 17:13:12 +0000632 Config->SearchPaths.push_back(next());
Davide Italiano68a39a62015-10-08 17:51:41 +0000633 expect(")");
634}
635
Rui Ueyama717677a2016-02-11 21:17:59 +0000636void ScriptParser::readSections() {
Rui Ueyama07320e42016-04-20 20:13:41 +0000637 Opt.DoLayout = true;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000638 expect("{");
George Rimar652852c2016-04-16 10:10:32 +0000639 while (!Error && !skip("}")) {
Rui Ueyama113cdec2016-07-24 23:05:57 +0000640 StringRef Tok = next();
641 if (peek() == "=") {
642 readAssignment(Tok);
643 expect(";");
644 } else if (Tok == "PROVIDE") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000645 readProvide(false);
Rui Ueyama708019c2016-07-24 18:19:40 +0000646 } else if (Tok == "PROVIDE_HIDDEN") {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000647 readProvide(true);
Rui Ueyama708019c2016-07-24 18:19:40 +0000648 } else {
Eugene Levianteda81a12016-07-12 06:39:48 +0000649 readOutputSectionDescription(Tok);
Rui Ueyama708019c2016-07-24 18:19:40 +0000650 }
George Rimar652852c2016-04-16 10:10:32 +0000651 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000652}
653
Rui Ueyama708019c2016-07-24 18:19:40 +0000654static int precedence(StringRef Op) {
655 return StringSwitch<int>(Op)
656 .Case("*", 4)
657 .Case("/", 4)
658 .Case("+", 3)
659 .Case("-", 3)
660 .Case("<", 2)
661 .Case(">", 2)
662 .Case(">=", 2)
663 .Case("<=", 2)
664 .Case("==", 2)
665 .Case("!=", 2)
666 .Case("&", 1)
667 .Default(-1);
668}
669
Davide Italianoe7282792016-07-27 01:44:01 +0000670std::unique_ptr<InputSectionDescription> ScriptParser::readFilePattern() {
Davide Italiano0ed42b02016-07-25 21:47:13 +0000671 expect("*");
672 expect("(");
Davide Italianoe7282792016-07-27 01:44:01 +0000673
674 auto InCmd = llvm::make_unique<InputSectionDescription>();
675
676 if (skip("EXCLUDE_FILE")) {
677 expect("(");
678 while (!Error && !skip(")"))
679 InCmd->ExcludedFiles.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000680 InCmd->Patterns.push_back(next());
Davide Italianoe7282792016-07-27 01:44:01 +0000681 expect(")");
682 } else {
683 while (!Error && !skip(")"))
684 InCmd->Patterns.push_back(next());
Davide Italiano0ed42b02016-07-25 21:47:13 +0000685 }
Davide Italianoe7282792016-07-27 01:44:01 +0000686 return InCmd;
687}
688
689void ScriptParser::readKeep(OutputSectionCommand *Cmd) {
690 expect("(");
691 std::unique_ptr<InputSectionDescription> InCmd = readFilePattern();
692 Opt.KeptSections.insert(Opt.KeptSections.end(), InCmd->Patterns.begin(),
693 InCmd->Patterns.end());
694 Cmd->Commands.push_back(std::move(InCmd));
Davide Italiano0ed42b02016-07-25 21:47:13 +0000695 expect(")");
696}
697
George Rimar630c6172016-07-26 18:06:29 +0000698void ScriptParser::readAlign(OutputSectionCommand *Cmd) {
699 expect("(");
700 Cmd->AlignExpr = readExpr();
701 expect(")");
702}
703
Eugene Levianteda81a12016-07-12 06:39:48 +0000704void ScriptParser::readOutputSectionDescription(StringRef OutSec) {
George Rimar076fe152016-07-21 06:43:01 +0000705 OutputSectionCommand *Cmd = new OutputSectionCommand(OutSec);
706 Opt.Commands.emplace_back(Cmd);
George Rimar58e5c4d2016-07-25 08:29:46 +0000707
708 // Read an address expression.
709 // https://sourceware.org/binutils/docs/ld/Output-Section-Address.html#Output-Section-Address
710 if (peek() != ":")
711 Cmd->AddrExpr = readExpr();
712
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000713 expect(":");
Davide Italiano246f6812016-07-22 03:36:24 +0000714
George Rimar630c6172016-07-26 18:06:29 +0000715 if (skip("ALIGN"))
716 readAlign(Cmd);
717
Davide Italiano246f6812016-07-22 03:36:24 +0000718 // Parse constraints.
719 if (skip("ONLY_IF_RO"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000720 Cmd->Constraint = ConstraintKind::ReadOnly;
Davide Italiano246f6812016-07-22 03:36:24 +0000721 if (skip("ONLY_IF_RW"))
Rui Ueyamaefc40662016-07-25 22:00:10 +0000722 Cmd->Constraint = ConstraintKind::ReadWrite;
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000723 expect("{");
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000724
Rui Ueyama025d59b2016-02-02 20:27:59 +0000725 while (!Error && !skip("}")) {
George Rimar481c2ce2016-02-23 07:47:54 +0000726 StringRef Tok = next();
727 if (Tok == "*") {
George Rimareea31142016-07-21 14:26:59 +0000728 auto *InCmd = new InputSectionDescription();
729 Cmd->Commands.emplace_back(InCmd);
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000730 expect("(");
731 while (!Error && !skip(")"))
George Rimareea31142016-07-21 14:26:59 +0000732 InCmd->Patterns.push_back(next());
George Rimar481c2ce2016-02-23 07:47:54 +0000733 } else if (Tok == "KEEP") {
Davide Italiano0ed42b02016-07-25 21:47:13 +0000734 readKeep(Cmd);
Davide Italiano054a6792016-07-24 23:13:48 +0000735 } else if (Tok == "PROVIDE") {
736 readProvide(false);
737 } else if (Tok == "PROVIDE_HIDDEN") {
738 readProvide(true);
George Rimar481c2ce2016-02-23 07:47:54 +0000739 } else {
George Rimar777f9632016-03-12 08:31:34 +0000740 setError("unknown command " + Tok);
George Rimar481c2ce2016-02-23 07:47:54 +0000741 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000742 }
George Rimar076fe152016-07-21 06:43:01 +0000743 Cmd->Phdrs = readOutputSectionPhdrs();
Rui Ueyama8ec77e62016-04-21 22:00:51 +0000744
George Rimare2ee72b2016-02-26 14:48:31 +0000745 StringRef Tok = peek();
746 if (Tok.startswith("=")) {
747 if (!Tok.startswith("=0x")) {
Rui Ueyama3ed2f062016-03-13 03:17:44 +0000748 setError("filler should be a hexadecimal value");
George Rimare2ee72b2016-02-26 14:48:31 +0000749 return;
750 }
Rui Ueyama3e808972016-02-28 05:09:11 +0000751 Tok = Tok.substr(3);
George Rimarf6c3cce2016-07-21 07:48:54 +0000752 Cmd->Filler = parseHex(Tok);
George Rimare2ee72b2016-02-26 14:48:31 +0000753 next();
754 }
Denis Protivensky8e3b38a2015-11-12 09:52:08 +0000755}
756
Eugene Levianta31c91b2016-07-22 07:38:40 +0000757void ScriptParser::readProvide(bool Hidden) {
758 expect("(");
Rui Ueyama113cdec2016-07-24 23:05:57 +0000759 if (SymbolAssignment *Assignment = readAssignment(next())) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000760 Assignment->Provide = true;
761 Assignment->Hidden = Hidden;
762 }
763 expect(")");
764 expect(";");
Eugene Levianteda81a12016-07-12 06:39:48 +0000765}
766
Rui Ueyama113cdec2016-07-24 23:05:57 +0000767SymbolAssignment *ScriptParser::readAssignment(StringRef Name) {
Eugene Levianta31c91b2016-07-22 07:38:40 +0000768 expect("=");
Rui Ueyama708019c2016-07-24 18:19:40 +0000769 Expr E = readExpr();
Rui Ueyama113cdec2016-07-24 23:05:57 +0000770 auto *Cmd = new SymbolAssignment(Name, E);
771 Opt.Commands.emplace_back(Cmd);
772 return Cmd;
Eugene Levianta31c91b2016-07-22 07:38:40 +0000773}
774
Rui Ueyama708019c2016-07-24 18:19:40 +0000775// This is an operator-precedence parser to parse a linker
776// script expression.
777Expr ScriptParser::readExpr() { return readExpr1(readPrimary(), 0); }
Eugene Levianta31c91b2016-07-22 07:38:40 +0000778
George Rimara9c5a522016-07-26 18:18:58 +0000779static uint64_t getSymbolValue(StringRef S) {
780 switch (Config->EKind) {
781 case ELF32LEKind:
782 if (SymbolBody *B = Symtab<ELF32LE>::X->find(S))
783 return B->getVA<ELF32LE>();
784 break;
785 case ELF32BEKind:
786 if (SymbolBody *B = Symtab<ELF32BE>::X->find(S))
787 return B->getVA<ELF32BE>();
788 break;
789 case ELF64LEKind:
790 if (SymbolBody *B = Symtab<ELF64LE>::X->find(S))
791 return B->getVA<ELF64LE>();
792 break;
793 case ELF64BEKind:
794 if (SymbolBody *B = Symtab<ELF64BE>::X->find(S))
795 return B->getVA<ELF64BE>();
796 break;
George Rimar6930a6d2016-07-26 18:41:06 +0000797 default:
George Rimarb567b622016-07-26 18:46:13 +0000798 llvm_unreachable("unsupported target");
George Rimara9c5a522016-07-26 18:18:58 +0000799 }
800 error("symbol not found: " + S);
801 return 0;
802}
803
Rui Ueyama708019c2016-07-24 18:19:40 +0000804// This is a part of the operator-precedence parser. This function
805// assumes that the remaining token stream starts with an operator.
806Expr ScriptParser::readExpr1(Expr Lhs, int MinPrec) {
807 while (!atEOF() && !Error) {
808 // Read an operator and an expression.
809 StringRef Op1 = peek();
810 if (Op1 == "?")
811 return readTernary(Lhs);
812 if (precedence(Op1) < MinPrec)
Eugene Levianteda81a12016-07-12 06:39:48 +0000813 break;
Rui Ueyama708019c2016-07-24 18:19:40 +0000814 next();
815 Expr Rhs = readPrimary();
816
817 // Evaluate the remaining part of the expression first if the
818 // next operator has greater precedence than the previous one.
819 // For example, if we have read "+" and "3", and if the next
820 // operator is "*", then we'll evaluate 3 * ... part first.
821 while (!atEOF()) {
822 StringRef Op2 = peek();
823 if (precedence(Op2) <= precedence(Op1))
824 break;
825 Rhs = readExpr1(Rhs, precedence(Op2));
826 }
827
828 Lhs = combine(Op1, Lhs, Rhs);
Eugene Levianteda81a12016-07-12 06:39:48 +0000829 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000830 return Lhs;
831}
832
833uint64_t static getConstant(StringRef S) {
834 if (S == "COMMONPAGESIZE" || S == "MAXPAGESIZE")
835 return Target->PageSize;
836 error("unknown constant: " + S);
837 return 0;
838}
839
840Expr ScriptParser::readPrimary() {
841 StringRef Tok = next();
842
843 if (Tok == ".")
844 return [](uint64_t Dot) { return Dot; };
845
846 if (Tok == "(") {
847 Expr E = readExpr();
848 expect(")");
849 return E;
850 }
851
852 // Built-in functions are parsed here.
853 // https://sourceware.org/binutils/docs/ld/Builtin-Functions.html.
854 if (Tok == "ALIGN") {
855 expect("(");
856 Expr E = readExpr();
857 expect(")");
858 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
859 }
860 if (Tok == "CONSTANT") {
861 expect("(");
862 StringRef Tok = next();
863 expect(")");
864 return [=](uint64_t Dot) { return getConstant(Tok); };
865 }
866 if (Tok == "DATA_SEGMENT_ALIGN") {
867 expect("(");
868 Expr E = readExpr();
869 expect(",");
870 readExpr();
871 expect(")");
Rui Ueyamaf7791bb2016-07-26 19:34:10 +0000872 return [=](uint64_t Dot) { return alignTo(Dot, E(Dot)); };
Rui Ueyama708019c2016-07-24 18:19:40 +0000873 }
874 if (Tok == "DATA_SEGMENT_END") {
875 expect("(");
876 expect(".");
877 expect(")");
878 return [](uint64_t Dot) { return Dot; };
879 }
George Rimar276b4e62016-07-26 17:58:44 +0000880 // GNU linkers implements more complicated logic to handle
881 // DATA_SEGMENT_RELRO_END. We instead ignore the arguments and just align to
882 // the next page boundary for simplicity.
883 if (Tok == "DATA_SEGMENT_RELRO_END") {
884 expect("(");
885 next();
886 expect(",");
887 readExpr();
888 expect(")");
889 return [](uint64_t Dot) { return alignTo(Dot, Target->PageSize); };
890 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000891
George Rimara9c5a522016-07-26 18:18:58 +0000892 // Parse a symbol name or a number literal.
Rui Ueyama708019c2016-07-24 18:19:40 +0000893 uint64_t V = 0;
George Rimara9c5a522016-07-26 18:18:58 +0000894 if (Tok.getAsInteger(0, V)) {
895 if (!isValidCIdentifier(Tok))
896 setError("malformed number: " + Tok);
897 return [=](uint64_t Dot) { return getSymbolValue(Tok); };
898 }
Rui Ueyama708019c2016-07-24 18:19:40 +0000899 return [=](uint64_t Dot) { return V; };
900}
901
902Expr ScriptParser::readTernary(Expr Cond) {
903 next();
904 Expr L = readExpr();
905 expect(":");
906 Expr R = readExpr();
907 return [=](uint64_t Dot) { return Cond(Dot) ? L(Dot) : R(Dot); };
908}
909
910Expr ScriptParser::combine(StringRef Op, Expr L, Expr R) {
911 if (Op == "*")
912 return [=](uint64_t Dot) { return L(Dot) * R(Dot); };
913 if (Op == "/") {
914 return [=](uint64_t Dot) -> uint64_t {
915 uint64_t RHS = R(Dot);
916 if (RHS == 0) {
917 error("division by zero");
918 return 0;
919 }
920 return L(Dot) / RHS;
921 };
922 }
923 if (Op == "+")
924 return [=](uint64_t Dot) { return L(Dot) + R(Dot); };
925 if (Op == "-")
926 return [=](uint64_t Dot) { return L(Dot) - R(Dot); };
927 if (Op == "<")
928 return [=](uint64_t Dot) { return L(Dot) < R(Dot); };
929 if (Op == ">")
930 return [=](uint64_t Dot) { return L(Dot) > R(Dot); };
931 if (Op == ">=")
932 return [=](uint64_t Dot) { return L(Dot) >= R(Dot); };
933 if (Op == "<=")
934 return [=](uint64_t Dot) { return L(Dot) <= R(Dot); };
935 if (Op == "==")
936 return [=](uint64_t Dot) { return L(Dot) == R(Dot); };
937 if (Op == "!=")
938 return [=](uint64_t Dot) { return L(Dot) != R(Dot); };
939 if (Op == "&")
940 return [=](uint64_t Dot) { return L(Dot) & R(Dot); };
941 llvm_unreachable("invalid operator");
Eugene Levianteda81a12016-07-12 06:39:48 +0000942}
943
Eugene Leviantbbe38602016-07-19 09:25:43 +0000944std::vector<StringRef> ScriptParser::readOutputSectionPhdrs() {
945 std::vector<StringRef> Phdrs;
946 while (!Error && peek().startswith(":")) {
947 StringRef Tok = next();
948 Tok = (Tok.size() == 1) ? next() : Tok.substr(1);
949 if (Tok.empty()) {
950 setError("section header name is empty");
951 break;
952 }
Rui Ueyama047404f2016-07-20 19:36:36 +0000953 Phdrs.push_back(Tok);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000954 }
955 return Phdrs;
956}
957
958unsigned ScriptParser::readPhdrType() {
Eugene Leviantbbe38602016-07-19 09:25:43 +0000959 StringRef Tok = next();
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000960 unsigned Ret = StringSwitch<unsigned>(Tok)
961 .Case("PT_NULL", PT_NULL)
962 .Case("PT_LOAD", PT_LOAD)
963 .Case("PT_DYNAMIC", PT_DYNAMIC)
964 .Case("PT_INTERP", PT_INTERP)
965 .Case("PT_NOTE", PT_NOTE)
966 .Case("PT_SHLIB", PT_SHLIB)
967 .Case("PT_PHDR", PT_PHDR)
968 .Case("PT_TLS", PT_TLS)
969 .Case("PT_GNU_EH_FRAME", PT_GNU_EH_FRAME)
970 .Case("PT_GNU_STACK", PT_GNU_STACK)
971 .Case("PT_GNU_RELRO", PT_GNU_RELRO)
972 .Default(-1);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000973
Rui Ueyamab0f6c592016-07-20 19:36:38 +0000974 if (Ret == (unsigned)-1) {
975 setError("invalid program header type: " + Tok);
976 return PT_NULL;
977 }
978 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000979}
980
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000981static bool isUnderSysroot(StringRef Path) {
982 if (Config->Sysroot == "")
983 return false;
984 for (; !Path.empty(); Path = sys::path::parent_path(Path))
985 if (sys::fs::equivalent(Config->Sysroot, Path))
986 return true;
987 return false;
988}
989
Rui Ueyama07320e42016-04-20 20:13:41 +0000990// Entry point.
991void elf::readLinkerScript(MemoryBufferRef MB) {
Simon Atanasyan16b0cc92015-11-26 05:53:00 +0000992 StringRef Path = MB.getBufferIdentifier();
Rui Ueyama07320e42016-04-20 20:13:41 +0000993 ScriptParser(MB.getBuffer(), isUnderSysroot(Path)).run();
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +0000994}
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +0000995
Rui Ueyama07320e42016-04-20 20:13:41 +0000996template class elf::LinkerScript<ELF32LE>;
997template class elf::LinkerScript<ELF32BE>;
998template class elf::LinkerScript<ELF64LE>;
999template class elf::LinkerScript<ELF64BE>;