blob: a5ca4a2e6e888de75adf286f9c94941550adf1bf [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"
Eugene Zelenko22886a22016-11-05 01:00:56 +000028#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000029#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000030#include "llvm/Support/Endian.h"
31#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000032#include "llvm/Support/FileSystem.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000033#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000034#include <algorithm>
35#include <cassert>
36#include <cstddef>
37#include <cstdint>
38#include <iterator>
39#include <limits>
Eugene Zelenko22886a22016-11-05 01:00:56 +000040#include <string>
Eugene Zelenko22886a22016-11-05 01:00:56 +000041#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000042
43using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000044using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000045using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000046using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000047using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000048using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000049
Rui Ueyamaa34da932017-03-21 23:03:09 +000050LinkerScript *elf::Script;
51
Rafael Espindola72dc1952017-03-17 13:05:04 +000052uint64_t ExprValue::getValue() const {
George Rimar608cf672017-05-10 14:23:33 +000053 if (Sec) {
Rafael Espindolad54c5662017-05-31 19:53:40 +000054 if (OutputSection *OS = Sec->getOutputSection())
55 return alignTo(Sec->getOffset(Val) + OS->Addr, Alignment);
George Rimar608cf672017-05-10 14:23:33 +000056 error("unable to evaluate expression: input section " + Sec->Name +
57 " has no output section assigned");
58 }
Petr Hosek3c6de1a2017-05-30 03:18:28 +000059 return alignTo(Val, Alignment);
Rafael Espindola72dc1952017-03-17 13:05:04 +000060}
61
Rafael Espindola7ba5f472017-03-17 14:55:36 +000062uint64_t ExprValue::getSecAddr() const {
63 if (Sec)
64 return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
65 return 0;
66}
67
Meador Inge8f1f3c42017-01-09 18:36:57 +000068template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000069 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000070 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +000071 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
72 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
73 /*File*/ nullptr);
74 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +000075 ExprValue Value = Cmd->Expression();
76 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
George Rimar01aa7952017-04-14 09:23:26 +000077
78 // We want to set symbol values early if we can. This allows us to use symbols
79 // as variables in linker scripts. Doing so allows us to write expressions
80 // like this: `alignment = 16; . = ALIGN(., alignment)`
81 uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
Rui Ueyama80474a22017-02-28 19:29:55 +000082 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
George Rimar01aa7952017-04-14 09:23:26 +000083 STT_NOTYPE, SymValue, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +000084 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000085}
86
Rui Ueyamab8dd23f2017-03-21 23:02:51 +000087OutputSection *LinkerScript::getOutputSection(const Twine &Loc,
88 StringRef Name) {
George Rimar851dc1e2017-03-14 10:15:53 +000089 for (OutputSection *Sec : *OutputSections)
90 if (Sec->Name == Name)
91 return Sec;
92
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +000093 static OutputSection Dummy("", 0, 0);
Rafael Espindola72dc1952017-03-17 13:05:04 +000094 if (ErrorOnMissingSection)
95 error(Loc + ": undefined section " + Name);
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +000096 return &Dummy;
George Rimar851dc1e2017-03-14 10:15:53 +000097}
98
George Rimard83ce1b2017-03-14 10:24:47 +000099// This function is essentially the same as getOutputSection(Name)->Size,
100// but it won't print out an error message if a given section is not found.
101//
102// Linker script does not create an output section if its content is empty.
103// We want to allow SIZEOF(.foo) where .foo is a section which happened to
104// be empty. That is why this function is different from getOutputSection().
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000105uint64_t LinkerScript::getOutputSectionSize(StringRef Name) {
George Rimard83ce1b2017-03-14 10:24:47 +0000106 for (OutputSection *Sec : *OutputSections)
107 if (Sec->Name == Name)
108 return Sec->Size;
109 return 0;
110}
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;
145 if (Sym->Section->Flags & SHF_ALLOC)
Petr Hosek3c6de1a2017-05-30 03:18:28 +0000146 Sym->Value = alignTo(V.Val, V.Alignment);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000147 else
148 Sym->Value = V.getValue();
Meador Inge8f1f3c42017-01-09 18:36:57 +0000149 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000150}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000151
George Rimara8dba482017-03-20 10:09:58 +0000152static SymbolBody *findSymbol(StringRef S) {
153 switch (Config->EKind) {
154 case ELF32LEKind:
155 return Symtab<ELF32LE>::X->find(S);
156 case ELF32BEKind:
157 return Symtab<ELF32BE>::X->find(S);
158 case ELF64LEKind:
159 return Symtab<ELF64LE>::X->find(S);
160 case ELF64BEKind:
161 return Symtab<ELF64BE>::X->find(S);
162 default:
163 llvm_unreachable("unknown Config->EKind");
164 }
165}
166
167static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
168 switch (Config->EKind) {
169 case ELF32LEKind:
170 return addRegular<ELF32LE>(Cmd);
171 case ELF32BEKind:
172 return addRegular<ELF32BE>(Cmd);
173 case ELF64LEKind:
174 return addRegular<ELF64LE>(Cmd);
175 case ELF64BEKind:
176 return addRegular<ELF64BE>(Cmd);
177 default:
178 llvm_unreachable("unknown Config->EKind");
179 }
180}
181
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000182void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000183 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000184 return;
185
186 // If a symbol was in PROVIDE(), we need to define it only when
187 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000188 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000189 if (Cmd->Provide && (!B || B->isDefined()))
190 return;
191
George Rimara8dba482017-03-20 10:09:58 +0000192 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000193}
194
George Rimar076fe152016-07-21 06:43:01 +0000195bool SymbolAssignment::classof(const BaseCommand *C) {
196 return C->Kind == AssignmentKind;
197}
198
199bool OutputSectionCommand::classof(const BaseCommand *C) {
200 return C->Kind == OutputSectionKind;
201}
202
Rafael Espindola55b169b2017-05-24 18:08:04 +0000203// Fill [Buf, Buf + Size) with Filler.
204// This is used for linker script "=fillexp" command.
205static void fill(uint8_t *Buf, size_t Size, uint32_t Filler) {
206 size_t I = 0;
207 for (; I + 4 < Size; I += 4)
208 memcpy(Buf + I, &Filler, 4);
209 memcpy(Buf + I, &Filler, Size - I);
210}
211
George Rimareea31142016-07-21 14:26:59 +0000212bool InputSectionDescription::classof(const BaseCommand *C) {
213 return C->Kind == InputSectionKind;
214}
215
George Rimareefa7582016-08-04 09:29:31 +0000216bool AssertCommand::classof(const BaseCommand *C) {
217 return C->Kind == AssertKind;
218}
219
George Rimare38cbab2016-09-26 19:22:50 +0000220bool BytesDataCommand::classof(const BaseCommand *C) {
221 return C->Kind == BytesDataKind;
222}
223
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000224static StringRef basename(InputSectionBase *S) {
225 if (S->File)
226 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000227 return "";
228}
229
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000230bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000231 for (InputSectionDescription *ID : Opt.KeptSections)
232 if (ID->FilePat.match(basename(S)))
233 for (SectionPattern &P : ID->SectionPatterns)
234 if (P.SectionPat.match(S->Name))
235 return true;
George Rimareea31142016-07-21 14:26:59 +0000236 return false;
237}
238
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000239// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000240static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000241getComparator(SortSectionPolicy K) {
242 switch (K) {
243 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000244 return [](InputSectionBase *A, InputSectionBase *B) {
245 // ">" is not a mistake. Sections with larger alignments are placed
246 // before sections with smaller alignments in order to reduce the
247 // amount of padding necessary. This is compatible with GNU.
248 return A->Alignment > B->Alignment;
249 };
George Rimarbe394db2016-09-16 20:21:55 +0000250 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000251 return [](InputSectionBase *A, InputSectionBase *B) {
252 return A->Name < B->Name;
253 };
George Rimarbe394db2016-09-16 20:21:55 +0000254 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000255 return [](InputSectionBase *A, InputSectionBase *B) {
256 return getPriority(A->Name) < getPriority(B->Name);
257 };
George Rimarbe394db2016-09-16 20:21:55 +0000258 default:
259 llvm_unreachable("unknown sort policy");
260 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000261}
George Rimar0702c4e2016-07-29 15:32:46 +0000262
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000263// A helper function for the SORT() command.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000264static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000265 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000266 if (Kind == ConstraintKind::NoConstraint)
267 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000268
269 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
270 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000271 });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000272
Rafael Espindolae746e522016-09-21 18:33:44 +0000273 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
274 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000275}
276
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000277static void sortSections(InputSection **Begin, InputSection **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000278 SortSectionPolicy K) {
279 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000280 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000281}
282
Rafael Espindolad3190792016-09-16 15:10:23 +0000283// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000284std::vector<InputSection *>
Rui Ueyama72e107f2017-04-05 02:05:48 +0000285LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000286 std::vector<InputSection *> Ret;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000287
Rui Ueyama72e107f2017-04-05 02:05:48 +0000288 // Collects all sections that satisfy constraints of Cmd.
289 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
290 size_t SizeBefore = Ret.size();
291
292 for (InputSectionBase *Sec : InputSections) {
293 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000294 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000295
Rafael Espindolae39709b2017-05-30 20:40:03 +0000296 if (!Sec->Live) {
297 reportDiscarded(Sec);
298 continue;
299 }
300
Rafael Espindola908a3d32017-02-16 14:36:09 +0000301 // For -emit-relocs we have to ignore entries like
302 // .rela.dyn : { *(.rela.data) }
303 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000304 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000305 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000306
Rui Ueyama72e107f2017-04-05 02:05:48 +0000307 StringRef Filename = basename(Sec);
308 if (!Cmd->FilePat.match(Filename) ||
309 Pat.ExcludedFilePat.match(Filename) ||
310 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000311 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000312
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000313 Ret.push_back(cast<InputSection>(Sec));
Rui Ueyama72e107f2017-04-05 02:05:48 +0000314 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000315 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000316
George Rimar07171f22016-09-21 15:56:44 +0000317 // Sort sections as instructed by SORT-family commands and --sort-section
318 // option. Because SORT-family commands can be nested at most two depth
319 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
320 // line option is respected even if a SORT command is given, the exact
321 // behavior we have here is a bit complicated. Here are the rules.
322 //
323 // 1. If two SORT commands are given, --sort-section is ignored.
324 // 2. If one SORT command is given, and if it is not SORT_NONE,
325 // --sort-section is handled as an inner SORT command.
326 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
327 // 4. If no SORT command is given, sort according to --sort-section.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000328 InputSection **Begin = Ret.data() + SizeBefore;
329 InputSection **End = Ret.data() + Ret.size();
George Rimar07171f22016-09-21 15:56:44 +0000330 if (Pat.SortOuter != SortSectionPolicy::None) {
331 if (Pat.SortInner == SortSectionPolicy::Default)
332 sortSections(Begin, End, Config->SortSection);
333 else
334 sortSections(Begin, End, Pat.SortInner);
335 sortSections(Begin, End, Pat.SortOuter);
336 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000337 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000338 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000339}
340
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000341void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000342 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000343 S->Live = false;
George Rimar503206c2017-03-15 15:42:44 +0000344 if (S == InX::ShStrTab)
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000345 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000346 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000347 }
348}
349
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000350std::vector<InputSectionBase *>
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000351LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000352 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000353
Rui Ueyama8f99f732017-04-05 03:20:42 +0000354 for (BaseCommand *Base : OutCmd.Commands) {
355 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000356 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000357 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000358
359 Cmd->Sections = computeInputSections(Cmd);
Rafael Espindolae4c8b9b2017-04-07 16:10:46 +0000360 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000361 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000362
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000363 return Ret;
364}
365
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000366void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000367 // A symbol can be assigned before any section is mentioned in the linker
368 // script. In an DSO, the symbol values are addresses, so the only important
369 // section values are:
370 // * SHN_UNDEF
371 // * SHN_ABS
372 // * Any value meaning a regular section.
373 // To handle that, create a dummy aether section that fills the void before
374 // the linker scripts switches to another section. It has an index of one
375 // which will map to whatever the first actual section is.
376 Aether = make<OutputSection>("", 0, SHF_ALLOC);
377 Aether->SectionIndex = 1;
378 CurOutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000379 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000380
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000381 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000382 // Handle symbol assignments outside of any output section.
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000383 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000384 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000385 continue;
386 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000387
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000388 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000389 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000390
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000391 // The output section name `/DISCARD/' is special.
392 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000393 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000394 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000395 continue;
396 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000397
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000398 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
399 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
400 // sections satisfy a given constraint. If not, a directive is handled
George Rimar07d7c422017-04-05 09:19:29 +0000401 // as if it wasn't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000402 //
403 // Because we'll iterate over Commands many more times, the easiest
George Rimar07d7c422017-04-05 09:19:29 +0000404 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000405 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000406 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000407 S->Assigned = false;
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000408 Opt.Commands.erase(Opt.Commands.begin() + I);
George Rimar07d7c422017-04-05 09:19:29 +0000409 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000410 continue;
411 }
412
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000413 // A directive may contain symbol definitions like this:
414 // ".foo : { ...; bar = .; }". Handle them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000415 for (BaseCommand *Base : Cmd->Commands)
416 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000417 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000418
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000419 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
420 // is given, input sections are aligned to that value, whether the
421 // given value is larger or smaller than the original section alignment.
422 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000423 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000424 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000425 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000426 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000427
428 // Add input sections to an output section.
George Rimard86a4e52017-05-08 10:18:12 +0000429 for (InputSectionBase *S : V)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000430 Factory.addInputSec(S, Cmd->Name, Cmd->Sec);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000431 if (OutputSection *Sec = Cmd->Sec) {
432 assert(Sec->SectionIndex == INT_MAX);
433 Sec->SectionIndex = I;
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 Espindola02ed7572017-05-04 19:34:17 +0000445 uint64_t StartAddr = Config->ImageBase + elf::getHeaderSize();
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
Peter Smithcbfe9e92017-04-19 12:46:32 +0000453 Commands.push_back(
454 make<SymbolAssignment>(".", [=] { return StartAddr; }, ""));
455
456 // For each OutputSection that needs a VA fabricate an OutputSectionCommand
457 // with an InputSectionDescription describing the InputSections
458 for (OutputSection *Sec : *OutputSections) {
Peter Smithc60b4512017-05-03 08:44:50 +0000459 auto *OSCmd = make<OutputSectionCommand>(Sec->Name);
460 OSCmd->Sec = Sec;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000461 SecToCommand[Sec] = OSCmd;
Peter Smithc60b4512017-05-03 08:44:50 +0000462
463 // Prefer user supplied address over additional alignment constraint
Peter Smithcbfe9e92017-04-19 12:46:32 +0000464 auto I = Config->SectionStartMap.find(Sec->Name);
465 if (I != Config->SectionStartMap.end())
466 Commands.push_back(
467 make<SymbolAssignment>(".", [=] { return I->second; }, ""));
Peter Smithc60b4512017-05-03 08:44:50 +0000468 else if (Sec->PageAlign)
Peter Smithcbfe9e92017-04-19 12:46:32 +0000469 OSCmd->AddrExpr = [=] {
470 return alignTo(Script->getDot(), Config->MaxPageSize);
471 };
Peter Smithc60b4512017-05-03 08:44:50 +0000472
Peter Smithcbfe9e92017-04-19 12:46:32 +0000473 Commands.push_back(OSCmd);
474 if (Sec->Sections.size()) {
475 auto *ISD = make<InputSectionDescription>("");
476 OSCmd->Commands.push_back(ISD);
477 for (InputSection *ISec : Sec->Sections) {
478 ISD->Sections.push_back(ISec);
479 ISec->Assigned = true;
480 }
481 }
482 }
483 // SECTIONS commands run before other non SECTIONS commands
484 Commands.insert(Commands.end(), Opt.Commands.begin(), Opt.Commands.end());
485 Opt.Commands = std::move(Commands);
486}
487
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000488// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000489void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000490 for (InputSectionBase *S : InputSections) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000491 if (!S->Live || S->Parent)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000492 continue;
493 StringRef Name = getOutputSectionName(S->Name);
494 auto I = std::find_if(
495 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
496 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
497 return Cmd->Name == Name;
498 return false;
499 });
Rafael Espindolade8d9892017-04-29 15:44:03 +0000500 if (I == Opt.Commands.end()) {
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000501 Factory.addInputSec(S, Name);
Rafael Espindolade8d9892017-04-29 15:44:03 +0000502 } else {
503 auto *Cmd = cast<OutputSectionCommand>(*I);
504 Factory.addInputSec(S, Name, Cmd->Sec);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000505 if (OutputSection *Sec = Cmd->Sec) {
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000506 SecToCommand[Sec] = Cmd;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000507 unsigned Index = std::distance(Opt.Commands.begin(), I);
508 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
509 Sec->SectionIndex = Index;
510 }
Rafael Espindolade8d9892017-04-29 15:44:03 +0000511 auto *ISD = make<InputSectionDescription>("");
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000512 ISD->Sections.push_back(cast<InputSection>(S));
Rafael Espindolade8d9892017-04-29 15:44:03 +0000513 Cmd->Commands.push_back(ISD);
514 }
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000515 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000516}
517
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000518uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
519 bool IsTbss = (CurOutSec->Flags & SHF_TLS) && CurOutSec->Type == SHT_NOBITS;
520 uint64_t Start = IsTbss ? Dot + ThreadBssOffset : Dot;
521 Start = alignTo(Start, Align);
522 uint64_t End = Start + Size;
523
524 if (IsTbss)
525 ThreadBssOffset = End - Dot;
526 else
527 Dot = End;
528 return End;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000529}
530
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000531void LinkerScript::output(InputSection *S) {
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000532 uint64_t Pos = advance(S->getSize(), S->Alignment);
533 S->OutSecOff = Pos - S->getSize() - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000534
535 // Update output section size after adding each section. This is so that
536 // SIZEOF works correctly in the case below:
537 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000538 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000539
Meador Ingeb8897442017-01-24 02:34:00 +0000540 // If there is a memory region associated with this input section, then
541 // place the section in that region and update the region index.
542 if (CurMemRegion) {
543 CurMemRegion->Offset += CurOutSec->Size;
544 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
545 if (CurSize > CurMemRegion->Length) {
546 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
547 error("section '" + CurOutSec->Name + "' will not fit in region '" +
548 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
549 " bytes");
550 }
551 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000552}
553
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000554void LinkerScript::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000555 if (CurOutSec == Sec)
556 return;
Rafael Espindolad3190792016-09-16 15:10:23 +0000557
Rafael Espindolad3190792016-09-16 15:10:23 +0000558 CurOutSec = Sec;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000559 CurOutSec->Addr = advance(0, CurOutSec->Alignment);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000560
561 // If neither AT nor AT> is specified for an allocatable section, the linker
562 // will set the LMA such that the difference between VMA and LMA for the
563 // section is the same as the preceding output section in the same region
564 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000565 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000566 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000567}
568
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000569void LinkerScript::process(BaseCommand &Base) {
Rui Ueyama2e081a42017-04-05 03:18:46 +0000570 // This handles the assignments to symbol or to the dot.
571 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
572 assignSymbol(Cmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000573 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000574 }
George Rimare38cbab2016-09-26 19:22:50 +0000575
576 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyama2e081a42017-04-05 03:18:46 +0000577 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
578 Cmd->Offset = Dot - CurOutSec->Addr;
579 Dot += Cmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000580 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000581 return;
582 }
583
Rui Ueyama2e081a42017-04-05 03:18:46 +0000584 // Handle ASSERT().
585 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
586 Cmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000587 return;
588 }
589
Rui Ueyama2e081a42017-04-05 03:18:46 +0000590 // Handle a single input section description command.
591 // It calculates and assigns the offsets for each section and also
George Rimare38cbab2016-09-26 19:22:50 +0000592 // updates the output section size.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000593 auto &Cmd = cast<InputSectionDescription>(Base);
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000594 for (InputSection *Sec : Cmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000595 // We tentatively added all synthetic sections at the beginning and removed
596 // empty ones afterwards (because there is no way to know whether they were
597 // going be empty or not other than actually running linker scripts.)
598 // We need to ignore remains of empty sections.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000599 if (auto *S = dyn_cast<SyntheticSection>(Sec))
600 if (S->empty())
George Rimar3fb5a6d2016-11-29 16:05:27 +0000601 continue;
602
Rui Ueyama2e081a42017-04-05 03:18:46 +0000603 if (!Sec->Live)
George Rimar78ef6452017-02-21 15:46:43 +0000604 continue;
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000605 assert(CurOutSec == Sec->getParent());
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000606 output(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000607 }
608}
609
Meador Ingeb8897442017-01-24 02:34:00 +0000610// This function searches for a memory region to place the given output
611// section in. If found, a pointer to the appropriate memory region is
612// returned. Otherwise, a nullptr is returned.
Rafael Espindola1902b332017-04-06 21:26:03 +0000613MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd) {
Meador Ingeb8897442017-01-24 02:34:00 +0000614 // If a memory region name was specified in the output section command,
615 // then try to find that region first.
616 if (!Cmd->MemoryRegionName.empty()) {
617 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
618 if (It != Opt.MemoryRegions.end())
619 return &It->second;
620 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
621 return nullptr;
622 }
623
Rui Ueyamad7c54002017-04-05 03:19:43 +0000624 // If at least one memory region is defined, all sections must
625 // belong to some memory region. Otherwise, we don't need to do
626 // anything for memory regions.
Rui Ueyamacc400cc2017-04-05 03:19:24 +0000627 if (Opt.MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000628 return nullptr;
629
Rafael Espindola1902b332017-04-06 21:26:03 +0000630 OutputSection *Sec = Cmd->Sec;
Meador Ingeb8897442017-01-24 02:34:00 +0000631 // See if a region can be found by matching section flags.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000632 for (auto &Pair : Opt.MemoryRegions) {
633 MemoryRegion &M = Pair.second;
634 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
635 return &M;
Meador Ingeb8897442017-01-24 02:34:00 +0000636 }
637
638 // Otherwise, no suitable region was found.
639 if (Sec->Flags & SHF_ALLOC)
640 error("no memory region specified for section '" + Sec->Name + "'");
641 return nullptr;
642}
643
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000644// This function assigns offsets to input sections and an output section
645// for a single sections command (e.g. ".text { *(.text); }").
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000646void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
Rafael Espindola9b980092017-04-06 21:05:39 +0000647 OutputSection *Sec = Cmd->Sec;
Rafael Espindola2b074552017-02-03 22:27:05 +0000648 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000649 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000650
Rui Ueyamacba41012017-04-05 03:20:03 +0000651 if (Cmd->AddrExpr && (Sec->Flags & SHF_ALLOC))
Rui Ueyamad379f732017-04-05 03:20:22 +0000652 setDot(Cmd->AddrExpr, Cmd->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000653
Eugene Leviant5784e962017-03-14 08:57:09 +0000654 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000655 uint64_t D = Dot;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000656 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000657 }
658
Rafael Espindolafeed7502017-04-06 21:31:24 +0000659 CurMemRegion = Cmd->MemRegion;
Meador Ingeb8897442017-01-24 02:34:00 +0000660 if (CurMemRegion)
661 Dot = CurMemRegion->Offset;
662 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000663
George Rimard86a4e52017-05-08 10:18:12 +0000664 // We do not support custom layout for compressed debug sectons.
665 // At this point we already know their size and have compressed content.
666 if (CurOutSec->Flags & SHF_COMPRESSED)
667 return;
668
Rafael Espindolade8d9892017-04-29 15:44:03 +0000669 for (BaseCommand *C : Cmd->Commands)
670 process(*C);
Rafael Espindolad3190792016-09-16 15:10:23 +0000671}
672
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000673void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000674 // It is common practice to use very generic linker scripts. So for any
675 // given run some of the output sections in the script will be empty.
676 // We could create corresponding empty output sections, but that would
677 // clutter the output.
678 // We instead remove trivially empty sections. The bfd linker seems even
679 // more aggressive at removing them.
680 auto Pos = std::remove_if(
Rui Ueyama8f99f732017-04-05 03:20:42 +0000681 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
682 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000683 return std::find(OutputSections->begin(), OutputSections->end(),
684 Cmd->Sec) == OutputSections->end();
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000685 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000686 });
687 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000688}
689
Rafael Espindola6a537372016-11-14 14:33:49 +0000690static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000691 for (BaseCommand *Base : Cmd.Commands)
692 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000693 return false;
694 return true;
695}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000696
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000697void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000698 // If the output section contains only symbol assignments, create a
699 // corresponding output section. The bfd linker seems to only create them if
700 // '.' is assigned to, but creating these section should not have any bad
701 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000702 uint64_t Flags = SHF_ALLOC;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000703
704 for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
705 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000706 if (!Cmd)
707 continue;
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000708 if (OutputSection *Sec = Cmd->Sec) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000709 Flags = Sec->Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000710 continue;
711 }
712
Rafael Espindola6a537372016-11-14 14:33:49 +0000713 if (isAllSectionDescription(*Cmd))
714 continue;
715
Dmitry Mikulinfd0c8442017-05-24 16:48:31 +0000716 auto *OutSec = make<OutputSection>(Cmd->Name, SHT_PROGBITS, Flags);
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000717 OutSec->SectionIndex = I;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000718 OutputSections->push_back(OutSec);
Rafael Espindola9b980092017-04-06 21:05:39 +0000719 Cmd->Sec = OutSec;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000720 SecToCommand[OutSec] = Cmd;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000721 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000722}
723
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000724void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000725 placeOrphanSections();
726
Rafael Espindolafeed7502017-04-06 21:31:24 +0000727 // Try and find an appropriate memory region to assign offsets in.
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000728 for (BaseCommand *Base : Opt.Commands) {
729 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base)) {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000730 Cmd->MemRegion = findMemoryRegion(Cmd);
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000731 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
732 if (Cmd->AlignExpr)
733 Cmd->Sec->updateAlignment(Cmd->AlignExpr().getValue());
734 }
735 }
Rafael Espindolafeed7502017-04-06 21:31:24 +0000736
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000737 // If output section command doesn't specify any segments,
738 // and we haven't previously assigned any section to segment,
739 // then we simply assign section to the very first load segment.
740 // Below is an example of such linker script:
741 // PHDRS { seg PT_LOAD; }
742 // SECTIONS { .aaa : { *(.aaa) } }
743 std::vector<StringRef> DefPhdrs;
744 auto FirstPtLoad =
745 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
746 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
747 if (FirstPtLoad != Opt.PhdrsCommands.end())
748 DefPhdrs.push_back(FirstPtLoad->Name);
749
750 // Walk the commands and propagate the program headers to commands that don't
751 // explicitly specify them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000752 for (BaseCommand *Base : Opt.Commands) {
753 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000754 if (!Cmd)
755 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000756
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000757 if (Cmd->Phdrs.empty())
758 Cmd->Phdrs = DefPhdrs;
759 else
760 DefPhdrs = Cmd->Phdrs;
761 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000762
763 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000764}
765
Rafael Espindola15c57952016-09-22 18:05:49 +0000766// When placing orphan sections, we want to place them after symbol assignments
767// so that an orphan after
768// begin_foo = .;
769// foo : { *(foo) }
770// end_foo = .;
771// doesn't break the intended meaning of the begin/end symbols.
772// We don't want to go over sections since Writer<ELFT>::sortSections is the
773// one in charge of deciding the order of the sections.
774// We don't want to go over alignments, since doing so in
775// rx_sec : { *(rx_sec) }
776// . = ALIGN(0x1000);
777// /* The RW PT_LOAD starts here*/
778// rw_sec : { *(rw_sec) }
779// would mean that the RW PT_LOAD would become unaligned.
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000780static bool shouldSkip(BaseCommand *Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000781 if (isa<OutputSectionCommand>(Cmd))
782 return false;
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000783 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
784 return Assign->Name != ".";
785 return true;
Rafael Espindola15c57952016-09-22 18:05:49 +0000786}
787
Rui Ueyama6697ec22017-02-02 23:26:12 +0000788// Orphan sections are sections present in the input files which are
789// not explicitly placed into the output file by the linker script.
790//
791// When the control reaches this function, Opt.Commands contains
792// output section commands for non-orphan sections only. This function
Rui Ueyama81cb7102017-03-24 00:15:57 +0000793// adds new elements for orphan sections so that all sections are
794// explicitly handled by Opt.Commands.
Rui Ueyama6697ec22017-02-02 23:26:12 +0000795//
796// Writer<ELFT>::sortSections has already sorted output sections.
797// What we need to do is to scan OutputSections vector and
798// Opt.Commands in parallel to find orphan sections. If there is an
799// output section that doesn't have a corresponding entry in
800// Opt.Commands, we will insert a new entry to Opt.Commands.
801//
802// There is some ambiguity as to where exactly a new entry should be
803// inserted, because Opt.Commands contains not only output section
Rui Ueyama81cb7102017-03-24 00:15:57 +0000804// commands but also other types of commands such as symbol assignment
Rui Ueyama6697ec22017-02-02 23:26:12 +0000805// expressions. There's no correct answer here due to the lack of the
806// formal specification of the linker script. We use heuristics to
807// determine whether a new output command should be added before or
808// after another commands. For the details, look at shouldSkip
809// function.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000810void LinkerScript::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000811 // The OutputSections are already in the correct order.
812 // This loops creates or moves commands as needed so that they are in the
813 // correct order.
814 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000815
816 // As a horrible special case, skip the first . assignment if it is before any
817 // section. We do this because it is common to set a load address by starting
818 // the script with ". = 0xabcd" and the expectation is that every section is
819 // after that.
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000820 auto FirstSectionOrDotAssignment =
821 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
822 [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000823 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
824 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
825 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
826 ++CmdIndex;
827 }
828
Rafael Espindola24e6f362017-02-24 15:07:30 +0000829 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000830 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000831
832 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000833 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000834 auto CmdIter = Opt.Commands.begin() + CmdIndex;
835 auto E = Opt.Commands.end();
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000836 while (CmdIter != E && shouldSkip(*CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000837 ++CmdIter;
838 ++CmdIndex;
839 }
840
Rafael Espindolade8d9892017-04-29 15:44:03 +0000841 // If there is no command corresponding to this output section,
842 // create one and put a InputSectionDescription in it so that both
843 // representations agree on which input sections to use.
Rafael Espindolafa948c72017-05-10 19:00:23 +0000844 OutputSectionCommand *Cmd = getCmd(Sec);
845 if (!Cmd) {
846 Cmd = make<OutputSectionCommand>(Name);
Rafael Espindola9b980092017-04-06 21:05:39 +0000847 Opt.Commands.insert(CmdIter, Cmd);
Rafael Espindola15c57952016-09-22 18:05:49 +0000848 ++CmdIndex;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000849
850 Cmd->Sec = Sec;
Rafael Espindolad7dc2252017-05-10 19:13:38 +0000851 SecToCommand[Sec] = Cmd;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000852 auto *ISD = make<InputSectionDescription>("");
853 for (InputSection *IS : Sec->Sections)
854 ISD->Sections.push_back(IS);
855 Cmd->Commands.push_back(ISD);
856
Rafael Espindola15c57952016-09-22 18:05:49 +0000857 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000858 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000859
860 // Continue from where we found it.
Rafael Espindolafa948c72017-05-10 19:00:23 +0000861 while (*CmdIter != Cmd) {
862 ++CmdIter;
863 ++CmdIndex;
864 }
865 ++CmdIndex;
George Rimar652852c2016-04-16 10:10:32 +0000866 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000867}
868
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000869void LinkerScript::processNonSectionCommands() {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000870 for (BaseCommand *Base : Opt.Commands) {
871 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
Rui Ueyamad379f732017-04-05 03:20:22 +0000872 assignSymbol(Cmd, false);
Rui Ueyama8f99f732017-04-05 03:20:42 +0000873 else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
Petr Hosek02ad5162017-03-15 03:33:23 +0000874 Cmd->Expression();
875 }
876}
877
Rafael Espindolade8d9892017-04-29 15:44:03 +0000878// Do a last effort at synchronizing the linker script "AST" and the section
879// list. This is needed to account for last minute changes, like adding a
880// .ARM.exidx terminator and sorting SHF_LINK_ORDER sections.
881//
882// FIXME: We should instead create the "AST" earlier and the above changes would
883// be done directly in the "AST".
884//
885// This can only handle new sections being added and sections being reordered.
886void LinkerScript::synchronize() {
887 for (BaseCommand *Base : Opt.Commands) {
888 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
889 if (!Cmd)
890 continue;
891 ArrayRef<InputSection *> Sections = Cmd->Sec->Sections;
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000892 std::vector<InputSection **> ScriptSections;
893 DenseSet<InputSection *> ScriptSectionsSet;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000894 for (BaseCommand *Base : Cmd->Commands) {
895 auto *ISD = dyn_cast<InputSectionDescription>(Base);
896 if (!ISD)
897 continue;
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000898 for (InputSection *&IS : ISD->Sections) {
Rafael Espindolade8d9892017-04-29 15:44:03 +0000899 if (IS->Live) {
900 ScriptSections.push_back(&IS);
901 ScriptSectionsSet.insert(IS);
902 }
903 }
904 }
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000905 std::vector<InputSection *> Missing;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000906 for (InputSection *IS : Sections)
907 if (!ScriptSectionsSet.count(IS))
908 Missing.push_back(IS);
909 if (!Missing.empty()) {
910 auto ISD = make<InputSectionDescription>("");
911 ISD->Sections = Missing;
912 Cmd->Commands.push_back(ISD);
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000913 for (InputSection *&IS : ISD->Sections)
Rafael Espindolade8d9892017-04-29 15:44:03 +0000914 if (IS->Live)
915 ScriptSections.push_back(&IS);
916 }
917 assert(ScriptSections.size() == Sections.size());
918 for (int I = 0, N = Sections.size(); I < N; ++I)
919 *ScriptSections[I] = Sections[I];
920 }
921}
922
Rafael Espindola02ed7572017-05-04 19:34:17 +0000923static bool allocateHeaders(std::vector<PhdrEntry> &Phdrs,
924 ArrayRef<OutputSection *> OutputSections,
925 uint64_t Min) {
926 auto FirstPTLoad =
927 std::find_if(Phdrs.begin(), Phdrs.end(),
928 [](const PhdrEntry &E) { return E.p_type == PT_LOAD; });
929 if (FirstPTLoad == Phdrs.end())
930 return false;
931
932 uint64_t HeaderSize = getHeaderSize();
933 if (HeaderSize <= Min || Script->hasPhdrsCommands()) {
934 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
935 Out::ElfHeader->Addr = Min;
936 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
937 return true;
938 }
939
940 assert(FirstPTLoad->First == Out::ElfHeader);
941 OutputSection *ActualFirst = nullptr;
942 for (OutputSection *Sec : OutputSections) {
943 if (Sec->FirstInPtLoad == Out::ElfHeader) {
944 ActualFirst = Sec;
945 break;
946 }
947 }
948 if (ActualFirst) {
949 for (OutputSection *Sec : OutputSections)
950 if (Sec->FirstInPtLoad == Out::ElfHeader)
951 Sec->FirstInPtLoad = ActualFirst;
952 FirstPTLoad->First = ActualFirst;
953 } else {
954 Phdrs.erase(FirstPTLoad);
955 }
956
957 auto PhdrI = std::find_if(Phdrs.begin(), Phdrs.end(), [](const PhdrEntry &E) {
958 return E.p_type == PT_PHDR;
959 });
960 if (PhdrI != Phdrs.end())
961 Phdrs.erase(PhdrI);
962 return false;
963}
964
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000965void LinkerScript::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000966 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000967 Dot = 0;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000968 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000969 switchTo(Aether);
970
Rui Ueyama8f99f732017-04-05 03:20:42 +0000971 for (BaseCommand *Base : Opt.Commands) {
972 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
Rui Ueyamad379f732017-04-05 03:20:22 +0000973 assignSymbol(Cmd, false);
George Rimar652852c2016-04-16 10:10:32 +0000974 continue;
975 }
976
Rui Ueyama8f99f732017-04-05 03:20:42 +0000977 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000978 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000979 continue;
980 }
981
Rui Ueyama8f99f732017-04-05 03:20:42 +0000982 auto *Cmd = cast<OutputSectionCommand>(Base);
Rafael Espindolad3190792016-09-16 15:10:23 +0000983 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000984 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000985
George Rimar0c1c8082017-03-14 10:00:19 +0000986 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000987 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000988 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000989 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000990 else
991 Sec->Addr = 0;
992 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000993
George Rimar2d262102017-03-14 09:03:53 +0000994 allocateHeaders(Phdrs, *OutputSections, MinVA);
George Rimar652852c2016-04-16 10:10:32 +0000995}
996
Rui Ueyama464daad2016-08-22 04:55:20 +0000997// Creates program headers as instructed by PHDRS linker script command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000998std::vector<PhdrEntry> LinkerScript::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000999 std::vector<PhdrEntry> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001000
Rui Ueyama464daad2016-08-22 04:55:20 +00001001 // Process PHDRS and FILEHDR keywords because they are not
1002 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +00001003 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +00001004 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001005 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001006
1007 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001008 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +00001009 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +00001010 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +00001011
1012 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001013 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +00001014 Phdr.HasLMA = true;
1015 }
Eugene Leviantbbe38602016-07-19 09:25:43 +00001016 }
1017
Rui Ueyama464daad2016-08-22 04:55:20 +00001018 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +00001019 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +00001020 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +00001021 break;
1022
Eugene Leviantce30b1c2016-10-19 15:04:49 +00001023 // Assign headers specified by linker script
Rafael Espindola2c923c22017-05-10 14:28:31 +00001024 for (size_t Id : getPhdrIndices(Sec)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +00001025 Ret[Id].add(Sec);
1026 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +00001027 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +00001028 }
Eugene Leviantbbe38602016-07-19 09:25:43 +00001029 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +00001030 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001031}
1032
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001033bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +00001034 // Ignore .interp section in case we have PHDRS specification
1035 // and PT_INTERP isn't listed.
Rui Ueyamae31d9882017-04-05 05:06:17 +00001036 if (Opt.PhdrsCommands.empty())
1037 return false;
1038 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
1039 if (Cmd.Type == PT_INTERP)
1040 return false;
1041 return true;
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +00001042}
1043
Rafael Espindolad7dc2252017-05-10 19:13:38 +00001044OutputSectionCommand *LinkerScript::getCmd(OutputSection *Sec) const {
1045 auto I = SecToCommand.find(Sec);
1046 if (I == SecToCommand.end())
1047 return nullptr;
1048 return I->second;
Rafael Espindolafa948c72017-05-10 19:00:23 +00001049}
1050
Rafael Espindola55b169b2017-05-24 18:08:04 +00001051uint32_t OutputSectionCommand::getFiller() {
1052 if (Filler)
1053 return *Filler;
1054 if (Sec->Flags & SHF_EXECINSTR)
1055 return Target->TrapInstr;
1056 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +00001057}
1058
George Rimare38cbab2016-09-26 19:22:50 +00001059static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001060 if (Size == 1)
1061 *Buf = Data;
1062 else if (Size == 2)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +00001063 write16(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001064 else if (Size == 4)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +00001065 write32(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001066 else if (Size == 8)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +00001067 write64(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +00001068 else
George Rimare38cbab2016-09-26 19:22:50 +00001069 llvm_unreachable("unsupported Size argument");
George Rimare38cbab2016-09-26 19:22:50 +00001070}
1071
Rafael Espindola55b169b2017-05-24 18:08:04 +00001072template <class ELFT> void OutputSectionCommand::writeTo(uint8_t *Buf) {
1073 Sec->Loc = Buf;
1074
1075 // We may have already rendered compressed content when using
1076 // -compress-debug-sections option. Write it together with header.
1077 if (!Sec->CompressedData.empty()) {
1078 memcpy(Buf, Sec->ZDebugHeader.data(), Sec->ZDebugHeader.size());
1079 memcpy(Buf + Sec->ZDebugHeader.size(), Sec->CompressedData.data(),
1080 Sec->CompressedData.size());
1081 return;
1082 }
1083
George Rimard4096142017-05-30 05:48:09 +00001084 if (Sec->Type == SHT_NOBITS)
1085 return;
1086
Rafael Espindola55b169b2017-05-24 18:08:04 +00001087 // Write leading padding.
1088 ArrayRef<InputSection *> Sections = Sec->Sections;
1089 uint32_t Filler = getFiller();
1090 if (Filler)
1091 fill(Buf, Sections.empty() ? Sec->Size : Sections[0]->OutSecOff, Filler);
1092
1093 parallelForEachN(0, Sections.size(), [=](size_t I) {
1094 InputSection *IS = Sections[I];
1095 IS->writeTo<ELFT>(Buf);
1096
1097 // Fill gaps between sections.
1098 if (Filler) {
1099 uint8_t *Start = Buf + IS->OutSecOff + IS->getSize();
1100 uint8_t *End;
1101 if (I + 1 == Sections.size())
1102 End = Buf + Sec->Size;
1103 else
1104 End = Buf + Sections[I + 1]->OutSecOff;
1105 fill(Start, End - Start, Filler);
1106 }
1107 });
1108
1109 // Linker scripts may have BYTE()-family commands with which you
1110 // can write arbitrary bytes to the output. Process them if any.
1111 for (BaseCommand *Base : Commands)
1112 if (auto *Data = dyn_cast<BytesDataCommand>(Base))
1113 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +00001114}
1115
Rafael Espindoladc1ed122017-05-10 14:12:02 +00001116bool LinkerScript::hasLMA(OutputSection *Sec) {
Rafael Espindolafa948c72017-05-10 19:00:23 +00001117 if (OutputSectionCommand *Cmd = getCmd(Sec))
1118 if (Cmd->LMAExpr)
1119 return true;
Eugene Leviantb71d6f72016-10-06 09:39:28 +00001120 return false;
George Rimar8ceadb32016-08-17 07:44:19 +00001121}
1122
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001123ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +00001124 if (S == ".")
Rafael Espindola72dc1952017-03-17 13:05:04 +00001125 return {CurOutSec, Dot - CurOutSec->Addr};
George Rimara8dba482017-03-20 10:09:58 +00001126 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +00001127 if (auto *D = dyn_cast<DefinedRegular>(B))
1128 return {D->Section, D->Value};
Petr Hosek30f16b22017-03-23 03:52:34 +00001129 if (auto *C = dyn_cast<DefinedCommon>(B))
1130 return {InX::Common, C->Offset};
Rafael Espindola72dc1952017-03-17 13:05:04 +00001131 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +00001132 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +00001133 return 0;
1134}
1135
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001136bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +00001137
Rafael Espindola2c923c22017-05-10 14:28:31 +00001138// Returns indices of ELF headers containing specific section. Each index is a
1139// zero based number of ELF header listed within PHDRS {} script block.
1140std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Sec) {
Rafael Espindolafa948c72017-05-10 19:00:23 +00001141 if (OutputSectionCommand *Cmd = getCmd(Sec)) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001142 std::vector<size_t> Ret;
1143 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +00001144 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001145 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +00001146 }
George Rimar31d842f2016-07-20 16:43:03 +00001147 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +00001148}
1149
Rui Ueyamab8dd23f2017-03-21 23:02:51 +00001150size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001151 size_t I = 0;
1152 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
1153 if (Cmd.Name == PhdrName)
1154 return I;
1155 ++I;
1156 }
Eugene Leviant2a942c42016-12-05 16:38:32 +00001157 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +00001158 return 0;
1159}
Rafael Espindola55b169b2017-05-24 18:08:04 +00001160
1161template void OutputSectionCommand::writeTo<ELF32LE>(uint8_t *Buf);
1162template void OutputSectionCommand::writeTo<ELF32BE>(uint8_t *Buf);
1163template void OutputSectionCommand::writeTo<ELF64LE>(uint8_t *Buf);
1164template void OutputSectionCommand::writeTo<ELF64BE>(uint8_t *Buf);