blob: 8b239c4d0222970101a52a82d2c85af6bb630144 [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 Ueyamaf7c5fbb2015-09-30 17:23:26 +000011//
12//===----------------------------------------------------------------------===//
13
Rui Ueyama717677a2016-02-11 21:17:59 +000014#include "LinkerScript.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000015#include "Config.h"
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000016#include "InputSection.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000017#include "Memory.h"
George Rimar652852c2016-04-16 10:10:32 +000018#include "OutputSections.h"
Rui Ueyama93c9af42016-06-29 08:01:32 +000019#include "Strings.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000020#include "SymbolTable.h"
Rui Ueyama55518e72016-10-28 20:57:25 +000021#include "Symbols.h"
George Rimar3fb5a6d2016-11-29 16:05:27 +000022#include "SyntheticSections.h"
Rafael Espindola55b169b2017-05-24 18:08:04 +000023#include "Target.h"
24#include "Threads.h"
Eugene Leviantbbe38602016-07-19 09:25:43 +000025#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000026#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/StringRef.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000028#include "llvm/BinaryFormat/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000029#include "llvm/Support/Casting.h"
Rafael Espindola68880722017-06-01 16:57:48 +000030#include "llvm/Support/Compression.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000031#include "llvm/Support/Endian.h"
32#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000033#include "llvm/Support/FileSystem.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000034#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000035#include <algorithm>
36#include <cassert>
37#include <cstddef>
38#include <cstdint>
39#include <iterator>
40#include <limits>
Eugene Zelenko22886a22016-11-05 01:00:56 +000041#include <string>
Eugene Zelenko22886a22016-11-05 01:00:56 +000042#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000043
44using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000045using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000046using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000047using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000048using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000049using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000050
Rui Ueyamaa34da932017-03-21 23:03:09 +000051LinkerScript *elf::Script;
52
Rafael Espindola72dc1952017-03-17 13:05:04 +000053uint64_t ExprValue::getValue() const {
George Rimar608cf672017-05-10 14:23:33 +000054 if (Sec) {
Rafael Espindolad54c5662017-05-31 19:53:40 +000055 if (OutputSection *OS = Sec->getOutputSection())
56 return alignTo(Sec->getOffset(Val) + OS->Addr, Alignment);
George Rimar41c7ab42017-06-07 08:54:43 +000057 error(Loc + ": unable to evaluate expression: input section " + Sec->Name +
George Rimar608cf672017-05-10 14:23:33 +000058 " has no output section assigned");
59 }
Petr Hosek3c6de1a2017-05-30 03:18:28 +000060 return alignTo(Val, Alignment);
Rafael Espindola72dc1952017-03-17 13:05:04 +000061}
62
Rafael Espindola7ba5f472017-03-17 14:55:36 +000063uint64_t ExprValue::getSecAddr() const {
64 if (Sec)
65 return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
66 return 0;
67}
68
Meador Inge8f1f3c42017-01-09 18:36:57 +000069template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000070 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000071 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +000072 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
73 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
74 /*File*/ nullptr);
75 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +000076 ExprValue Value = Cmd->Expression();
77 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
George Rimar01aa7952017-04-14 09:23:26 +000078
79 // We want to set symbol values early if we can. This allows us to use symbols
80 // as variables in linker scripts. Doing so allows us to write expressions
81 // like this: `alignment = 16; . = ALIGN(., alignment)`
82 uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
Rui Ueyama80474a22017-02-28 19:29:55 +000083 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
George Rimar01aa7952017-04-14 09:23:26 +000084 STT_NOTYPE, SymValue, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +000085 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000086}
87
Rafael Espindola05c4f672017-06-01 01:16:50 +000088OutputSectionCommand *
89LinkerScript::createOutputSectionCommand(StringRef Name, StringRef Location) {
90 OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
91 OutputSectionCommand *Cmd;
92 if (CmdRef && CmdRef->Location.empty()) {
93 // There was a forward reference.
94 Cmd = CmdRef;
95 } else {
96 Cmd = make<OutputSectionCommand>(Name);
97 if (!CmdRef)
98 CmdRef = Cmd;
99 }
100 Cmd->Location = Location;
101 return Cmd;
George Rimar851dc1e2017-03-14 10:15:53 +0000102}
103
Rafael Espindola05c4f672017-06-01 01:16:50 +0000104OutputSectionCommand *
105LinkerScript::getOrCreateOutputSectionCommand(StringRef Name) {
106 OutputSectionCommand *&CmdRef = NameToOutputSectionCommand[Name];
107 if (!CmdRef)
108 CmdRef = make<OutputSectionCommand>(Name);
109 return CmdRef;
George Rimard83ce1b2017-03-14 10:24:47 +0000110}
111
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000112void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000113 uint64_t Val = E().getValue();
Rafael Espindola679828f2017-02-17 16:26:13 +0000114 if (Val < Dot) {
115 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000116 error(Loc + ": unable to move location counter backward for: " +
117 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000118 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000119 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000120 }
121 Dot = Val;
122 // Update to location counter means update to section size.
123 if (InSec)
124 CurOutSec->Size = Dot - CurOutSec->Addr;
125}
126
George Rimarb2b70972017-02-07 10:23:28 +0000127// Sets value of a symbol. Two kinds of symbols are processed: synthetic
128// symbols, whose value is an offset from beginning of section and regular
129// symbols whose value is absolute.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000130void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000131 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000132 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000133 return;
134 }
135
George Rimarb2b70972017-02-07 10:23:28 +0000136 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000137 return;
138
Rafael Espindola5616adf2017-03-08 22:36:28 +0000139 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000140 ExprValue V = Cmd->Expression();
141 if (V.isAbsolute()) {
142 Sym->Value = V.getValue();
143 } else {
144 Sym->Section = V.Sec;
Rafael Espindoladece2802017-06-13 20:57:43 +0000145 Sym->Value = alignTo(V.Val, V.Alignment);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000146 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000147}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000148
George Rimara8dba482017-03-20 10:09:58 +0000149static SymbolBody *findSymbol(StringRef S) {
150 switch (Config->EKind) {
151 case ELF32LEKind:
152 return Symtab<ELF32LE>::X->find(S);
153 case ELF32BEKind:
154 return Symtab<ELF32BE>::X->find(S);
155 case ELF64LEKind:
156 return Symtab<ELF64LE>::X->find(S);
157 case ELF64BEKind:
158 return Symtab<ELF64BE>::X->find(S);
159 default:
160 llvm_unreachable("unknown Config->EKind");
161 }
162}
163
164static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
165 switch (Config->EKind) {
166 case ELF32LEKind:
167 return addRegular<ELF32LE>(Cmd);
168 case ELF32BEKind:
169 return addRegular<ELF32BE>(Cmd);
170 case ELF64LEKind:
171 return addRegular<ELF64LE>(Cmd);
172 case ELF64BEKind:
173 return addRegular<ELF64BE>(Cmd);
174 default:
175 llvm_unreachable("unknown Config->EKind");
176 }
177}
178
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000179void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000180 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000181 return;
182
183 // If a symbol was in PROVIDE(), we need to define it only when
184 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000185 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000186 if (Cmd->Provide && (!B || B->isDefined()))
187 return;
188
George Rimara8dba482017-03-20 10:09:58 +0000189 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000190}
191
George Rimar076fe152016-07-21 06:43:01 +0000192bool SymbolAssignment::classof(const BaseCommand *C) {
193 return C->Kind == AssignmentKind;
194}
195
196bool OutputSectionCommand::classof(const BaseCommand *C) {
197 return C->Kind == OutputSectionKind;
198}
199
Rafael Espindola55b169b2017-05-24 18:08:04 +0000200// Fill [Buf, Buf + Size) with Filler.
201// This is used for linker script "=fillexp" command.
202static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
203 size_t I = 0;
204 for (; I + 4 < Size; I += 4)
205 memcpy(Buf + I, &Filler, 4);
206 memcpy(Buf + I, &Filler, Size - I);
207}
208
George Rimareea31142016-07-21 14:26:59 +0000209bool InputSectionDescription::classof(const BaseCommand *C) {
210 return C->Kind == InputSectionKind;
211}
212
George Rimareefa7582016-08-04 09:29:31 +0000213bool AssertCommand::classof(const BaseCommand *C) {
214 return C->Kind == AssertKind;
215}
216
George Rimare38cbab2016-09-26 19:22:50 +0000217bool BytesDataCommand::classof(const BaseCommand *C) {
218 return C->Kind == BytesDataKind;
219}
220
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000221static StringRef basename(InputSectionBase *S) {
222 if (S->File)
223 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000224 return "";
225}
226
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000227bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000228 for (InputSectionDescription *ID : Opt.KeptSections)
229 if (ID->FilePat.match(basename(S)))
230 for (SectionPattern &P : ID->SectionPatterns)
231 if (P.SectionPat.match(S->Name))
232 return true;
George Rimareea31142016-07-21 14:26:59 +0000233 return false;
234}
235
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000236// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000237static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000238getComparator(SortSectionPolicy K) {
239 switch (K) {
240 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000241 return [](InputSectionBase *A, InputSectionBase *B) {
242 // ">" is not a mistake. Sections with larger alignments are placed
243 // before sections with smaller alignments in order to reduce the
244 // amount of padding necessary. This is compatible with GNU.
245 return A->Alignment > B->Alignment;
246 };
George Rimarbe394db2016-09-16 20:21:55 +0000247 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000248 return [](InputSectionBase *A, InputSectionBase *B) {
249 return A->Name < B->Name;
250 };
George Rimarbe394db2016-09-16 20:21:55 +0000251 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000252 return [](InputSectionBase *A, InputSectionBase *B) {
253 return getPriority(A->Name) < getPriority(B->Name);
254 };
George Rimarbe394db2016-09-16 20:21:55 +0000255 default:
256 llvm_unreachable("unknown sort policy");
257 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000258}
George Rimar0702c4e2016-07-29 15:32:46 +0000259
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000260// A helper function for the SORT() command.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000261static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000262 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000263 if (Kind == ConstraintKind::NoConstraint)
264 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000265
266 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
267 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000268 });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000269
Rafael Espindolae746e522016-09-21 18:33:44 +0000270 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
271 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000272}
273
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000274static void sortSections(InputSection **Begin, InputSection **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000275 SortSectionPolicy K) {
276 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000277 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000278}
279
Rafael Espindolad3190792016-09-16 15:10:23 +0000280// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000281std::vector<InputSection *>
Rui Ueyama72e107f2017-04-05 02:05:48 +0000282LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000283 std::vector<InputSection *> Ret;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000284
Rui Ueyama72e107f2017-04-05 02:05:48 +0000285 // Collects all sections that satisfy constraints of Cmd.
286 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
287 size_t SizeBefore = Ret.size();
288
289 for (InputSectionBase *Sec : InputSections) {
290 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000291 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000292
Rafael Espindolae39709b2017-05-30 20:40:03 +0000293 if (!Sec->Live) {
294 reportDiscarded(Sec);
295 continue;
296 }
297
Rafael Espindola908a3d32017-02-16 14:36:09 +0000298 // For -emit-relocs we have to ignore entries like
299 // .rela.dyn : { *(.rela.data) }
300 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000301 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000302 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000303
Rui Ueyama72e107f2017-04-05 02:05:48 +0000304 StringRef Filename = basename(Sec);
305 if (!Cmd->FilePat.match(Filename) ||
306 Pat.ExcludedFilePat.match(Filename) ||
307 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000308 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000309
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000310 Ret.push_back(cast<InputSection>(Sec));
Rui Ueyama72e107f2017-04-05 02:05:48 +0000311 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000312 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000313
George Rimar07171f22016-09-21 15:56:44 +0000314 // Sort sections as instructed by SORT-family commands and --sort-section
315 // option. Because SORT-family commands can be nested at most two depth
316 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
317 // line option is respected even if a SORT command is given, the exact
318 // behavior we have here is a bit complicated. Here are the rules.
319 //
320 // 1. If two SORT commands are given, --sort-section is ignored.
321 // 2. If one SORT command is given, and if it is not SORT_NONE,
322 // --sort-section is handled as an inner SORT command.
323 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
324 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000325 InputSection **Begin = Ret.data() + SizeBefore;
326 InputSection **End = Ret.data() + Ret.size();
George Rimar07171f22016-09-21 15:56:44 +0000327 if (Pat.SortOuter != SortSectionPolicy::None) {
328 if (Pat.SortInner == SortSectionPolicy::Default)
329 sortSections(Begin, End, Config->SortSection);
330 else
331 sortSections(Begin, End, Pat.SortInner);
332 sortSections(Begin, End, Pat.SortOuter);
333 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000334 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000335 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000336}
337
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000338void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000339 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000340 S->Live = false;
Rafael Espindola4f1fca2702017-06-16 23:53:36 +0000341 if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
342 S == InX::DynStrTab)
Rafael Espindola2af64b02017-06-16 23:45:35 +0000343 error("discarding " + S->Name + " section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000344 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000345 }
346}
347
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000348std::vector<InputSectionBase *>
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000349LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000350 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000351
Rui Ueyama8f99f732017-04-05 03:20:42 +0000352 for (BaseCommand *Base : OutCmd.Commands) {
353 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000354 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000355 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000356
357 Cmd->Sections = computeInputSections(Cmd);
Rafael Espindolae4c8b9b2017-04-07 16:10:46 +0000358 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000359 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000360
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000361 return Ret;
362}
363
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000364void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000365 // A symbol can be assigned before any section is mentioned in the linker
366 // script. In an DSO, the symbol values are addresses, so the only important
367 // section values are:
368 // * SHN_UNDEF
369 // * SHN_ABS
370 // * Any value meaning a regular section.
371 // To handle that, create a dummy aether section that fills the void before
372 // the linker scripts switches to another section. It has an index of one
373 // which will map to whatever the first actual section is.
374 Aether = make<OutputSection>("", 0, SHF_ALLOC);
375 Aether->SectionIndex = 1;
376 CurOutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000377 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000378
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000379 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000380 // Handle symbol assignments outside of any output section.
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000381 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000382 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000383 continue;
384 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000385
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000386 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000387 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000388
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000389 // The output section name `/DISCARD/' is special.
390 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000391 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000392 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000393 continue;
394 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000395
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000396 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
397 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
398 // sections satisfy a given constraint. If not, a directive is handled
George Rimar07d7c422017-04-05 09:19:29 +0000399 // as if it wasn't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000400 //
401 // Because we'll iterate over Commands many more times, the easiest
George Rimar07d7c422017-04-05 09:19:29 +0000402 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000403 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000404 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000405 S->Assigned = false;
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000406 Opt.Commands.erase(Opt.Commands.begin() + I);
George Rimar07d7c422017-04-05 09:19:29 +0000407 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000408 continue;
409 }
410
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000411 // A directive may contain symbol definitions like this:
412 // ".foo : { ...; bar = .; }". Handle them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000413 for (BaseCommand *Base : Cmd->Commands)
414 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000415 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000416
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000417 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
418 // is given, input sections are aligned to that value, whether the
419 // given value is larger or smaller than the original section alignment.
420 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000421 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000422 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000423 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000424 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000425
426 // Add input sections to an output section.
George Rimard86a4e52017-05-08 10:18:12 +0000427 for (InputSectionBase *S : V)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000428 Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000429 if (OutputSection *Sec = Cmd->Sec) {
430 assert(Sec->SectionIndex == INT_MAX);
431 Sec->SectionIndex = I;
George Rimarfbb04632017-06-07 16:31:08 +0000432 if (Cmd->Noload)
433 Sec->Type = SHT_NOBITS;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000434 SecToCommand[Sec] = Cmd;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000435 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000436 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000437 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000438 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000439}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000440
Rafael Espindola02ed7572017-05-04 19:34:17 +0000441void LinkerScript::fabricateDefaultCommands() {
Peter Smithcbfe9e92017-04-19 12:46:32 +0000442 std::vector<BaseCommand *> Commands;
443
444 // Define start address
Rafael Espindolae76231b2017-06-08 04:17:04 +0000445 uint64_t StartAddr = -1;
Peter Smithcbfe9e92017-04-19 12:46:32 +0000446
Peter Smithc60b4512017-05-03 08:44:50 +0000447 // The Sections with -T<section> have been sorted in order of ascending
448 // address. We must lower StartAddr if the lowest -T<section address> as
449 // calls to setDot() must be monotonically increasing.
450 for (auto& KV : Config->SectionStartMap)
451 StartAddr = std::min(StartAddr, KV.second);
452
Rafael Espindolae76231b2017-06-08 04:17:04 +0000453 Commands.push_back(make<SymbolAssignment>(
454 ".",
455 [=] {
456 return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize());
457 },
458 ""));
Peter Smithcbfe9e92017-04-19 12:46:32 +0000459
460 // For each OutputSection that needs a VA fabricate an OutputSectionCommand
461 // with an InputSectionDescription describing the InputSections
Rafael Espindolaf51c8052017-06-13 23:26:31 +0000462 for (OutputSection *Sec : OutputSections) {
Rafael Espindola05c4f672017-06-01 01:16:50 +0000463 auto *OSCmd = createOutputSectionCommand(Sec->Name, "<internal>");
Peter Smithc60b4512017-05-03 08:44:50 +0000464 OSCmd->Sec = Sec;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000465 SecToCommand[Sec] = OSCmd;
Peter Smithc60b4512017-05-03 08:44:50 +0000466
Peter Smithcbfe9e92017-04-19 12:46:32 +0000467 Commands.push_back(OSCmd);
468 if (Sec->Sections.size()) {
469 auto *ISD = make<InputSectionDescription>("");
470 OSCmd->Commands.push_back(ISD);
471 for (InputSection *ISec : Sec->Sections) {
472 ISD->Sections.push_back(ISec);
473 ISec->Assigned = true;
474 }
475 }
476 }
477 // SECTIONS commands run before other non SECTIONS commands
478 Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
479 Opt.Commands = std::move(Commands);
480}
481
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000482// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000483void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000484 for (InputSectionBase *S : InputSections) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000485 if (!S->Live || S->Parent)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000486 continue;
487 StringRef Name = getOutputSectionName(S->Name);
488 auto I = std::find_if(
489 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
490 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
491 return Cmd->Name == Name;
492 return false;
493 });
Rafael Espindolade8d9892017-04-29 15:44:03 +0000494 if (I == Opt.Commands.end()) {
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000495 Factory.addInputSec(S, Name);
Rafael Espindolade8d9892017-04-29 15:44:03 +0000496 } else {
497 auto *Cmd = cast<OutputSectionCommand>(*I);
498 Factory.addInputSec(S, Name, Cmd->Sec);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000499 if (OutputSection *Sec = Cmd->Sec) {
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000500 SecToCommand[Sec] = Cmd;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000501 unsigned Index = std::distance(Opt.Commands.begin(), I);
502 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
503 Sec->SectionIndex = Index;
504 }
Rafael Espindolade8d9892017-04-29 15:44:03 +0000505 auto *ISD = make<InputSectionDescription>("");
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000506 ISD->Sections.push_back(cast<InputSection>(S));
Rafael Espindolade8d9892017-04-29 15:44:03 +0000507 Cmd->Commands.push_back(ISD);
508 }
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000509 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000510}
511
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000512uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
513 bool IsTbss = (CurOutSec->Flags & SHF_TLS) && CurOutSec->Type == SHT_NOBITS;
514 uint64_t Start = IsTbss ? Dot + ThreadBssOffset : Dot;
515 Start = alignTo(Start, Align);
516 uint64_t End = Start + Size;
517
518 if (IsTbss)
519 ThreadBssOffset = End - Dot;
520 else
521 Dot = End;
522 return End;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000523}
524
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000525void LinkerScript::output(InputSection *S) {
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000526 uint64_t Pos = advance(S->getSize(), S->Alignment);
527 S->OutSecOff = Pos - S->getSize() - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000528
529 // Update output section size after adding each section. This is so that
530 // SIZEOF works correctly in the case below:
531 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000532 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000533
Meador Ingeb8897442017-01-24 02:34:00 +0000534 // If there is a memory region associated with this input section, then
535 // place the section in that region and update the region index.
536 if (CurMemRegion) {
537 CurMemRegion->Offset += CurOutSec->Size;
538 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
539 if (CurSize > CurMemRegion->Length) {
540 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
541 error("section '" + CurOutSec->Name + "' will not fit in region '" +
542 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
543 " bytes");
544 }
545 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000546}
547
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000548void LinkerScript::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000549 if (CurOutSec == Sec)
550 return;
Rafael Espindolad3190792016-09-16 15:10:23 +0000551
Rafael Espindolad3190792016-09-16 15:10:23 +0000552 CurOutSec = Sec;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000553 CurOutSec->Addr = advance(0, CurOutSec->Alignment);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000554
555 // If neither AT nor AT> is specified for an allocatable section, the linker
556 // will set the LMA such that the difference between VMA and LMA for the
557 // section is the same as the preceding output section in the same region
558 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000559 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000560 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000561}
562
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000563void LinkerScript::process(BaseCommand &Base) {
Rui Ueyama2e081a42017-04-05 03:18:46 +0000564 // This handles the assignments to symbol or to the dot.
565 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
566 assignSymbol(Cmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000567 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000568 }
George Rimare38cbab2016-09-26 19:22:50 +0000569
570 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyama2e081a42017-04-05 03:18:46 +0000571 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
572 Cmd->Offset = Dot - CurOutSec->Addr;
573 Dot += Cmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000574 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000575 return;
576 }
577
Rui Ueyama2e081a42017-04-05 03:18:46 +0000578 // Handle ASSERT().
579 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
580 Cmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000581 return;
582 }
583
Rui Ueyama2e081a42017-04-05 03:18:46 +0000584 // Handle a single input section description command.
585 // It calculates and assigns the offsets for each section and also
George Rimare38cbab2016-09-26 19:22:50 +0000586 // updates the output section size.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000587 auto &Cmd = cast<InputSectionDescription>(Base);
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000588 for (InputSection *Sec : Cmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000589 // We tentatively added all synthetic sections at the beginning and removed
590 // empty ones afterwards (because there is no way to know whether they were
591 // going be empty or not other than actually running linker scripts.)
592 // We need to ignore remains of empty sections.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000593 if (auto *S = dyn_cast<SyntheticSection>(Sec))
594 if (S->empty())
George Rimar3fb5a6d2016-11-29 16:05:27 +0000595 continue;
596
Rui Ueyama2e081a42017-04-05 03:18:46 +0000597 if (!Sec->Live)
George Rimar78ef6452017-02-21 15:46:43 +0000598 continue;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000599 assert(CurOutSec == Sec->getParent());
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000600 output(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000601 }
602}
603
Meador Ingeb8897442017-01-24 02:34:00 +0000604// This function searches for a memory region to place the given output
605// section in. If found, a pointer to the appropriate memory region is
606// returned. Otherwise, a nullptr is returned.
Rafael Espindola1902b332017-04-06 21:26:03 +0000607MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
Meador Ingeb8897442017-01-24 02:34:00 +0000608 // If a memory region name was specified in the output section command,
609 // then try to find that region first.
610 if (!Cmd->MemoryRegionName.empty()) {
611 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
612 if (It != Opt.MemoryRegions.end())
613 return &It->second;
614 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
615 return nullptr;
616 }
617
Rui Ueyamad7c54002017-04-05 03:19:43 +0000618 // If at least one memory region is defined, all sections must
619 // belong to some memory region. Otherwise, we don't need to do
620 // anything for memory regions.
Rui Ueyamacc400cc2017-04-05 03:19:24 +0000621 if (Opt.MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000622 return nullptr;
623
Rafael Espindola1902b332017-04-06 21:26:03 +0000624 OutputSection *Sec = Cmd->Sec;
Meador Ingeb8897442017-01-24 02:34:00 +0000625 // See if a region can be found by matching section flags.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000626 for (auto &Pair : Opt.MemoryRegions) {
627 MemoryRegion &M = Pair.second;
628 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
629 return &M;
Meador Ingeb8897442017-01-24 02:34:00 +0000630 }
631
632 // Otherwise, no suitable region was found.
633 if (Sec->Flags & SHF_ALLOC)
634 error("no memory region specified for section '" + Sec->Name + "'");
635 return nullptr;
636}
637
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000638// This function assigns offsets to input sections and an output section
639// for a single sections command (e.g. ".text { *(.text); }").
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000640void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
Rafael Espindola9b980092017-04-06 21:05:39 +0000641 OutputSection *Sec = Cmd->Sec;
Rafael Espindola2b074552017-02-03 22:27:05 +0000642 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000643 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000644
Rafael Espindoladece2802017-06-13 20:57:43 +0000645 if (!(Sec->Flags & SHF_ALLOC))
646 Dot = 0;
647 else if (Cmd->AddrExpr)
Rui Ueyamad379f732017-04-05 03:20:22 +0000648 setDot(Cmd->AddrExpr, Cmd->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000649
Eugene Leviant5784e962017-03-14 08:57:09 +0000650 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000651 uint64_t D = Dot;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000652 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000653 }
654
Rafael Espindolafeed7502017-04-06 21:31:24 +0000655 CurMemRegion = Cmd->MemRegion;
Meador Ingeb8897442017-01-24 02:34:00 +0000656 if (CurMemRegion)
657 Dot = CurMemRegion->Offset;
658 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000659
George Rimard86a4e52017-05-08 10:18:12 +0000660 // We do not support custom layout for compressed debug sectons.
661 // At this point we already know their size and have compressed content.
662 if (CurOutSec->Flags & SHF_COMPRESSED)
663 return;
664
Rafael Espindolade8d9892017-04-29 15:44:03 +0000665 for (BaseCommand *C : Cmd->Commands)
666 process(*C);
Rafael Espindolad3190792016-09-16 15:10:23 +0000667}
668
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000669void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000670 // It is common practice to use very generic linker scripts. So for any
671 // given run some of the output sections in the script will be empty.
672 // We could create corresponding empty output sections, but that would
673 // clutter the output.
674 // We instead remove trivially empty sections. The bfd linker seems even
675 // more aggressive at removing them.
676 auto Pos = std::remove_if(
Rui Ueyama8f99f732017-04-05 03:20:42 +0000677 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
678 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
Rafael Espindolae86fddd2017-06-13 23:54:34 +0000679 return Cmd->Sec == nullptr;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000680 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000681 });
682 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000683}
684
Rafael Espindola6a537372016-11-14 14:33:49 +0000685static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000686 for (BaseCommand *Base : Cmd.Commands)
687 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000688 return false;
689 return true;
690}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000691
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000692void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000693 // If the output section contains only symbol assignments, create a
694 // corresponding output section. The bfd linker seems to only create them if
695 // '.' is assigned to, but creating these section should not have any bad
696 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000697 uint64_t Flags = SHF_ALLOC;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000698
699 for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
700 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000701 if (!Cmd)
702 continue;
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000703 if (OutputSection *Sec = Cmd->Sec) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000704 Flags = Sec->Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000705 continue;
706 }
707
Rafael Espindola6a537372016-11-14 14:33:49 +0000708 if (isAllSectionDescription(*Cmd))
709 continue;
710
Dmitry Mikulinfd0c8442017-05-24 16:48:31 +0000711 auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000712 OutSec->SectionIndex = I;
Rafael Espindola9b980092017-04-06 21:05:39 +0000713 Cmd->Sec = OutSec;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000714 SecToCommand[OutSec] = Cmd;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000715 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000716}
717
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000718void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000719 // Try and find an appropriate memory region to assign offsets in.
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000720 for (BaseCommand *Base : Opt.Commands) {
721 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000722 Cmd->MemRegion = findMemoryRegion(Cmd);
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000723 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
724 if (Cmd->AlignExpr)
725 Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
726 }
727 }
Rafael Espindolafeed7502017-04-06 21:31:24 +0000728
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000729 // If output section command doesn't specify any segments,
730 // and we haven't previously assigned any section to segment,
731 // then we simply assign section to the very first load segment.
732 // Below is an example of such linker script:
733 // PHDRS { seg PT_LOAD; }
734 // SECTIONS { .aaa : { *(.aaa) } }
735 std::vector<StringRef> DefPhdrs;
736 auto FirstPtLoad =
737 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
738 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
739 if (FirstPtLoad != Opt.PhdrsCommands.end())
740 DefPhdrs.push_back(FirstPtLoad->Name);
741
742 // Walk the commands and propagate the program headers to commands that don't
743 // explicitly specify them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000744 for (BaseCommand *Base : Opt.Commands) {
745 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000746 if (!Cmd)
747 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000748
Andrew Nga020d342017-07-03 10:11:25 +0000749 if (Cmd->Phdrs.empty()) {
750 OutputSection *Sec = Cmd->Sec;
751 // To match the bfd linker script behaviour, only propagate program
752 // headers to sections that are allocated.
753 if (Sec && (Sec->Flags & SHF_ALLOC))
754 Cmd->Phdrs = DefPhdrs;
755 } else {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000756 DefPhdrs = Cmd->Phdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000757 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000758 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000759
760 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000761}
762
Rafael Espindola383971d2017-06-15 21:51:01 +0000763void LinkerScript::createOrphanCommands() {
Rafael Espindolaf51c8052017-06-13 23:26:31 +0000764 for (OutputSection *Sec : OutputSections) {
Rafael Espindola383971d2017-06-15 21:51:01 +0000765 if (Sec->SectionIndex != INT_MAX)
Rafael Espindola15c57952016-09-22 18:05:49 +0000766 continue;
Rafael Espindola383971d2017-06-15 21:51:01 +0000767 OutputSectionCommand *Cmd =
768 createOutputSectionCommand(Sec->Name, "<internal>");
769 Cmd->Sec = Sec;
770 SecToCommand[Sec] = Cmd;
771 auto *ISD = make<InputSectionDescription>("");
772 ISD->Sections = Sec->Sections;
773 Cmd->Commands.push_back(ISD);
774 Opt.Commands.push_back(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000775 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000776}
777
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000778void LinkerScript::processNonSectionCommands() {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000779 for (BaseCommand *Base : Opt.Commands) {
780 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
Rui Ueyamad379f732017-04-05 03:20:22 +0000781 assignSymbol(Cmd, false);
Rui Ueyama8f99f732017-04-05 03:20:42 +0000782 else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
Petr Hosek02ad5162017-03-15 03:33:23 +0000783 Cmd->Expression();
784 }
785}
786
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000787static bool
788allocateHeaders(std::vector<PhdrEntry> &Phdrs,
789 ArrayRef<OutputSectionCommand *> OutputSectionCommands,
790 uint64_t Min) {
Rafael Espindola02ed7572017-05-04 19:34:17 +0000791 auto FirstPTLoad =
792 std::find_if(Phdrs.begin(), Phdrs.end(),
793 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
794 if (FirstPTLoad == Phdrs.end())
795 return false;
796
797 uint64_t HeaderSize = getHeaderSize();
798 if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
799 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
800 Out::ElfHeader->Addr = Min;
801 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
802 return true;
803 }
804
805 assert(FirstPTLoad->First == Out::ElfHeader);
806 OutputSection *ActualFirst = nullptr;
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000807 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
808 OutputSection *Sec = Cmd->Sec;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000809 if (Sec->FirstInPtLoad == Out::ElfHeader) {
810 ActualFirst = Sec;
811 break;
812 }
813 }
814 if (ActualFirst) {
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000815 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
816 OutputSection *Sec = Cmd->Sec;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000817 if (Sec->FirstInPtLoad == Out::ElfHeader)
818 Sec->FirstInPtLoad = ActualFirst;
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000819 }
Rafael Espindola02ed7572017-05-04 19:34:17 +0000820 FirstPTLoad->First = ActualFirst;
821 } else {
822 Phdrs.erase(FirstPTLoad);
823 }
824
825 auto PhdrI = std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry &E) {
826 return E.p_type == PT_PHDR;
827 });
828 if (PhdrI != Phdrs.end())
829 Phdrs.erase(PhdrI);
830 return false;
831}
832
Rafael Espindolaf51c8052017-06-13 23:26:31 +0000833void LinkerScript::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000834 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000835 Dot = 0;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000836 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000837 switchTo(Aether);
838
Rui Ueyama8f99f732017-04-05 03:20:42 +0000839 for (BaseCommand *Base : Opt.Commands) {
840 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
Rui Ueyamad379f732017-04-05 03:20:22 +0000841 assignSymbol(Cmd, false);
George Rimar652852c2016-04-16 10:10:32 +0000842 continue;
843 }
844
Rui Ueyama8f99f732017-04-05 03:20:42 +0000845 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000846 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000847 continue;
848 }
849
Rui Ueyama8f99f732017-04-05 03:20:42 +0000850 auto *Cmd = cast<OutputSectionCommand>(Base);
Rafael Espindolad3190792016-09-16 15:10:23 +0000851 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000852 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000853
George Rimar0c1c8082017-03-14 10:00:19 +0000854 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000855 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
856 OutputSection *Sec = Cmd->Sec;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000857 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000858 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000859 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000860
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000861 allocateHeaders(Phdrs, OutputSectionCommands, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000862}
863
Rui Ueyama464daad2016-08-22 04:55:20 +0000864// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindolaf51c8052017-06-13 23:26:31 +0000865std::vector<PhdrEntry> LinkerScript::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000866 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000867
Rui Ueyama464daad2016-08-22 04:55:20 +0000868 // Process PHDRS and FILEHDR keywords because they are not
869 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000870 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000871 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000872 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000873
874 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000875 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000876 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000877 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000878
879 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000880 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000881 Phdr.HasLMA = true;
882 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000883 }
884
Rui Ueyama464daad2016-08-22 04:55:20 +0000885 // Add output sections to program headers.
Rafael Espindola7ff93292017-06-10 22:12:32 +0000886 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
887 OutputSection *Sec = Cmd->Sec;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000888
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000889 // Assign headers specified by linker script
Rafael Espindola2c923c22017-05-10 14:28:31 +0000890 for (size_t Id : getPhdrIndices(Sec)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000891 Ret[Id].add(Sec);
892 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000893 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000894 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000895 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000896 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000897}
898
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000899bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000900 // Ignore .interp section in case we have PHDRS specification
901 // and PT_INTERP isn't listed.
Rui Ueyamae31d9882017-04-05 05:06:17 +0000902 if (Opt.PhdrsCommands.empty())
903 return false;
904 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
905 if (Cmd.Type == PT_INTERP)
906 return false;
907 return true;
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000908}
909
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000910OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const {
911 auto I = SecToCommand.find(Sec);
912 if (I == SecToCommand.end())
913 return nullptr;
914 return I->second;
Rafael Espindolafa948c72017-05-10 19:00:23 +0000915}
916
Rafael Espindola55b169b2017-05-24 18:08:04 +0000917uint32_t OutputSectionCommand::getFiller() {
918 if (Filler)
919 return *Filler;
920 if (Sec->Flags & SHF_EXECINSTR)
921 return Target->TrapInstr;
922 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000923}
924
George Rimare38cbab2016-09-26 19:22:50 +0000925static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000926 if (Size == 1)
927 *Buf = Data;
928 else if (Size == 2)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000929 write16(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000930 else if (Size == 4)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000931 write32(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000932 else if (Size == 8)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000933 write64(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000934 else
George Rimare38cbab2016-09-26 19:22:50 +0000935 llvm_unreachable("unsupported Size argument");
George Rimare38cbab2016-09-26 19:22:50 +0000936}
937
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000938static bool compareByFilePosition(InputSection *A, InputSection *B) {
939 // Synthetic doesn't have link order dependecy, stable_sort will keep it last
940 if (A->kind() == InputSectionBase::Synthetic ||
941 B->kind() == InputSectionBase::Synthetic)
942 return false;
943 InputSection *LA = A->getLinkOrderDep();
944 InputSection *LB = B->getLinkOrderDep();
945 OutputSection *AOut = LA->getParent();
946 OutputSection *BOut = LB->getParent();
947 if (AOut != BOut)
948 return AOut->SectionIndex < BOut->SectionIndex;
949 return LA->OutSecOff < LB->OutSecOff;
950}
951
Rafael Espindola658a0c72017-06-06 20:13:19 +0000952template <class ELFT>
953static void finalizeShtGroup(OutputSection *OS,
954 ArrayRef<InputSection *> Sections) {
Rui Ueyama82143d32017-06-26 17:11:36 +0000955 assert(Config->Relocatable && Sections.size() == 1);
956
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000957 // sh_link field for SHT_GROUP sections should contain the section index of
958 // the symbol table.
Rafael Espindola658a0c72017-06-06 20:13:19 +0000959 OS->Link = InX::SymTab->getParent()->SectionIndex;
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000960
961 // sh_info then contain index of an entry in symbol table section which
962 // provides signature of the section group.
Rafael Espindola658a0c72017-06-06 20:13:19 +0000963 elf::ObjectFile<ELFT> *Obj = Sections[0]->getFile<ELFT>();
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000964 ArrayRef<SymbolBody *> Symbols = Obj->getSymbols();
Rafael Espindola658a0c72017-06-06 20:13:19 +0000965 OS->Info = InX::SymTab->getSymbolIndex(Symbols[Sections[0]->Info - 1]);
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000966}
967
968template <class ELFT> void OutputSectionCommand::finalize() {
Rafael Espindola658a0c72017-06-06 20:13:19 +0000969 // Link order may be distributed across several InputSectionDescriptions
970 // but sort must consider them all at once.
971 std::vector<InputSection **> ScriptSections;
972 std::vector<InputSection *> Sections;
973 for (BaseCommand *Base : Commands)
974 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
975 for (InputSection *&IS : ISD->Sections) {
976 ScriptSections.push_back(&IS);
977 Sections.push_back(IS);
978 }
979
980 if ((Sec->Flags & SHF_LINK_ORDER)) {
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000981 std::sort(Sections.begin(), Sections.end(), compareByFilePosition);
982 for (int I = 0, N = Sections.size(); I < N; ++I)
983 *ScriptSections[I] = Sections[I];
984
985 // We must preserve the link order dependency of sections with the
986 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
987 // need to translate the InputSection sh_link to the OutputSection sh_link,
988 // all InputSections in the OutputSection have the same dependency.
Rafael Espindola658a0c72017-06-06 20:13:19 +0000989 if (auto *D = Sections.front()->getLinkOrderDep())
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000990 Sec->Link = D->getParent()->SectionIndex;
991 }
992
993 uint32_t Type = Sec->Type;
994 if (Type == SHT_GROUP) {
Rafael Espindola658a0c72017-06-06 20:13:19 +0000995 finalizeShtGroup<ELFT>(Sec, Sections);
Rafael Espindola8c284ac2017-06-06 19:40:01 +0000996 return;
997 }
998
999 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
1000 return;
1001
Rafael Espindola658a0c72017-06-06 20:13:19 +00001002 InputSection *First = Sections[0];
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001003 if (isa<SyntheticSection>(First))
1004 return;
1005
1006 Sec->Link = InX::SymTab->getParent()->SectionIndex;
1007 // sh_info for SHT_REL[A] sections should contain the section header index of
1008 // the section to which the relocation applies.
1009 InputSectionBase *S = First->getRelocatedSection();
1010 Sec->Info = S->getOutputSection()->SectionIndex;
1011 Sec->Flags |= SHF_INFO_LINK;
1012}
1013
Rafael Espindola68880722017-06-01 16:57:48 +00001014// Compress section contents if this section contains debug info.
1015template <class ELFT> void OutputSectionCommand::maybeCompress() {
1016 typedef typename ELFT::Chdr Elf_Chdr;
1017
1018 // Compress only DWARF debug sections.
1019 if (!Config->CompressDebugSections || (Sec->Flags & SHF_ALLOC) ||
1020 !Name.startswith(".debug_"))
1021 return;
1022
1023 // Create a section header.
1024 Sec->ZDebugHeader.resize(sizeof(Elf_Chdr));
1025 auto *Hdr = reinterpret_cast<Elf_Chdr *>(Sec->ZDebugHeader.data());
1026 Hdr->ch_type = ELFCOMPRESS_ZLIB;
1027 Hdr->ch_size = Sec->Size;
1028 Hdr->ch_addralign = Sec->Alignment;
1029
1030 // Write section contents to a temporary buffer and compress it.
1031 std::vector<uint8_t> Buf(Sec->Size);
1032 writeTo<ELFT>(Buf.data());
1033 if (Error E = zlib::compress(toStringRef(Buf), Sec->CompressedData))
1034 fatal("compress failed: " + llvm::toString(std::move(E)));
1035
1036 // Update section headers.
1037 Sec->Size = sizeof(Elf_Chdr) + Sec->CompressedData.size();
1038 Sec->Flags |= SHF_COMPRESSED;
1039}
1040
Rafael Espindola55b169b2017-05-24 18:08:04 +00001041template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) {
George Rimar11240012017-06-06 07:46:28 +00001042 if (Sec->Type == SHT_NOBITS)
1043 return;
1044
Rafael Espindola55b169b2017-05-24 18:08:04 +00001045 Sec->Loc = Buf;
1046
Rui Ueyamae6d8c1c2017-06-16 22:45:13 +00001047 // If -compress-debug-section is specified and if this is a debug seciton,
1048 // we've already compressed section contents. If that's the case,
1049 // just write it down.
Rafael Espindola55b169b2017-05-24 18:08:04 +00001050 if (!Sec->CompressedData.empty()) {
1051 memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size());
1052 memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(),
1053 Sec->CompressedData.size());
1054 return;
1055 }
1056
1057 // Write leading padding.
Rafael Espindola969c6512017-05-31 20:22:27 +00001058 std::vector<InputSection *> Sections;
1059 for (BaseCommand *Cmd : Commands)
1060 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
1061 for (InputSection *IS : ISD->Sections)
1062 if (IS->Live)
1063 Sections.push_back(IS);
Rafael Espindola55b169b2017-05-24 18:08:04 +00001064 uint32_t Filler = getFiller();
1065 if (Filler)
1066 fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler);
1067
1068 parallelForEachN(0, Sections.size(), [=](size_t I) {
1069 InputSection *IS = Sections[I];
1070 IS->writeTo<ELFT>(Buf);
1071
1072 // Fill gaps between sections.
1073 if (Filler) {
1074 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
1075 uint8_t *End;
1076 if (I + 1 == Sections.size())
1077 End = Buf + Sec->Size;
1078 else
1079 End = Buf + Sections[I + 1]->OutSecOff;
1080 fill(Start, End - Start, Filler);
1081 }
1082 });
1083
1084 // Linker scripts may have BYTE()-family commands with which you
1085 // can write arbitrary bytes to the output. Process them if any.
1086 for (BaseCommand *Base : Commands)
1087 if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1088 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +00001089}
1090
Rafael Espindoladc1ed122017-05-10 14:12:02 +00001091bool LinkerScript::hasLMA(OutputSection *Sec) {
Rafael Espindolafa948c72017-05-10 19:00:23 +00001092 if (OutputSectionCommand *Cmd = getCmd(Sec))
1093 if (Cmd->LMAExpr)
1094 return true;
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001095 return false;
George Rimar8ceadb32016-08-17 07:44:19 +00001096}
1097
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001098ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +00001099 if (S == ".")
George Rimar41c7ab42017-06-07 08:54:43 +00001100 return {CurOutSec, Dot - CurOutSec->Addr, Loc};
George Rimara8dba482017-03-20 10:09:58 +00001101 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001102 if (auto *D = dyn_cast<DefinedRegular>(B))
George Rimar41c7ab42017-06-07 08:54:43 +00001103 return {D->Section, D->Value, Loc};
Petr Hosek30f16b22017-03-23 03:52:34 +00001104 if (auto *C = dyn_cast<DefinedCommon>(B))
George Rimar41c7ab42017-06-07 08:54:43 +00001105 return {InX::Common, C->Offset, Loc};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001106 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001107 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +00001108 return 0;
1109}
1110
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001111bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +00001112
Andrew Ng6e9f98c2017-06-19 15:28:58 +00001113static const size_t NoPhdr = -1;
1114
Rafael Espindola2c923c22017-05-10 14:28:31 +00001115// Returns indices of ELF headers containing specific section. Each index is a
1116// zero based number of ELF header listed within PHDRS {} script block.
1117std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Sec) {
Rafael Espindolafa948c72017-05-10 19:00:23 +00001118 if (OutputSectionCommand *Cmd = getCmd(Sec)) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001119 std::vector<size_t> Ret;
Andrew Ng6e9f98c2017-06-19 15:28:58 +00001120 for (StringRef PhdrName : Cmd->Phdrs) {
1121 size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
1122 if (Index != NoPhdr)
1123 Ret.push_back(Index);
1124 }
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001125 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001126 }
George Rimar31d842f2016-07-20 16:43:03 +00001127 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001128}
1129
Andrew Ng6e9f98c2017-06-19 15:28:58 +00001130// Returns the index of the segment named PhdrName if found otherwise
1131// NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
1132// (which can be used to explicitly specify that a section isn't assigned to a
1133// segment) then error.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001134size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001135 size_t I = 0;
1136 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1137 if (Cmd.Name == PhdrName)
1138 return I;
1139 ++I;
1140 }
Andrew Ng6e9f98c2017-06-19 15:28:58 +00001141 if (PhdrName != "NONE")
1142 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1143 return NoPhdr;
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001144}
Rafael Espindola55b169b2017-05-24 18:08:04 +00001145
1146template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf);
1147template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf);
1148template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf);
1149template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf);
Rafael Espindola68880722017-06-01 16:57:48 +00001150
1151template void OutputSectionCommand::maybeCompress<ELF32LE>();
1152template void OutputSectionCommand::maybeCompress<ELF32BE>();
1153template void OutputSectionCommand::maybeCompress<ELF64LE>();
1154template void OutputSectionCommand::maybeCompress<ELF64BE>();
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001155
1156template void OutputSectionCommand::finalize<ELF32LE>();
1157template void OutputSectionCommand::finalize<ELF32BE>();
1158template void OutputSectionCommand::finalize<ELF64LE>();
1159template void OutputSectionCommand::finalize<ELF64BE>();