blob: 835706d591e55149cd8dccf604ed8258e17e09d3 [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();
George Rimar8c804d92017-07-12 14:50:25 +0000114 if (Val < Dot && InSec)
115 error(Loc + ": unable to move location counter backward for: " +
116 CurAddressState->OutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000117 Dot = Val;
118 // Update to location counter means update to section size.
119 if (InSec)
Peter Smith906e9a12017-07-07 09:11:27 +0000120 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
Rafael Espindola679828f2017-02-17 16:26:13 +0000121}
122
George Rimarb2b70972017-02-07 10:23:28 +0000123// Sets value of a symbol. Two kinds of symbols are processed: synthetic
124// symbols, whose value is an offset from beginning of section and regular
125// symbols whose value is absolute.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000126void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000127 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000128 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000129 return;
130 }
131
George Rimarb2b70972017-02-07 10:23:28 +0000132 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000133 return;
134
Rafael Espindola5616adf2017-03-08 22:36:28 +0000135 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000136 ExprValue V = Cmd->Expression();
137 if (V.isAbsolute()) {
138 Sym->Value = V.getValue();
139 } else {
140 Sym->Section = V.Sec;
Rafael Espindoladece2802017-06-13 20:57:43 +0000141 Sym->Value = alignTo(V.Val, V.Alignment);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000142 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000143}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000144
George Rimara8dba482017-03-20 10:09:58 +0000145static SymbolBody *findSymbol(StringRef S) {
146 switch (Config->EKind) {
147 case ELF32LEKind:
148 return Symtab<ELF32LE>::X->find(S);
149 case ELF32BEKind:
150 return Symtab<ELF32BE>::X->find(S);
151 case ELF64LEKind:
152 return Symtab<ELF64LE>::X->find(S);
153 case ELF64BEKind:
154 return Symtab<ELF64BE>::X->find(S);
155 default:
156 llvm_unreachable("unknown Config->EKind");
157 }
158}
159
160static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
161 switch (Config->EKind) {
162 case ELF32LEKind:
163 return addRegular<ELF32LE>(Cmd);
164 case ELF32BEKind:
165 return addRegular<ELF32BE>(Cmd);
166 case ELF64LEKind:
167 return addRegular<ELF64LE>(Cmd);
168 case ELF64BEKind:
169 return addRegular<ELF64BE>(Cmd);
170 default:
171 llvm_unreachable("unknown Config->EKind");
172 }
173}
174
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000175void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000176 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000177 return;
178
179 // If a symbol was in PROVIDE(), we need to define it only when
180 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000181 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000182 if (Cmd->Provide && (!B || B->isDefined()))
183 return;
184
George Rimara8dba482017-03-20 10:09:58 +0000185 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000186}
187
George Rimar076fe152016-07-21 06:43:01 +0000188bool SymbolAssignment::classof(const BaseCommand *C) {
189 return C->Kind == AssignmentKind;
190}
191
192bool OutputSectionCommand::classof(const BaseCommand *C) {
193 return C->Kind == OutputSectionKind;
194}
195
Rafael Espindola55b169b2017-05-24 18:08:04 +0000196// Fill [Buf, Buf + Size) with Filler.
197// This is used for linker script "=fillexp" command.
198static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
199 size_t I = 0;
200 for (; I + 4 < Size; I += 4)
201 memcpy(Buf + I, &Filler, 4);
202 memcpy(Buf + I, &Filler, Size - I);
203}
204
George Rimareea31142016-07-21 14:26:59 +0000205bool InputSectionDescription::classof(const BaseCommand *C) {
206 return C->Kind == InputSectionKind;
207}
208
George Rimareefa7582016-08-04 09:29:31 +0000209bool AssertCommand::classof(const BaseCommand *C) {
210 return C->Kind == AssertKind;
211}
212
George Rimare38cbab2016-09-26 19:22:50 +0000213bool BytesDataCommand::classof(const BaseCommand *C) {
214 return C->Kind == BytesDataKind;
215}
216
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000217static StringRef basename(InputSectionBase *S) {
218 if (S->File)
219 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000220 return "";
221}
222
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000223bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000224 for (InputSectionDescription *ID : Opt.KeptSections)
225 if (ID->FilePat.match(basename(S)))
226 for (SectionPattern &P : ID->SectionPatterns)
227 if (P.SectionPat.match(S->Name))
228 return true;
George Rimareea31142016-07-21 14:26:59 +0000229 return false;
230}
231
Rui Ueyama1e77ad12017-07-13 20:30:35 +0000232// If an input string is in the form of "foo.N" where N is a number,
233// return N. Otherwise, returns 65536, which is one greater than the
234// lowest priority.
235static int getPriority(StringRef S) {
236 size_t Pos = S.rfind('.');
237 if (Pos == StringRef::npos)
238 return 65536;
239 int V;
240 if (!to_integer(S.substr(Pos + 1), V, 10))
241 return 65536;
242 return V;
243}
244
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000245// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000246static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000247getComparator(SortSectionPolicy K) {
248 switch (K) {
249 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000250 return [](InputSectionBase *A, InputSectionBase *B) {
251 // ">" is not a mistake. Sections with larger alignments are placed
252 // before sections with smaller alignments in order to reduce the
253 // amount of padding necessary. This is compatible with GNU.
254 return A->Alignment > B->Alignment;
255 };
George Rimarbe394db2016-09-16 20:21:55 +0000256 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000257 return [](InputSectionBase *A, InputSectionBase *B) {
258 return A->Name < B->Name;
259 };
George Rimarbe394db2016-09-16 20:21:55 +0000260 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000261 return [](InputSectionBase *A, InputSectionBase *B) {
262 return getPriority(A->Name) < getPriority(B->Name);
263 };
George Rimarbe394db2016-09-16 20:21:55 +0000264 default:
265 llvm_unreachable("unknown sort policy");
266 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000267}
George Rimar0702c4e2016-07-29 15:32:46 +0000268
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000269// A helper function for the SORT() command.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000270static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000271 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000272 if (Kind == ConstraintKind::NoConstraint)
273 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000274
275 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
276 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000277 });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000278
Rafael Espindolae746e522016-09-21 18:33:44 +0000279 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
280 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000281}
282
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000283static void sortSections(InputSection **Begin, InputSection **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000284 SortSectionPolicy K) {
285 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000286 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000287}
288
Rafael Espindolad3190792016-09-16 15:10:23 +0000289// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000290std::vector<InputSection *>
Rui Ueyama72e107f2017-04-05 02:05:48 +0000291LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000292 std::vector<InputSection *> Ret;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000293
Rui Ueyama72e107f2017-04-05 02:05:48 +0000294 // Collects all sections that satisfy constraints of Cmd.
295 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
296 size_t SizeBefore = Ret.size();
297
298 for (InputSectionBase *Sec : InputSections) {
299 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000300 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000301
Rafael Espindolae39709b2017-05-30 20:40:03 +0000302 if (!Sec->Live) {
303 reportDiscarded(Sec);
304 continue;
305 }
306
Rafael Espindola908a3d32017-02-16 14:36:09 +0000307 // For -emit-relocs we have to ignore entries like
308 // .rela.dyn : { *(.rela.data) }
309 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000310 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000311 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000312
Rui Ueyama72e107f2017-04-05 02:05:48 +0000313 StringRef Filename = basename(Sec);
314 if (!Cmd->FilePat.match(Filename) ||
315 Pat.ExcludedFilePat.match(Filename) ||
316 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000317 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000318
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000319 Ret.push_back(cast<InputSection>(Sec));
Rui Ueyama72e107f2017-04-05 02:05:48 +0000320 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000321 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000322
George Rimar07171f22016-09-21 15:56:44 +0000323 // Sort sections as instructed by SORT-family commands and --sort-section
324 // option. Because SORT-family commands can be nested at most two depth
325 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
326 // line option is respected even if a SORT command is given, the exact
327 // behavior we have here is a bit complicated. Here are the rules.
328 //
329 // 1. If two SORT commands are given, --sort-section is ignored.
330 // 2. If one SORT command is given, and if it is not SORT_NONE,
331 // --sort-section is handled as an inner SORT command.
332 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
333 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000334 InputSection **Begin = Ret.data() + SizeBefore;
335 InputSection **End = Ret.data() + Ret.size();
George Rimar07171f22016-09-21 15:56:44 +0000336 if (Pat.SortOuter != SortSectionPolicy::None) {
337 if (Pat.SortInner == SortSectionPolicy::Default)
338 sortSections(Begin, End, Config->SortSection);
339 else
340 sortSections(Begin, End, Pat.SortInner);
341 sortSections(Begin, End, Pat.SortOuter);
342 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000343 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000344 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000345}
346
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000347void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000348 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000349 S->Live = false;
Rafael Espindola4f1fca2702017-06-16 23:53:36 +0000350 if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
351 S == InX::DynStrTab)
Rafael Espindola2af64b02017-06-16 23:45:35 +0000352 error("discarding " + S->Name + " section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000353 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000354 }
355}
356
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000357std::vector<InputSectionBase *>
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000358LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000359 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000360
Rui Ueyama8f99f732017-04-05 03:20:42 +0000361 for (BaseCommand *Base : OutCmd.Commands) {
362 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000363 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000364 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000365
366 Cmd->Sections = computeInputSections(Cmd);
Rafael Espindolae4c8b9b2017-04-07 16:10:46 +0000367 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000368 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000369
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000370 return Ret;
371}
372
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000373void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000374 // A symbol can be assigned before any section is mentioned in the linker
375 // script. In an DSO, the symbol values are addresses, so the only important
376 // section values are:
377 // * SHN_UNDEF
378 // * SHN_ABS
379 // * Any value meaning a regular section.
380 // To handle that, create a dummy aether section that fills the void before
381 // the linker scripts switches to another section. It has an index of one
382 // which will map to whatever the first actual section is.
383 Aether = make<OutputSection>("", 0, SHF_ALLOC);
384 Aether->SectionIndex = 1;
Peter Smith906e9a12017-07-07 09:11:27 +0000385 auto State = make_unique<AddressState>(Opt);
Peter Smithc1ace402017-07-11 09:28:27 +0000386 // CurAddressState captures the local AddressState and makes it accessible
387 // deliberately. This is needed as there are some cases where we cannot just
388 // thread the current state through to a lambda function created by the
389 // script parser.
Peter Smith906e9a12017-07-07 09:11:27 +0000390 CurAddressState = State.get();
391 CurAddressState->OutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000392 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000393
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000394 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000395 // Handle symbol assignments outside of any output section.
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000396 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000397 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000398 continue;
399 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000400
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000401 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000402 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000403
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000404 // The output section name `/DISCARD/' is special.
405 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000406 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000407 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000408 continue;
409 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000410
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000411 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
412 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
413 // sections satisfy a given constraint. If not, a directive is handled
George Rimar07d7c422017-04-05 09:19:29 +0000414 // as if it wasn't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000415 //
416 // Because we'll iterate over Commands many more times, the easiest
George Rimar07d7c422017-04-05 09:19:29 +0000417 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000418 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000419 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000420 S->Assigned = false;
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000421 Opt.Commands.erase(Opt.Commands.begin() + I);
George Rimar07d7c422017-04-05 09:19:29 +0000422 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000423 continue;
424 }
425
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000426 // A directive may contain symbol definitions like this:
427 // ".foo : { ...; bar = .; }". Handle them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000428 for (BaseCommand *Base : Cmd->Commands)
429 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000430 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000431
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000432 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
433 // is given, input sections are aligned to that value, whether the
434 // given value is larger or smaller than the original section alignment.
435 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000436 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000437 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000438 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000439 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000440
441 // Add input sections to an output section.
George Rimard86a4e52017-05-08 10:18:12 +0000442 for (InputSectionBase *S : V)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000443 Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000444 if (OutputSection *Sec = Cmd->Sec) {
445 assert(Sec->SectionIndex == INT_MAX);
446 Sec->SectionIndex = I;
George Rimarfbb04632017-06-07 16:31:08 +0000447 if (Cmd->Noload)
448 Sec->Type = SHT_NOBITS;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000449 SecToCommand[Sec] = Cmd;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000450 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000451 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000452 }
Peter Smithc1ace402017-07-11 09:28:27 +0000453 CurAddressState = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000454}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000455
Rafael Espindola02ed7572017-05-04 19:34:17 +0000456void LinkerScript::fabricateDefaultCommands() {
Peter Smithcbfe9e92017-04-19 12:46:32 +0000457 std::vector<BaseCommand *> Commands;
458
459 // Define start address
Rafael Espindolae76231b2017-06-08 04:17:04 +0000460 uint64_t StartAddr = -1;
Peter Smithcbfe9e92017-04-19 12:46:32 +0000461
Peter Smithc60b4512017-05-03 08:44:50 +0000462 // The Sections with -T<section> have been sorted in order of ascending
463 // address. We must lower StartAddr if the lowest -T<section address> as
464 // calls to setDot() must be monotonically increasing.
George Rimar67c60722017-07-18 11:55:35 +0000465 for (auto &KV : Config->SectionStartMap)
Peter Smithc60b4512017-05-03 08:44:50 +0000466 StartAddr = std::min(StartAddr, KV.second);
467
Rafael Espindolae76231b2017-06-08 04:17:04 +0000468 Commands.push_back(make<SymbolAssignment>(
469 ".",
470 [=] {
471 return std::min(StartAddr, Config->ImageBase + elf::getHeaderSize());
472 },
473 ""));
Peter Smithcbfe9e92017-04-19 12:46:32 +0000474
475 // For each OutputSection that needs a VA fabricate an OutputSectionCommand
476 // with an InputSectionDescription describing the InputSections
Rafael Espindolaf51c8052017-06-13 23:26:31 +0000477 for (OutputSection *Sec : OutputSections) {
Rafael Espindola05c4f672017-06-01 01:16:50 +0000478 auto *OSCmd = createOutputSectionCommand(Sec->Name, "<internal>");
Peter Smithc60b4512017-05-03 08:44:50 +0000479 OSCmd->Sec = Sec;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000480 SecToCommand[Sec] = OSCmd;
Peter Smithc60b4512017-05-03 08:44:50 +0000481
Peter Smithcbfe9e92017-04-19 12:46:32 +0000482 Commands.push_back(OSCmd);
483 if (Sec->Sections.size()) {
484 auto *ISD = make<InputSectionDescription>("");
485 OSCmd->Commands.push_back(ISD);
486 for (InputSection *ISec : Sec->Sections) {
487 ISD->Sections.push_back(ISec);
488 ISec->Assigned = true;
489 }
490 }
491 }
492 // SECTIONS commands run before other non SECTIONS commands
493 Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
494 Opt.Commands = std::move(Commands);
495}
496
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000497// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000498void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rafael Espindolad7faa912017-07-05 17:50:43 +0000499 unsigned NumCommands = Opt.Commands.size();
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000500 for (InputSectionBase *S : InputSections) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000501 if (!S->Live || S->Parent)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000502 continue;
503 StringRef Name = getOutputSectionName(S->Name);
Rafael Espindolad7faa912017-07-05 17:50:43 +0000504 auto End = Opt.Commands.begin() + NumCommands;
505 auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
George Rimara951d5c2017-07-04 13:10:37 +0000506 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
507 return Cmd->Name == Name;
508 return false;
509 });
Rafael Espindolad7faa912017-07-05 17:50:43 +0000510 OutputSectionCommand *Cmd;
511 if (I == End) {
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000512 Factory.addInputSec(S, Name);
Rafael Espindolad7faa912017-07-05 17:50:43 +0000513 OutputSection *Sec = S->getOutputSection();
514 assert(Sec->SectionIndex == INT_MAX);
515 OutputSectionCommand *&CmdRef = SecToCommand[Sec];
516 if (!CmdRef) {
517 CmdRef = createOutputSectionCommand(Sec->Name, "<internal>");
518 CmdRef->Sec = Sec;
519 Opt.Commands.push_back(CmdRef);
520 }
521 Cmd = CmdRef;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000522 } else {
Rafael Espindolad7faa912017-07-05 17:50:43 +0000523 Cmd = cast<OutputSectionCommand>(*I);
Rafael Espindolade8d9892017-04-29 15:44:03 +0000524 Factory.addInputSec(S, Name, Cmd->Sec);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000525 if (OutputSection *Sec = Cmd->Sec) {
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000526 SecToCommand[Sec] = Cmd;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000527 unsigned Index = std::distance(Opt.Commands.begin(), I);
528 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
529 Sec->SectionIndex = Index;
530 }
Rafael Espindolade8d9892017-04-29 15:44:03 +0000531 }
Rafael Espindolad7faa912017-07-05 17:50:43 +0000532 auto *ISD = make<InputSectionDescription>("");
533 ISD->Sections.push_back(cast<InputSection>(S));
534 Cmd->Commands.push_back(ISD);
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000535 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000536}
537
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000538uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
Peter Smith906e9a12017-07-07 09:11:27 +0000539 bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
540 CurAddressState->OutSec->Type == SHT_NOBITS;
541 uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000542 Start = alignTo(Start, Align);
543 uint64_t End = Start + Size;
544
545 if (IsTbss)
Peter Smith906e9a12017-07-07 09:11:27 +0000546 CurAddressState->ThreadBssOffset = End - Dot;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000547 else
548 Dot = End;
549 return End;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000550}
551
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000552void LinkerScript::output(InputSection *S) {
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000553 uint64_t Pos = advance(S->getSize(), S->Alignment);
Peter Smith906e9a12017-07-07 09:11:27 +0000554 S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000555
556 // Update output section size after adding each section. This is so that
557 // SIZEOF works correctly in the case below:
558 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Peter Smith906e9a12017-07-07 09:11:27 +0000559 CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000560
Meador Ingeb8897442017-01-24 02:34:00 +0000561 // If there is a memory region associated with this input section, then
562 // place the section in that region and update the region index.
Peter Smith906e9a12017-07-07 09:11:27 +0000563 if (CurAddressState->MemRegion) {
564 uint64_t &CurOffset =
565 CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
566 CurOffset += CurAddressState->OutSec->Size;
567 uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
568 if (CurSize > CurAddressState->MemRegion->Length) {
569 uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
570 error("section '" + CurAddressState->OutSec->Name +
571 "' will not fit in region '" + CurAddressState->MemRegion->Name +
572 "': overflowed by " + Twine(OverflowAmt) + " bytes");
Meador Ingeb8897442017-01-24 02:34:00 +0000573 }
574 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000575}
576
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000577void LinkerScript::switchTo(OutputSection *Sec) {
Peter Smith906e9a12017-07-07 09:11:27 +0000578 if (CurAddressState->OutSec == Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000579 return;
Rafael Espindolad3190792016-09-16 15:10:23 +0000580
Peter Smith906e9a12017-07-07 09:11:27 +0000581 CurAddressState->OutSec = Sec;
582 CurAddressState->OutSec->Addr =
583 advance(0, CurAddressState->OutSec->Alignment);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000584
585 // If neither AT nor AT> is specified for an allocatable section, the linker
586 // will set the LMA such that the difference between VMA and LMA for the
587 // section is the same as the preceding output section in the same region
588 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
Peter Smith906e9a12017-07-07 09:11:27 +0000589 if (CurAddressState->LMAOffset)
590 CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000591}
592
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000593void LinkerScript::process(BaseCommand &Base) {
Rui Ueyama2e081a42017-04-05 03:18:46 +0000594 // This handles the assignments to symbol or to the dot.
595 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
596 assignSymbol(Cmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000597 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000598 }
George Rimare38cbab2016-09-26 19:22:50 +0000599
600 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyama2e081a42017-04-05 03:18:46 +0000601 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
Peter Smith906e9a12017-07-07 09:11:27 +0000602 Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
Rui Ueyama2e081a42017-04-05 03:18:46 +0000603 Dot += Cmd->Size;
Peter Smith906e9a12017-07-07 09:11:27 +0000604 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000605 return;
606 }
607
Rui Ueyama2e081a42017-04-05 03:18:46 +0000608 // Handle ASSERT().
609 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
610 Cmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000611 return;
612 }
613
Rui Ueyama2e081a42017-04-05 03:18:46 +0000614 // Handle a single input section description command.
615 // It calculates and assigns the offsets for each section and also
George Rimare38cbab2016-09-26 19:22:50 +0000616 // updates the output section size.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000617 auto &Cmd = cast<InputSectionDescription>(Base);
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000618 for (InputSection *Sec : Cmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000619 // We tentatively added all synthetic sections at the beginning and removed
620 // empty ones afterwards (because there is no way to know whether they were
621 // going be empty or not other than actually running linker scripts.)
622 // We need to ignore remains of empty sections.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000623 if (auto *S = dyn_cast<SyntheticSection>(Sec))
624 if (S->empty())
George Rimar3fb5a6d2016-11-29 16:05:27 +0000625 continue;
626
Rui Ueyama2e081a42017-04-05 03:18:46 +0000627 if (!Sec->Live)
George Rimar78ef6452017-02-21 15:46:43 +0000628 continue;
Peter Smith906e9a12017-07-07 09:11:27 +0000629 assert(CurAddressState->OutSec == Sec->getParent());
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000630 output(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000631 }
632}
633
Meador Ingeb8897442017-01-24 02:34:00 +0000634// This function searches for a memory region to place the given output
635// section in. If found, a pointer to the appropriate memory region is
636// returned. Otherwise, a nullptr is returned.
Rafael Espindola1902b332017-04-06 21:26:03 +0000637MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
Meador Ingeb8897442017-01-24 02:34:00 +0000638 // If a memory region name was specified in the output section command,
639 // then try to find that region first.
640 if (!Cmd->MemoryRegionName.empty()) {
641 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
642 if (It != Opt.MemoryRegions.end())
643 return &It->second;
644 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
645 return nullptr;
646 }
647
Rui Ueyamad7c54002017-04-05 03:19:43 +0000648 // If at least one memory region is defined, all sections must
649 // belong to some memory region. Otherwise, we don't need to do
650 // anything for memory regions.
Rui Ueyamacc400cc2017-04-05 03:19:24 +0000651 if (Opt.MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000652 return nullptr;
653
Rafael Espindola1902b332017-04-06 21:26:03 +0000654 OutputSection *Sec = Cmd->Sec;
Meador Ingeb8897442017-01-24 02:34:00 +0000655 // See if a region can be found by matching section flags.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000656 for (auto &Pair : Opt.MemoryRegions) {
657 MemoryRegion &M = Pair.second;
658 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
659 return &M;
Meador Ingeb8897442017-01-24 02:34:00 +0000660 }
661
662 // Otherwise, no suitable region was found.
663 if (Sec->Flags & SHF_ALLOC)
664 error("no memory region specified for section '" + Sec->Name + "'");
665 return nullptr;
666}
667
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000668// This function assigns offsets to input sections and an output section
669// for a single sections command (e.g. ".text { *(.text); }").
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000670void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
Rafael Espindola9b980092017-04-06 21:05:39 +0000671 OutputSection *Sec = Cmd->Sec;
Rafael Espindola2b074552017-02-03 22:27:05 +0000672 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000673 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000674
Rafael Espindoladece2802017-06-13 20:57:43 +0000675 if (!(Sec->Flags & SHF_ALLOC))
676 Dot = 0;
677 else if (Cmd->AddrExpr)
Rui Ueyamad379f732017-04-05 03:20:22 +0000678 setDot(Cmd->AddrExpr, Cmd->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000679
Eugene Leviant5784e962017-03-14 08:57:09 +0000680 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000681 uint64_t D = Dot;
Peter Smith906e9a12017-07-07 09:11:27 +0000682 CurAddressState->LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000683 }
684
Peter Smith906e9a12017-07-07 09:11:27 +0000685 CurAddressState->MemRegion = Cmd->MemRegion;
686 if (CurAddressState->MemRegion)
687 Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
Meador Ingeb8897442017-01-24 02:34:00 +0000688 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000689
George Rimard86a4e52017-05-08 10:18:12 +0000690 // We do not support custom layout for compressed debug sectons.
691 // At this point we already know their size and have compressed content.
Peter Smith906e9a12017-07-07 09:11:27 +0000692 if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
George Rimard86a4e52017-05-08 10:18:12 +0000693 return;
694
Rafael Espindolade8d9892017-04-29 15:44:03 +0000695 for (BaseCommand *C : Cmd->Commands)
696 process(*C);
Rafael Espindolad3190792016-09-16 15:10:23 +0000697}
698
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000699void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000700 // It is common practice to use very generic linker scripts. So for any
701 // given run some of the output sections in the script will be empty.
702 // We could create corresponding empty output sections, but that would
703 // clutter the output.
704 // We instead remove trivially empty sections. The bfd linker seems even
705 // more aggressive at removing them.
706 auto Pos = std::remove_if(
Rui Ueyama8f99f732017-04-05 03:20:42 +0000707 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
708 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
Rafael Espindolae86fddd2017-06-13 23:54:34 +0000709 return Cmd->Sec == nullptr;
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000710 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000711 });
712 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000713}
714
Rafael Espindola6a537372016-11-14 14:33:49 +0000715static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000716 for (BaseCommand *Base : Cmd.Commands)
717 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000718 return false;
719 return true;
720}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000721
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000722void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000723 // If the output section contains only symbol assignments, create a
724 // corresponding output section. The bfd linker seems to only create them if
725 // '.' is assigned to, but creating these section should not have any bad
726 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000727 uint64_t Flags = SHF_ALLOC;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000728
729 for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
730 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000731 if (!Cmd)
732 continue;
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000733 if (OutputSection *Sec = Cmd->Sec) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000734 Flags = Sec->Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000735 continue;
736 }
737
Rafael Espindola6a537372016-11-14 14:33:49 +0000738 if (isAllSectionDescription(*Cmd))
739 continue;
740
Dmitry Mikulinfd0c8442017-05-24 16:48:31 +0000741 auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000742 OutSec->SectionIndex = I;
Rafael Espindola9b980092017-04-06 21:05:39 +0000743 Cmd->Sec = OutSec;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000744 SecToCommand[OutSec] = Cmd;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000745 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000746}
747
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000748void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000749 // Try and find an appropriate memory region to assign offsets in.
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000750 for (BaseCommand *Base : Opt.Commands) {
751 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000752 Cmd->MemRegion = findMemoryRegion(Cmd);
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000753 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
Rafael Espindolaca5740d2017-07-22 00:00:51 +0000754 if (Cmd->AlignExpr && Cmd->Sec)
George Rimar67c60722017-07-18 11:55:35 +0000755 Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000756 }
757 }
Rafael Espindolafeed7502017-04-06 21:31:24 +0000758
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000759 // If output section command doesn't specify any segments,
760 // and we haven't previously assigned any section to segment,
761 // then we simply assign section to the very first load segment.
762 // Below is an example of such linker script:
763 // PHDRS { seg PT_LOAD; }
764 // SECTIONS { .aaa : { *(.aaa) } }
765 std::vector<StringRef> DefPhdrs;
766 auto FirstPtLoad =
767 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
768 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
769 if (FirstPtLoad != Opt.PhdrsCommands.end())
770 DefPhdrs.push_back(FirstPtLoad->Name);
771
772 // Walk the commands and propagate the program headers to commands that don't
773 // explicitly specify them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000774 for (BaseCommand *Base : Opt.Commands) {
775 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000776 if (!Cmd)
777 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000778
Andrew Nga020d342017-07-03 10:11:25 +0000779 if (Cmd->Phdrs.empty()) {
780 OutputSection *Sec = Cmd->Sec;
781 // To match the bfd linker script behaviour, only propagate program
782 // headers to sections that are allocated.
783 if (Sec && (Sec->Flags & SHF_ALLOC))
784 Cmd->Phdrs = DefPhdrs;
785 } else {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000786 DefPhdrs = Cmd->Phdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000787 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000788 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000789
790 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000791}
792
Peter Smith5aedebf2017-07-05 09:12:54 +0000793void LinkerScript::allocateHeaders(std::vector<PhdrEntry> &Phdrs) {
794 uint64_t Min = std::numeric_limits<uint64_t>::max();
795 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
796 OutputSection *Sec = Cmd->Sec;
797 if (Sec->Flags & SHF_ALLOC)
798 Min = std::min<uint64_t>(Min, Sec->Addr);
799 }
800
George Rimard971e702017-07-03 16:05:51 +0000801 auto FirstPTLoad = llvm::find_if(
802 Phdrs, [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
Rafael Espindola02ed7572017-05-04 19:34:17 +0000803 if (FirstPTLoad == Phdrs.end())
George Rimard971e702017-07-03 16:05:51 +0000804 return;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000805
806 uint64_t HeaderSize = getHeaderSize();
807 if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
808 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
809 Out::ElfHeader->Addr = Min;
810 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
George Rimard971e702017-07-03 16:05:51 +0000811 return;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000812 }
813
814 assert(FirstPTLoad->First == Out::ElfHeader);
815 OutputSection *ActualFirst = nullptr;
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000816 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
817 OutputSection *Sec = Cmd->Sec;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000818 if (Sec->FirstInPtLoad == Out::ElfHeader) {
819 ActualFirst = Sec;
820 break;
821 }
822 }
823 if (ActualFirst) {
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000824 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
825 OutputSection *Sec = Cmd->Sec;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000826 if (Sec->FirstInPtLoad == Out::ElfHeader)
827 Sec->FirstInPtLoad = ActualFirst;
Rafael Espindolafaf25a72017-06-01 16:26:28 +0000828 }
Rafael Espindola02ed7572017-05-04 19:34:17 +0000829 FirstPTLoad->First = ActualFirst;
830 } else {
831 Phdrs.erase(FirstPTLoad);
832 }
833
George Rimard971e702017-07-03 16:05:51 +0000834 auto PhdrI = llvm::find_if(
835 Phdrs, [](const PhdrEntry &E) { return E.p_type == PT_PHDR; });
Rafael Espindola02ed7572017-05-04 19:34:17 +0000836 if (PhdrI != Phdrs.end())
837 Phdrs.erase(PhdrI);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000838}
839
Peter Smith906e9a12017-07-07 09:11:27 +0000840LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
841 for (auto &MRI : Opt.MemoryRegions) {
842 const MemoryRegion *MR = &MRI.second;
843 MemRegionOffset[MR] = MR->Origin;
844 }
845}
846
Peter Smith5aedebf2017-07-05 09:12:54 +0000847void LinkerScript::assignAddresses() {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000848 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000849 Dot = 0;
Peter Smith906e9a12017-07-07 09:11:27 +0000850 auto State = make_unique<AddressState>(Opt);
Peter Smithc1ace402017-07-11 09:28:27 +0000851 // CurAddressState captures the local AddressState and makes it accessible
852 // deliberately. This is needed as there are some cases where we cannot just
853 // thread the current state through to a lambda function created by the
854 // script parser.
Peter Smith906e9a12017-07-07 09:11:27 +0000855 CurAddressState = State.get();
Rafael Espindola72dc1952017-03-17 13:05:04 +0000856 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000857 switchTo(Aether);
858
Rui Ueyama8f99f732017-04-05 03:20:42 +0000859 for (BaseCommand *Base : Opt.Commands) {
860 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
Rui Ueyamad379f732017-04-05 03:20:22 +0000861 assignSymbol(Cmd, false);
George Rimar652852c2016-04-16 10:10:32 +0000862 continue;
863 }
864
Rui Ueyama8f99f732017-04-05 03:20:42 +0000865 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000866 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000867 continue;
868 }
869
Rui Ueyama8f99f732017-04-05 03:20:42 +0000870 auto *Cmd = cast<OutputSectionCommand>(Base);
Rafael Espindolad3190792016-09-16 15:10:23 +0000871 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000872 }
Peter Smithc1ace402017-07-11 09:28:27 +0000873 CurAddressState = nullptr;
George Rimar652852c2016-04-16 10:10:32 +0000874}
875
Rui Ueyama464daad2016-08-22 04:55:20 +0000876// Creates program headers as instructed by PHDRS linker script command.
Rafael Espindolaf51c8052017-06-13 23:26:31 +0000877std::vector<PhdrEntry> LinkerScript::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000878 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000879
Rui Ueyama464daad2016-08-22 04:55:20 +0000880 // Process PHDRS and FILEHDR keywords because they are not
881 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000882 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000883 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000884 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000885
886 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000887 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000888 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000889 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000890
891 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000892 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000893 Phdr.HasLMA = true;
894 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000895 }
896
Rui Ueyama464daad2016-08-22 04:55:20 +0000897 // Add output sections to program headers.
Rafael Espindola7ff93292017-06-10 22:12:32 +0000898 for (OutputSectionCommand *Cmd : OutputSectionCommands) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000899 // Assign headers specified by linker script
Rafael Espindola9f9e99b2017-07-05 22:30:04 +0000900 for (size_t Id : getPhdrIndices(Cmd)) {
901 OutputSection *Sec = Cmd->Sec;
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000902 Ret[Id].add(Sec);
903 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000904 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000905 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000906 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000907 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000908}
909
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000910bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000911 // Ignore .interp section in case we have PHDRS specification
912 // and PT_INTERP isn't listed.
Rui Ueyamae31d9882017-04-05 05:06:17 +0000913 if (Opt.PhdrsCommands.empty())
914 return false;
915 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
916 if (Cmd.Type == PT_INTERP)
917 return false;
918 return true;
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000919}
920
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000921OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const {
922 auto I = SecToCommand.find(Sec);
923 if (I == SecToCommand.end())
924 return nullptr;
925 return I->second;
Rafael Espindolafa948c72017-05-10 19:00:23 +0000926}
927
Rafael Espindola21263342017-07-05 23:36:24 +0000928void OutputSectionCommand::sort(std::function<int(InputSectionBase *S)> Order) {
929 typedef std::pair<unsigned, InputSection *> Pair;
930 auto Comp = [](const Pair &A, const Pair &B) { return A.first < B.first; };
931
932 std::vector<Pair> V;
933 assert(Commands.size() == 1);
934 auto *ISD = cast<InputSectionDescription>(Commands[0]);
935 for (InputSection *S : ISD->Sections)
936 V.push_back({Order(S), S});
937 std::stable_sort(V.begin(), V.end(), Comp);
938 ISD->Sections.clear();
939 for (Pair &P : V)
940 ISD->Sections.push_back(P.second);
941}
942
943// Returns true if S matches /Filename.?\.o$/.
944static bool isCrtBeginEnd(StringRef S, StringRef Filename) {
945 if (!S.endswith(".o"))
946 return false;
947 S = S.drop_back(2);
948 if (S.endswith(Filename))
949 return true;
950 return !S.empty() && S.drop_back().endswith(Filename);
951}
952
953static bool isCrtbegin(StringRef S) { return isCrtBeginEnd(S, "crtbegin"); }
954static bool isCrtend(StringRef S) { return isCrtBeginEnd(S, "crtend"); }
955
956// .ctors and .dtors are sorted by this priority from highest to lowest.
957//
958// 1. The section was contained in crtbegin (crtbegin contains
959// some sentinel value in its .ctors and .dtors so that the runtime
960// can find the beginning of the sections.)
961//
962// 2. The section has an optional priority value in the form of ".ctors.N"
963// or ".dtors.N" where N is a number. Unlike .{init,fini}_array,
964// they are compared as string rather than number.
965//
966// 3. The section is just ".ctors" or ".dtors".
967//
968// 4. The section was contained in crtend, which contains an end marker.
969//
970// In an ideal world, we don't need this function because .init_array and
971// .ctors are duplicate features (and .init_array is newer.) However, there
972// are too many real-world use cases of .ctors, so we had no choice to
973// support that with this rather ad-hoc semantics.
974static bool compCtors(const InputSection *A, const InputSection *B) {
975 bool BeginA = isCrtbegin(A->File->getName());
976 bool BeginB = isCrtbegin(B->File->getName());
977 if (BeginA != BeginB)
978 return BeginA;
979 bool EndA = isCrtend(A->File->getName());
980 bool EndB = isCrtend(B->File->getName());
981 if (EndA != EndB)
982 return EndB;
983 StringRef X = A->Name;
984 StringRef Y = B->Name;
985 assert(X.startswith(".ctors") || X.startswith(".dtors"));
986 assert(Y.startswith(".ctors") || Y.startswith(".dtors"));
987 X = X.substr(6);
988 Y = Y.substr(6);
989 if (X.empty() && Y.empty())
990 return false;
991 return X < Y;
992}
993
994// Sorts input sections by the special rules for .ctors and .dtors.
995// Unfortunately, the rules are different from the one for .{init,fini}_array.
996// Read the comment above.
997void OutputSectionCommand::sortCtorsDtors() {
998 assert(Commands.size() == 1);
999 auto *ISD = cast<InputSectionDescription>(Commands[0]);
1000 std::stable_sort(ISD->Sections.begin(), ISD->Sections.end(), compCtors);
1001}
1002
1003// Sorts input sections by section name suffixes, so that .foo.N comes
1004// before .foo.M if N < M. Used to sort .{init,fini}_array.N sections.
1005// We want to keep the original order if the priorities are the same
1006// because the compiler keeps the original initialization order in a
1007// translation unit and we need to respect that.
1008// For more detail, read the section of the GCC's manual about init_priority.
1009void OutputSectionCommand::sortInitFini() {
1010 // Sort sections by priority.
1011 sort([](InputSectionBase *S) { return getPriority(S->Name); });
1012}
1013
Rafael Espindola55b169b2017-05-24 18:08:04 +00001014uint32_t OutputSectionCommand::getFiller() {
1015 if (Filler)
1016 return *Filler;
1017 if (Sec->Flags & SHF_EXECINSTR)
1018 return Target->TrapInstr;
1019 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +00001020}
1021
George Rimare38cbab2016-09-26 19:22:50 +00001022static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001023 if (Size == 1)
1024 *Buf = Data;
1025 else if (Size == 2)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +00001026 write16(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001027 else if (Size == 4)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +00001028 write32(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001029 else if (Size == 8)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +00001030 write64(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001031 else
George Rimare38cbab2016-09-26 19:22:50 +00001032 llvm_unreachable("unsupported Size argument");
George Rimare38cbab2016-09-26 19:22:50 +00001033}
1034
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001035static bool compareByFilePosition(InputSection *A, InputSection *B) {
1036 // Synthetic doesn't have link order dependecy, stable_sort will keep it last
1037 if (A->kind() == InputSectionBase::Synthetic ||
1038 B->kind() == InputSectionBase::Synthetic)
1039 return false;
1040 InputSection *LA = A->getLinkOrderDep();
1041 InputSection *LB = B->getLinkOrderDep();
1042 OutputSection *AOut = LA->getParent();
1043 OutputSection *BOut = LB->getParent();
1044 if (AOut != BOut)
1045 return AOut->SectionIndex < BOut->SectionIndex;
1046 return LA->OutSecOff < LB->OutSecOff;
1047}
1048
Rafael Espindola658a0c72017-06-06 20:13:19 +00001049template <class ELFT>
1050static void finalizeShtGroup(OutputSection *OS,
1051 ArrayRef<InputSection *> Sections) {
Rui Ueyama82143d32017-06-26 17:11:36 +00001052 assert(Config->Relocatable && Sections.size() == 1);
1053
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001054 // sh_link field for SHT_GROUP sections should contain the section index of
1055 // the symbol table.
Rafael Espindola658a0c72017-06-06 20:13:19 +00001056 OS->Link = InX::SymTab->getParent()->SectionIndex;
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001057
1058 // sh_info then contain index of an entry in symbol table section which
1059 // provides signature of the section group.
Rafael Espindola658a0c72017-06-06 20:13:19 +00001060 elf::ObjectFile<ELFT> *Obj = Sections[0]->getFile<ELFT>();
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001061 ArrayRef<SymbolBody *> Symbols = Obj->getSymbols();
Rafael Espindola658a0c72017-06-06 20:13:19 +00001062 OS->Info = InX::SymTab->getSymbolIndex(Symbols[Sections[0]->Info - 1]);
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001063}
1064
1065template <class ELFT> void OutputSectionCommand::finalize() {
Rafael Espindola658a0c72017-06-06 20:13:19 +00001066 // Link order may be distributed across several InputSectionDescriptions
1067 // but sort must consider them all at once.
1068 std::vector<InputSection **> ScriptSections;
1069 std::vector<InputSection *> Sections;
1070 for (BaseCommand *Base : Commands)
1071 if (auto *ISD = dyn_cast<InputSectionDescription>(Base))
1072 for (InputSection *&IS : ISD->Sections) {
1073 ScriptSections.push_back(&IS);
1074 Sections.push_back(IS);
1075 }
1076
1077 if ((Sec->Flags & SHF_LINK_ORDER)) {
Shoaib Meenaie1d77762017-07-17 19:42:19 +00001078 std::stable_sort(Sections.begin(), Sections.end(), compareByFilePosition);
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001079 for (int I = 0, N = Sections.size(); I < N; ++I)
1080 *ScriptSections[I] = Sections[I];
1081
1082 // We must preserve the link order dependency of sections with the
1083 // SHF_LINK_ORDER flag. The dependency is indicated by the sh_link field. We
1084 // need to translate the InputSection sh_link to the OutputSection sh_link,
1085 // all InputSections in the OutputSection have the same dependency.
Rafael Espindola658a0c72017-06-06 20:13:19 +00001086 if (auto *D = Sections.front()->getLinkOrderDep())
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001087 Sec->Link = D->getParent()->SectionIndex;
1088 }
1089
1090 uint32_t Type = Sec->Type;
1091 if (Type == SHT_GROUP) {
Rafael Espindola658a0c72017-06-06 20:13:19 +00001092 finalizeShtGroup<ELFT>(Sec, Sections);
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001093 return;
1094 }
1095
1096 if (!Config->CopyRelocs || (Type != SHT_RELA && Type != SHT_REL))
1097 return;
1098
Rafael Espindola658a0c72017-06-06 20:13:19 +00001099 InputSection *First = Sections[0];
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001100 if (isa<SyntheticSection>(First))
1101 return;
1102
1103 Sec->Link = InX::SymTab->getParent()->SectionIndex;
1104 // sh_info for SHT_REL[A] sections should contain the section header index of
1105 // the section to which the relocation applies.
1106 InputSectionBase *S = First->getRelocatedSection();
1107 Sec->Info = S->getOutputSection()->SectionIndex;
1108 Sec->Flags |= SHF_INFO_LINK;
1109}
1110
Rafael Espindola68880722017-06-01 16:57:48 +00001111// Compress section contents if this section contains debug info.
1112template <class ELFT> void OutputSectionCommand::maybeCompress() {
1113 typedef typename ELFT::Chdr Elf_Chdr;
1114
1115 // Compress only DWARF debug sections.
1116 if (!Config->CompressDebugSections || (Sec->Flags & SHF_ALLOC) ||
1117 !Name.startswith(".debug_"))
1118 return;
1119
1120 // Create a section header.
1121 Sec->ZDebugHeader.resize(sizeof(Elf_Chdr));
1122 auto *Hdr = reinterpret_cast<Elf_Chdr *>(Sec->ZDebugHeader.data());
1123 Hdr->ch_type = ELFCOMPRESS_ZLIB;
1124 Hdr->ch_size = Sec->Size;
1125 Hdr->ch_addralign = Sec->Alignment;
1126
1127 // Write section contents to a temporary buffer and compress it.
1128 std::vector<uint8_t> Buf(Sec->Size);
1129 writeTo<ELFT>(Buf.data());
1130 if (Error E = zlib::compress(toStringRef(Buf), Sec->CompressedData))
1131 fatal("compress failed: " + llvm::toString(std::move(E)));
1132
1133 // Update section headers.
1134 Sec->Size = sizeof(Elf_Chdr) + Sec->CompressedData.size();
1135 Sec->Flags |= SHF_COMPRESSED;
1136}
1137
Rafael Espindola55b169b2017-05-24 18:08:04 +00001138template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) {
George Rimar11240012017-06-06 07:46:28 +00001139 if (Sec->Type == SHT_NOBITS)
1140 return;
1141
Rafael Espindola55b169b2017-05-24 18:08:04 +00001142 Sec->Loc = Buf;
1143
Rui Ueyamae6d8c1c2017-06-16 22:45:13 +00001144 // If -compress-debug-section is specified and if this is a debug seciton,
1145 // we've already compressed section contents. If that's the case,
1146 // just write it down.
Rafael Espindola55b169b2017-05-24 18:08:04 +00001147 if (!Sec->CompressedData.empty()) {
1148 memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size());
1149 memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(),
1150 Sec->CompressedData.size());
1151 return;
1152 }
1153
1154 // Write leading padding.
Rafael Espindola969c6512017-05-31 20:22:27 +00001155 std::vector<InputSection *> Sections;
1156 for (BaseCommand *Cmd : Commands)
1157 if (auto *ISD = dyn_cast<InputSectionDescription>(Cmd))
1158 for (InputSection *IS : ISD->Sections)
1159 if (IS->Live)
1160 Sections.push_back(IS);
Rafael Espindola55b169b2017-05-24 18:08:04 +00001161 uint32_t Filler = getFiller();
1162 if (Filler)
1163 fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler);
1164
1165 parallelForEachN(0, Sections.size(), [=](size_t I) {
1166 InputSection *IS = Sections[I];
1167 IS->writeTo<ELFT>(Buf);
1168
1169 // Fill gaps between sections.
1170 if (Filler) {
1171 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
1172 uint8_t *End;
1173 if (I + 1 == Sections.size())
1174 End = Buf + Sec->Size;
1175 else
1176 End = Buf + Sections[I + 1]->OutSecOff;
1177 fill(Start, End - Start, Filler);
1178 }
1179 });
1180
1181 // Linker scripts may have BYTE()-family commands with which you
1182 // can write arbitrary bytes to the output. Process them if any.
1183 for (BaseCommand *Base : Commands)
1184 if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1185 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +00001186}
1187
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001188ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +00001189 if (S == ".")
Peter Smith906e9a12017-07-07 09:11:27 +00001190 return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr, Loc};
George Rimara8dba482017-03-20 10:09:58 +00001191 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001192 if (auto *D = dyn_cast<DefinedRegular>(B))
George Rimar41c7ab42017-06-07 08:54:43 +00001193 return {D->Section, D->Value, Loc};
Petr Hosek30f16b22017-03-23 03:52:34 +00001194 if (auto *C = dyn_cast<DefinedCommon>(B))
George Rimar41c7ab42017-06-07 08:54:43 +00001195 return {InX::Common, C->Offset, Loc};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001196 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001197 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +00001198 return 0;
1199}
1200
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001201bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +00001202
Andrew Ng6e9f98c2017-06-19 15:28:58 +00001203static const size_t NoPhdr = -1;
1204
Rafael Espindola2c923c22017-05-10 14:28:31 +00001205// Returns indices of ELF headers containing specific section. Each index is a
1206// zero based number of ELF header listed within PHDRS {} script block.
Rafael Espindola9f9e99b2017-07-05 22:30:04 +00001207std::vector<size_t> LinkerScript::getPhdrIndices(OutputSectionCommand *Cmd) {
1208 std::vector<size_t> Ret;
1209 for (StringRef PhdrName : Cmd->Phdrs) {
1210 size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
1211 if (Index != NoPhdr)
1212 Ret.push_back(Index);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001213 }
Rafael Espindola9f9e99b2017-07-05 22:30:04 +00001214 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001215}
1216
Andrew Ng6e9f98c2017-06-19 15:28:58 +00001217// Returns the index of the segment named PhdrName if found otherwise
1218// NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
1219// (which can be used to explicitly specify that a section isn't assigned to a
1220// segment) then error.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001221size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001222 size_t I = 0;
1223 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1224 if (Cmd.Name == PhdrName)
1225 return I;
1226 ++I;
1227 }
Andrew Ng6e9f98c2017-06-19 15:28:58 +00001228 if (PhdrName != "NONE")
1229 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
1230 return NoPhdr;
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001231}
Rafael Espindola55b169b2017-05-24 18:08:04 +00001232
1233template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf);
1234template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf);
1235template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf);
1236template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf);
Rafael Espindola68880722017-06-01 16:57:48 +00001237
1238template void OutputSectionCommand::maybeCompress<ELF32LE>();
1239template void OutputSectionCommand::maybeCompress<ELF32BE>();
1240template void OutputSectionCommand::maybeCompress<ELF64LE>();
1241template void OutputSectionCommand::maybeCompress<ELF64BE>();
Rafael Espindola8c284ac2017-06-06 19:40:01 +00001242
1243template void OutputSectionCommand::finalize<ELF32LE>();
1244template void OutputSectionCommand::finalize<ELF32BE>();
1245template void OutputSectionCommand::finalize<ELF64LE>();
1246template void OutputSectionCommand::finalize<ELF64BE>();