blob: ae8c9b687d9f9191321a777e631954cd16e5813e [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"
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
George Rimar5d0ea702017-08-21 07:57:12 +000052static uint64_t getOutputSectionVA(SectionBase *InputSec, StringRef Loc) {
53 if (OutputSection *OS = InputSec->getOutputSection())
54 return OS->Addr;
55 error(Loc + ": unable to evaluate expression: input section " +
56 InputSec->Name + " has no output section assigned");
57 return 0;
58}
59
Rafael Espindola72dc1952017-03-17 13:05:04 +000060uint64_t ExprValue::getValue() const {
George Rimar5d0ea702017-08-21 07:57:12 +000061 if (Sec)
62 return alignTo(Sec->getOffset(Val) + getOutputSectionVA(Sec, Loc),
63 Alignment);
Petr Hosek3c6de1a2017-05-30 03:18:28 +000064 return alignTo(Val, Alignment);
Rafael Espindola72dc1952017-03-17 13:05:04 +000065}
66
Rafael Espindola7ba5f472017-03-17 14:55:36 +000067uint64_t ExprValue::getSecAddr() const {
68 if (Sec)
George Rimar5d0ea702017-08-21 07:57:12 +000069 return Sec->getOffset(0) + getOutputSectionVA(Sec, Loc);
Rafael Espindola7ba5f472017-03-17 14:55:36 +000070 return 0;
71}
72
Rafael Espindolaa5e8dd32017-07-26 18:47:49 +000073static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000074 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000075 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rafael Espindola244ef982017-07-26 18:42:48 +000076 std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
77 /*CanOmitFromDynSym*/ false,
78 /*File*/ nullptr);
Petr Hosek5e51f7d2017-02-21 22:32:51 +000079 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +000080 ExprValue Value = Cmd->Expression();
81 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
George Rimar01aa7952017-04-14 09:23:26 +000082
83 // We want to set symbol values early if we can. This allows us to use symbols
84 // as variables in linker scripts. Doing so allows us to write expressions
85 // like this: `alignment = 16; . = ALIGN(., alignment)`
86 uint64_t SymValue = Value.isAbsolute() ? Value.getValue() : 0;
Rafael Espindola6e93d052017-08-04 22:31:42 +000087 replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
88 Visibility, STT_NOTYPE, SymValue, 0, Sec);
Meador Inge8f1f3c42017-01-09 18:36:57 +000089 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000090}
91
Rafael Espindola8c022ca2017-07-27 19:22:43 +000092OutputSection *LinkerScript::createOutputSection(StringRef Name,
93 StringRef Location) {
94 OutputSection *&SecRef = NameToOutputSection[Name];
95 OutputSection *Sec;
96 if (SecRef && SecRef->Location.empty()) {
Rafael Espindola05c4f672017-06-01 01:16:50 +000097 // There was a forward reference.
Rafael Espindola8c022ca2017-07-27 19:22:43 +000098 Sec = SecRef;
Rafael Espindola05c4f672017-06-01 01:16:50 +000099 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000100 Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
101 if (!SecRef)
102 SecRef = Sec;
Rafael Espindola05c4f672017-06-01 01:16:50 +0000103 }
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000104 Sec->Location = Location;
105 return Sec;
George Rimar851dc1e2017-03-14 10:15:53 +0000106}
107
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000108OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
109 OutputSection *&CmdRef = NameToOutputSection[Name];
Rafael Espindola05c4f672017-06-01 01:16:50 +0000110 if (!CmdRef)
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000111 CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
Rafael Espindola05c4f672017-06-01 01:16:50 +0000112 return CmdRef;
George Rimard83ce1b2017-03-14 10:24:47 +0000113}
114
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000115void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000116 uint64_t Val = E().getValue();
George Rimar8c804d92017-07-12 14:50:25 +0000117 if (Val < Dot && InSec)
118 error(Loc + ": unable to move location counter backward for: " +
119 CurAddressState->OutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000120 Dot = Val;
121 // Update to location counter means update to section size.
122 if (InSec)
Peter Smith906e9a12017-07-07 09:11:27 +0000123 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
Rafael Espindola679828f2017-02-17 16:26:13 +0000124}
125
George Rimarb2b70972017-02-07 10:23:28 +0000126// Sets value of a symbol. Two kinds of symbols are processed: synthetic
127// symbols, whose value is an offset from beginning of section and regular
128// symbols whose value is absolute.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000129void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000130 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000131 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000132 return;
133 }
134
George Rimarb2b70972017-02-07 10:23:28 +0000135 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000136 return;
137
Rafael Espindola5616adf2017-03-08 22:36:28 +0000138 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000139 ExprValue V = Cmd->Expression();
140 if (V.isAbsolute()) {
141 Sym->Value = V.getValue();
142 } else {
143 Sym->Section = V.Sec;
Rafael Espindoladece2802017-06-13 20:57:43 +0000144 Sym->Value = alignTo(V.Val, V.Alignment);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000145 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000146}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000147
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000148void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000149 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000150 return;
151
152 // If a symbol was in PROVIDE(), we need to define it only when
153 // it is a referenced undefined symbol.
Rafael Espindola244ef982017-07-26 18:42:48 +0000154 SymbolBody *B = Symtab->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000155 if (Cmd->Provide && (!B || B->isDefined()))
156 return;
157
Rafael Espindolaa5e8dd32017-07-26 18:47:49 +0000158 Cmd->Sym = addRegular(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000159}
160
George Rimar076fe152016-07-21 06:43:01 +0000161bool SymbolAssignment::classof(const BaseCommand *C) {
162 return C->Kind == AssignmentKind;
163}
164
George Rimareea31142016-07-21 14:26:59 +0000165bool InputSectionDescription::classof(const BaseCommand *C) {
166 return C->Kind == InputSectionKind;
167}
168
George Rimareefa7582016-08-04 09:29:31 +0000169bool AssertCommand::classof(const BaseCommand *C) {
170 return C->Kind == AssertKind;
171}
172
George Rimare38cbab2016-09-26 19:22:50 +0000173bool BytesDataCommand::classof(const BaseCommand *C) {
174 return C->Kind == BytesDataKind;
175}
176
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000177static StringRef basename(InputSectionBase *S) {
178 if (S->File)
179 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000180 return "";
181}
182
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000183bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000184 for (InputSectionDescription *ID : Opt.KeptSections)
185 if (ID->FilePat.match(basename(S)))
186 for (SectionPattern &P : ID->SectionPatterns)
187 if (P.SectionPat.match(S->Name))
188 return true;
George Rimareea31142016-07-21 14:26:59 +0000189 return false;
190}
191
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000192// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000193static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000194getComparator(SortSectionPolicy K) {
195 switch (K) {
196 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000197 return [](InputSectionBase *A, InputSectionBase *B) {
198 // ">" is not a mistake. Sections with larger alignments are placed
199 // before sections with smaller alignments in order to reduce the
200 // amount of padding necessary. This is compatible with GNU.
201 return A->Alignment > B->Alignment;
202 };
George Rimarbe394db2016-09-16 20:21:55 +0000203 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000204 return [](InputSectionBase *A, InputSectionBase *B) {
205 return A->Name < B->Name;
206 };
George Rimarbe394db2016-09-16 20:21:55 +0000207 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000208 return [](InputSectionBase *A, InputSectionBase *B) {
209 return getPriority(A->Name) < getPriority(B->Name);
210 };
George Rimarbe394db2016-09-16 20:21:55 +0000211 default:
212 llvm_unreachable("unknown sort policy");
213 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000214}
George Rimar0702c4e2016-07-29 15:32:46 +0000215
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000216// A helper function for the SORT() command.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000217static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000218 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000219 if (Kind == ConstraintKind::NoConstraint)
220 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000221
222 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
223 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000224 });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000225
Rafael Espindolae746e522016-09-21 18:33:44 +0000226 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
227 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000228}
229
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000230static void sortSections(InputSection **Begin, InputSection **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000231 SortSectionPolicy K) {
232 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000233 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000234}
235
George Rimard6bcde32017-08-04 10:25:29 +0000236static llvm::DenseMap<SectionBase *, int> getSectionOrder() {
237 switch (Config->EKind) {
238 case ELF32LEKind:
239 return buildSectionOrder<ELF32LE>();
240 case ELF32BEKind:
241 return buildSectionOrder<ELF32BE>();
242 case ELF64LEKind:
243 return buildSectionOrder<ELF64LE>();
244 case ELF64BEKind:
245 return buildSectionOrder<ELF64BE>();
246 default:
247 llvm_unreachable("unknown ELF type");
248 }
249}
250
251static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
252 if (Config->SymbolOrderingFile.empty())
253 return;
254 static llvm::DenseMap<SectionBase *, int> Order = getSectionOrder();
255 MutableArrayRef<InputSection *> In(Begin, End - Begin);
256 sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
257}
258
Rafael Espindolad3190792016-09-16 15:10:23 +0000259// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000260std::vector<InputSection *>
Rui Ueyama72e107f2017-04-05 02:05:48 +0000261LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000262 std::vector<InputSection *> Ret;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000263
Rui Ueyama72e107f2017-04-05 02:05:48 +0000264 // Collects all sections that satisfy constraints of Cmd.
265 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
266 size_t SizeBefore = Ret.size();
267
268 for (InputSectionBase *Sec : InputSections) {
269 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000270 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000271
Rafael Espindolae39709b2017-05-30 20:40:03 +0000272 if (!Sec->Live) {
273 reportDiscarded(Sec);
274 continue;
275 }
276
Rafael Espindola908a3d32017-02-16 14:36:09 +0000277 // For -emit-relocs we have to ignore entries like
278 // .rela.dyn : { *(.rela.data) }
279 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000280 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000281 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000282
Rui Ueyama72e107f2017-04-05 02:05:48 +0000283 StringRef Filename = basename(Sec);
284 if (!Cmd->FilePat.match(Filename) ||
285 Pat.ExcludedFilePat.match(Filename) ||
286 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000287 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000288
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000289 Ret.push_back(cast<InputSection>(Sec));
Rui Ueyama72e107f2017-04-05 02:05:48 +0000290 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000291 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000292
George Rimar07171f22016-09-21 15:56:44 +0000293 // Sort sections as instructed by SORT-family commands and --sort-section
294 // option. Because SORT-family commands can be nested at most two depth
295 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
296 // line option is respected even if a SORT command is given, the exact
297 // behavior we have here is a bit complicated. Here are the rules.
298 //
299 // 1. If two SORT commands are given, --sort-section is ignored.
300 // 2. If one SORT command is given, and if it is not SORT_NONE,
301 // --sort-section is handled as an inner SORT command.
302 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
303 // 4. If no SORT command is given, sort according to --sort-section.
George Rimard6bcde32017-08-04 10:25:29 +0000304 // 5. If no SORT commands are given and --sort-section is not specified,
305 // apply sorting provided by --symbol-ordering-file if any exist.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000306 InputSection **Begin = Ret.data() + SizeBefore;
307 InputSection **End = Ret.data() + Ret.size();
George Rimard6bcde32017-08-04 10:25:29 +0000308 if (Pat.SortOuter == SortSectionPolicy::Default &&
309 Config->SortSection == SortSectionPolicy::Default) {
310 sortBySymbolOrder(Begin, End);
311 continue;
312 }
George Rimar07171f22016-09-21 15:56:44 +0000313 if (Pat.SortOuter != SortSectionPolicy::None) {
314 if (Pat.SortInner == SortSectionPolicy::Default)
315 sortSections(Begin, End, Config->SortSection);
316 else
317 sortSections(Begin, End, Pat.SortInner);
318 sortSections(Begin, End, Pat.SortOuter);
319 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000320 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000321 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000322}
323
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000324void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000325 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000326 S->Live = false;
George Rimar945cd312017-08-10 08:07:05 +0000327 if (S == InX::ShStrTab || S == InX::Common || S == InX::Dynamic ||
328 S == InX::DynSymTab || S == InX::DynStrTab)
Rafael Espindola2af64b02017-06-16 23:45:35 +0000329 error("discarding " + S->Name + " section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000330 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000331 }
332}
333
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000334std::vector<InputSectionBase *>
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000335LinkerScript::createInputSectionList(OutputSection &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000336 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000337
Rui Ueyama8f99f732017-04-05 03:20:42 +0000338 for (BaseCommand *Base : OutCmd.Commands) {
339 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000340 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000341 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000342
343 Cmd->Sections = computeInputSections(Cmd);
Rafael Espindolae4c8b9b2017-04-07 16:10:46 +0000344 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000345 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000346
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000347 return Ret;
348}
349
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000350void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000351 // A symbol can be assigned before any section is mentioned in the linker
352 // script. In an DSO, the symbol values are addresses, so the only important
353 // section values are:
354 // * SHN_UNDEF
355 // * SHN_ABS
356 // * Any value meaning a regular section.
357 // To handle that, create a dummy aether section that fills the void before
358 // the linker scripts switches to another section. It has an index of one
359 // which will map to whatever the first actual section is.
360 Aether = make<OutputSection>("", 0, SHF_ALLOC);
361 Aether->SectionIndex = 1;
Peter Smith906e9a12017-07-07 09:11:27 +0000362 auto State = make_unique<AddressState>(Opt);
Peter Smithc1ace402017-07-11 09:28:27 +0000363 // CurAddressState captures the local AddressState and makes it accessible
364 // deliberately. This is needed as there are some cases where we cannot just
365 // thread the current state through to a lambda function created by the
366 // script parser.
Peter Smith906e9a12017-07-07 09:11:27 +0000367 CurAddressState = State.get();
368 CurAddressState->OutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000369 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000370
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000371 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000372 // Handle symbol assignments outside of any output section.
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000373 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000374 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000375 continue;
376 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000377
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000378 if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
379 std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000380
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000381 // The output section name `/DISCARD/' is special.
382 // Any input section assigned to it is discarded.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000383 if (Sec->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000384 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000385 continue;
386 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000387
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000388 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
389 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
390 // sections satisfy a given constraint. If not, a directive is handled
George Rimar07d7c422017-04-05 09:19:29 +0000391 // as if it wasn't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000392 //
393 // Because we'll iterate over Commands many more times, the easiest
George Rimar07d7c422017-04-05 09:19:29 +0000394 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000395 if (!matchConstraints(V, Sec->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000396 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000397 S->Assigned = false;
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000398 Opt.Commands.erase(Opt.Commands.begin() + I);
George Rimar07d7c422017-04-05 09:19:29 +0000399 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000400 continue;
401 }
402
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000403 // A directive may contain symbol definitions like this:
404 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000405 for (BaseCommand *Base : Sec->Commands)
Rui Ueyama8f99f732017-04-05 03:20:42 +0000406 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000407 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000408
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000409 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
410 // is given, input sections are aligned to that value, whether the
411 // given value is larger or smaller than the original section alignment.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000412 if (Sec->SubalignExpr) {
413 uint32_t Subalign = Sec->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000414 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000415 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000416 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000417
418 // Add input sections to an output section.
George Rimard86a4e52017-05-08 10:18:12 +0000419 for (InputSectionBase *S : V)
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000420 Factory.addInputSec(S, Sec->Name, Sec);
421 assert(Sec->SectionIndex == INT_MAX);
422 Sec->SectionIndex = I;
423 if (Sec->Noload)
424 Sec->Type = SHT_NOBITS;
Eugene Leviantceabe802016-08-11 07:56:43 +0000425 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000426 }
Peter Smithc1ace402017-07-11 09:28:27 +0000427 CurAddressState = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000428}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000429
Rafael Espindola02ed7572017-05-04 19:34:17 +0000430void LinkerScript::fabricateDefaultCommands() {
Peter Smithcbfe9e92017-04-19 12:46:32 +0000431 // Define start address
Rafael Espindolae76231b2017-06-08 04:17:04 +0000432 uint64_t StartAddr = -1;
Peter Smithcbfe9e92017-04-19 12:46:32 +0000433
Peter Smithc60b4512017-05-03 08:44:50 +0000434 // The Sections with -T<section> have been sorted in order of ascending
435 // address. We must lower StartAddr if the lowest -T<section address> as
436 // calls to setDot() must be monotonically increasing.
George Rimar67c60722017-07-18 11:55:35 +0000437 for (auto &KV : Config->SectionStartMap)
Peter Smithc60b4512017-05-03 08:44:50 +0000438 StartAddr = std::min(StartAddr, KV.second);
439
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000440 Opt.Commands.insert(Opt.Commands.begin(),
441 make<SymbolAssignment>(".",
442 [=] {
443 return std::min(
444 StartAddr,
445 Config->ImageBase +
446 elf::getHeaderSize());
447 },
448 ""));
Peter Smithcbfe9e92017-04-19 12:46:32 +0000449}
450
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000451// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000452void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rafael Espindolad7faa912017-07-05 17:50:43 +0000453 unsigned NumCommands = Opt.Commands.size();
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000454 for (InputSectionBase *S : InputSections) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000455 if (!S->Live || S->Parent)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000456 continue;
457 StringRef Name = getOutputSectionName(S->Name);
Rafael Espindolad7faa912017-07-05 17:50:43 +0000458 auto End = Opt.Commands.begin() + NumCommands;
459 auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000460 if (auto *Sec = dyn_cast<OutputSection>(Base))
461 return Sec->Name == Name;
George Rimara951d5c2017-07-04 13:10:37 +0000462 return false;
463 });
Rafael Espindolad7faa912017-07-05 17:50:43 +0000464 if (I == End) {
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000465 Factory.addInputSec(S, Name);
Rafael Espindolaa2df2f02017-07-27 21:42:42 +0000466 assert(S->getOutputSection()->SectionIndex == INT_MAX);
Rafael Espindolade8d9892017-04-29 15:44:03 +0000467 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000468 OutputSection *Sec = cast<OutputSection>(*I);
469 Factory.addInputSec(S, Name, Sec);
470 unsigned Index = std::distance(Opt.Commands.begin(), I);
471 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
472 Sec->SectionIndex = Index;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000473 }
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000474 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000475}
476
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000477uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
Peter Smith906e9a12017-07-07 09:11:27 +0000478 bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
479 CurAddressState->OutSec->Type == SHT_NOBITS;
480 uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000481 Start = alignTo(Start, Align);
482 uint64_t End = Start + Size;
483
484 if (IsTbss)
Peter Smith906e9a12017-07-07 09:11:27 +0000485 CurAddressState->ThreadBssOffset = End - Dot;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000486 else
487 Dot = End;
488 return End;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000489}
490
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000491void LinkerScript::output(InputSection *S) {
George Rimarf694d332017-07-25 08:29:29 +0000492 uint64_t Before = advance(0, 1);
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000493 uint64_t Pos = advance(S->getSize(), S->Alignment);
Peter Smith906e9a12017-07-07 09:11:27 +0000494 S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000495
496 // Update output section size after adding each section. This is so that
497 // SIZEOF works correctly in the case below:
498 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Peter Smith906e9a12017-07-07 09:11:27 +0000499 CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000500
Meador Ingeb8897442017-01-24 02:34:00 +0000501 // If there is a memory region associated with this input section, then
502 // place the section in that region and update the region index.
Peter Smith906e9a12017-07-07 09:11:27 +0000503 if (CurAddressState->MemRegion) {
504 uint64_t &CurOffset =
505 CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
George Rimarf694d332017-07-25 08:29:29 +0000506 CurOffset += Pos - Before;
Peter Smith906e9a12017-07-07 09:11:27 +0000507 uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
508 if (CurSize > CurAddressState->MemRegion->Length) {
509 uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
510 error("section '" + CurAddressState->OutSec->Name +
511 "' will not fit in region '" + CurAddressState->MemRegion->Name +
512 "': overflowed by " + Twine(OverflowAmt) + " bytes");
Meador Ingeb8897442017-01-24 02:34:00 +0000513 }
514 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000515}
516
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000517void LinkerScript::switchTo(OutputSection *Sec) {
Peter Smith906e9a12017-07-07 09:11:27 +0000518 if (CurAddressState->OutSec == Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000519 return;
Rafael Espindolad3190792016-09-16 15:10:23 +0000520
Peter Smith906e9a12017-07-07 09:11:27 +0000521 CurAddressState->OutSec = Sec;
522 CurAddressState->OutSec->Addr =
523 advance(0, CurAddressState->OutSec->Alignment);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000524
525 // If neither AT nor AT> is specified for an allocatable section, the linker
526 // will set the LMA such that the difference between VMA and LMA for the
527 // section is the same as the preceding output section in the same region
528 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
Peter Smith906e9a12017-07-07 09:11:27 +0000529 if (CurAddressState->LMAOffset)
530 CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000531}
532
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000533void LinkerScript::process(BaseCommand &Base) {
Rui Ueyama2e081a42017-04-05 03:18:46 +0000534 // This handles the assignments to symbol or to the dot.
535 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
536 assignSymbol(Cmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000537 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000538 }
George Rimare38cbab2016-09-26 19:22:50 +0000539
540 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyama2e081a42017-04-05 03:18:46 +0000541 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
Peter Smith906e9a12017-07-07 09:11:27 +0000542 Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
Rui Ueyama2e081a42017-04-05 03:18:46 +0000543 Dot += Cmd->Size;
Peter Smith906e9a12017-07-07 09:11:27 +0000544 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000545 return;
546 }
547
Rui Ueyama2e081a42017-04-05 03:18:46 +0000548 // Handle ASSERT().
549 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
550 Cmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000551 return;
552 }
553
Rui Ueyama2e081a42017-04-05 03:18:46 +0000554 // Handle a single input section description command.
555 // It calculates and assigns the offsets for each section and also
George Rimare38cbab2016-09-26 19:22:50 +0000556 // updates the output section size.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000557 auto &Cmd = cast<InputSectionDescription>(Base);
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000558 for (InputSection *Sec : Cmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000559 // We tentatively added all synthetic sections at the beginning and removed
560 // empty ones afterwards (because there is no way to know whether they were
561 // going be empty or not other than actually running linker scripts.)
562 // We need to ignore remains of empty sections.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000563 if (auto *S = dyn_cast<SyntheticSection>(Sec))
564 if (S->empty())
George Rimar3fb5a6d2016-11-29 16:05:27 +0000565 continue;
566
Rui Ueyama2e081a42017-04-05 03:18:46 +0000567 if (!Sec->Live)
George Rimar78ef6452017-02-21 15:46:43 +0000568 continue;
Peter Smith906e9a12017-07-07 09:11:27 +0000569 assert(CurAddressState->OutSec == Sec->getParent());
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000570 output(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000571 }
572}
573
Meador Ingeb8897442017-01-24 02:34:00 +0000574// This function searches for a memory region to place the given output
575// section in. If found, a pointer to the appropriate memory region is
576// returned. Otherwise, a nullptr is returned.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000577MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000578 // If a memory region name was specified in the output section command,
579 // then try to find that region first.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000580 if (!Sec->MemoryRegionName.empty()) {
581 auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
Meador Ingeb8897442017-01-24 02:34:00 +0000582 if (It != Opt.MemoryRegions.end())
583 return &It->second;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000584 error("memory region '" + Sec->MemoryRegionName + "' not declared");
Meador Ingeb8897442017-01-24 02:34:00 +0000585 return nullptr;
586 }
587
Rui Ueyamad7c54002017-04-05 03:19:43 +0000588 // If at least one memory region is defined, all sections must
589 // belong to some memory region. Otherwise, we don't need to do
590 // anything for memory regions.
Rui Ueyamacc400cc2017-04-05 03:19:24 +0000591 if (Opt.MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000592 return nullptr;
593
594 // See if a region can be found by matching section flags.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000595 for (auto &Pair : Opt.MemoryRegions) {
596 MemoryRegion &M = Pair.second;
597 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
598 return &M;
Meador Ingeb8897442017-01-24 02:34:00 +0000599 }
600
601 // Otherwise, no suitable region was found.
602 if (Sec->Flags & SHF_ALLOC)
603 error("no memory region specified for section '" + Sec->Name + "'");
604 return nullptr;
605}
606
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000607// This function assigns offsets to input sections and an output section
608// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000609void LinkerScript::assignOffsets(OutputSection *Sec) {
Rafael Espindoladece2802017-06-13 20:57:43 +0000610 if (!(Sec->Flags & SHF_ALLOC))
611 Dot = 0;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000612 else if (Sec->AddrExpr)
613 setDot(Sec->AddrExpr, Sec->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000614
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000615 if (Sec->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000616 uint64_t D = Dot;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000617 CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000618 }
619
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000620 CurAddressState->MemRegion = Sec->MemRegion;
Peter Smith906e9a12017-07-07 09:11:27 +0000621 if (CurAddressState->MemRegion)
622 Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
Meador Ingeb8897442017-01-24 02:34:00 +0000623 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000624
George Rimard86a4e52017-05-08 10:18:12 +0000625 // We do not support custom layout for compressed debug sectons.
626 // At this point we already know their size and have compressed content.
Peter Smith906e9a12017-07-07 09:11:27 +0000627 if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
George Rimard86a4e52017-05-08 10:18:12 +0000628 return;
629
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000630 for (BaseCommand *C : Sec->Commands)
Rafael Espindolade8d9892017-04-29 15:44:03 +0000631 process(*C);
Rafael Espindolad3190792016-09-16 15:10:23 +0000632}
633
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000634void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000635 // It is common practice to use very generic linker scripts. So for any
636 // given run some of the output sections in the script will be empty.
637 // We could create corresponding empty output sections, but that would
638 // clutter the output.
639 // We instead remove trivially empty sections. The bfd linker seems even
640 // more aggressive at removing them.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000641 auto Pos = std::remove_if(Opt.Commands.begin(), Opt.Commands.end(),
642 [&](BaseCommand *Base) {
643 if (auto *Sec = dyn_cast<OutputSection>(Base))
644 return !Sec->Live;
645 return false;
646 });
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000647 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000648}
649
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000650static bool isAllSectionDescription(const OutputSection &Cmd) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000651 for (BaseCommand *Base : Cmd.Commands)
652 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000653 return false;
654 return true;
655}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000656
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000657void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000658 // If the output section contains only symbol assignments, create a
659 // corresponding output section. The bfd linker seems to only create them if
660 // '.' is assigned to, but creating these section should not have any bad
661 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000662 uint64_t Flags = SHF_ALLOC;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000663
664 for (int I = 0, E = Opt.Commands.size(); I != E; ++I) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000665 auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I]);
666 if (!Sec)
Rafael Espindola9546fff2016-09-22 14:40:50 +0000667 continue;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000668 if (Sec->Live) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000669 Flags = Sec->Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000670 continue;
671 }
672
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000673 if (isAllSectionDescription(*Sec))
Rafael Espindola6a537372016-11-14 14:33:49 +0000674 continue;
675
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000676 Sec->Live = true;
677 Sec->SectionIndex = I;
678 Sec->Flags = Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000679 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000680}
681
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000682void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000683 // Try and find an appropriate memory region to assign offsets in.
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000684 for (BaseCommand *Base : Opt.Commands) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000685 if (auto *Sec = dyn_cast<OutputSection>(Base)) {
686 Sec->MemRegion = findMemoryRegion(Sec);
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000687 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000688 if (Sec->AlignExpr)
689 Sec->updateAlignment(Sec->AlignExpr().getValue());
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000690 }
691 }
Rafael Espindolafeed7502017-04-06 21:31:24 +0000692
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000693 // If output section command doesn't specify any segments,
694 // and we haven't previously assigned any section to segment,
695 // then we simply assign section to the very first load segment.
696 // Below is an example of such linker script:
697 // PHDRS { seg PT_LOAD; }
698 // SECTIONS { .aaa : { *(.aaa) } }
699 std::vector<StringRef> DefPhdrs;
700 auto FirstPtLoad =
701 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
702 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
703 if (FirstPtLoad != Opt.PhdrsCommands.end())
704 DefPhdrs.push_back(FirstPtLoad->Name);
705
706 // Walk the commands and propagate the program headers to commands that don't
707 // explicitly specify them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000708 for (BaseCommand *Base : Opt.Commands) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000709 auto *Sec = dyn_cast<OutputSection>(Base);
710 if (!Sec)
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000711 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000712
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000713 if (Sec->Phdrs.empty()) {
Andrew Nga020d342017-07-03 10:11:25 +0000714 // To match the bfd linker script behaviour, only propagate program
715 // headers to sections that are allocated.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000716 if (Sec->Flags & SHF_ALLOC)
717 Sec->Phdrs = DefPhdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000718 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000719 DefPhdrs = Sec->Phdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000720 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000721 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000722
723 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000724}
725
Petr Hosekb93c5b92017-08-23 18:44:34 +0000726// Try to find an address for the file and program headers output sections,
727// which were unconditionally added to the first PT_LOAD segment earlier.
728//
729// When using the default layout, we check if the headers fit below the first
730// allocated section. When using a linker script, we also check if the headers
731// are covered by the output section. This allows omitting the headers by not
732// leaving enough space for them in the linker script; this pattern is common
733// in embedded systems.
734//
735// If there isn't enough space for these sections, we'll remove them from the
736// PT_LOAD segment, and we'll also remove the PT_PHDR segment.
George Rimaraa354182017-07-27 07:46:50 +0000737void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
Peter Smith5aedebf2017-07-05 09:12:54 +0000738 uint64_t Min = std::numeric_limits<uint64_t>::max();
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000739 for (OutputSection *Sec : OutputSections)
Peter Smith5aedebf2017-07-05 09:12:54 +0000740 if (Sec->Flags & SHF_ALLOC)
741 Min = std::min<uint64_t>(Min, Sec->Addr);
Peter Smith5aedebf2017-07-05 09:12:54 +0000742
George Rimaraa354182017-07-27 07:46:50 +0000743 auto It = llvm::find_if(
744 Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
745 if (It == Phdrs.end())
George Rimard971e702017-07-03 16:05:51 +0000746 return;
George Rimaraa354182017-07-27 07:46:50 +0000747 PhdrEntry *FirstPTLoad = *It;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000748
749 uint64_t HeaderSize = getHeaderSize();
Petr Hosekb93c5b92017-08-23 18:44:34 +0000750 // When linker script with SECTIONS is being used, don't output headers
751 // unless there's a space for them.
752 uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
753 if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
754 Min = Opt.HasSections ? Base
755 : alignDown(Min - HeaderSize, Config->MaxPageSize);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000756 Out::ElfHeader->Addr = Min;
757 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
George Rimard971e702017-07-03 16:05:51 +0000758 return;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000759 }
760
Rafael Espindola02ed7572017-05-04 19:34:17 +0000761 OutputSection *ActualFirst = nullptr;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000762 for (OutputSection *Sec : OutputSections) {
Rafael Espindola02ed7572017-05-04 19:34:17 +0000763 if (Sec->FirstInPtLoad == Out::ElfHeader) {
764 ActualFirst = Sec;
765 break;
766 }
767 }
768 if (ActualFirst) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000769 for (OutputSection *Sec : OutputSections)
Rafael Espindola02ed7572017-05-04 19:34:17 +0000770 if (Sec->FirstInPtLoad == Out::ElfHeader)
771 Sec->FirstInPtLoad = ActualFirst;
772 FirstPTLoad->First = ActualFirst;
773 } else {
George Rimaraa354182017-07-27 07:46:50 +0000774 Phdrs.erase(It);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000775 }
776
George Rimard971e702017-07-03 16:05:51 +0000777 auto PhdrI = llvm::find_if(
George Rimaraa354182017-07-27 07:46:50 +0000778 Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
Rafael Espindola02ed7572017-05-04 19:34:17 +0000779 if (PhdrI != Phdrs.end())
780 Phdrs.erase(PhdrI);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000781}
782
Peter Smith906e9a12017-07-07 09:11:27 +0000783LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
784 for (auto &MRI : Opt.MemoryRegions) {
785 const MemoryRegion *MR = &MRI.second;
786 MemRegionOffset[MR] = MR->Origin;
787 }
788}
789
Peter Smith5aedebf2017-07-05 09:12:54 +0000790void LinkerScript::assignAddresses() {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000791 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000792 Dot = 0;
Peter Smith906e9a12017-07-07 09:11:27 +0000793 auto State = make_unique<AddressState>(Opt);
Peter Smithc1ace402017-07-11 09:28:27 +0000794 // CurAddressState captures the local AddressState and makes it accessible
795 // deliberately. This is needed as there are some cases where we cannot just
796 // thread the current state through to a lambda function created by the
797 // script parser.
Peter Smith906e9a12017-07-07 09:11:27 +0000798 CurAddressState = State.get();
Rafael Espindola72dc1952017-03-17 13:05:04 +0000799 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000800 switchTo(Aether);
801
Rui Ueyama8f99f732017-04-05 03:20:42 +0000802 for (BaseCommand *Base : Opt.Commands) {
803 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
Rui Ueyamad379f732017-04-05 03:20:22 +0000804 assignSymbol(Cmd, false);
George Rimar652852c2016-04-16 10:10:32 +0000805 continue;
806 }
807
Rui Ueyama8f99f732017-04-05 03:20:42 +0000808 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000809 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000810 continue;
811 }
812
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000813 assignOffsets(cast<OutputSection>(Base));
George Rimar652852c2016-04-16 10:10:32 +0000814 }
Peter Smithc1ace402017-07-11 09:28:27 +0000815 CurAddressState = nullptr;
George Rimar652852c2016-04-16 10:10:32 +0000816}
817
Rui Ueyama464daad2016-08-22 04:55:20 +0000818// Creates program headers as instructed by PHDRS linker script command.
George Rimaraa354182017-07-27 07:46:50 +0000819std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
820 std::vector<PhdrEntry *> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000821
Rui Ueyama464daad2016-08-22 04:55:20 +0000822 // Process PHDRS and FILEHDR keywords because they are not
823 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000824 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
George Rimaraa354182017-07-27 07:46:50 +0000825 PhdrEntry *Phdr =
826 make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000827
828 if (Cmd.HasFilehdr)
George Rimaraa354182017-07-27 07:46:50 +0000829 Phdr->add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000830 if (Cmd.HasPhdrs)
George Rimaraa354182017-07-27 07:46:50 +0000831 Phdr->add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000832
833 if (Cmd.LMAExpr) {
George Rimaraa354182017-07-27 07:46:50 +0000834 Phdr->p_paddr = Cmd.LMAExpr().getValue();
835 Phdr->HasLMA = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000836 }
George Rimaraa354182017-07-27 07:46:50 +0000837 Ret.push_back(Phdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000838 }
839
Rui Ueyama464daad2016-08-22 04:55:20 +0000840 // Add output sections to program headers.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000841 for (OutputSection *Sec : OutputSections) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000842 // Assign headers specified by linker script
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000843 for (size_t Id : getPhdrIndices(Sec)) {
George Rimaraa354182017-07-27 07:46:50 +0000844 Ret[Id]->add(Sec);
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000845 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
George Rimaraa354182017-07-27 07:46:50 +0000846 Ret[Id]->p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000847 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000848 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000849 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000850}
851
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000852bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000853 // Ignore .interp section in case we have PHDRS specification
854 // and PT_INTERP isn't listed.
Rui Ueyamae31d9882017-04-05 05:06:17 +0000855 if (Opt.PhdrsCommands.empty())
856 return false;
857 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
858 if (Cmd.Type == PT_INTERP)
859 return false;
860 return true;
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000861}
862
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000863ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar7e5b0a592017-08-17 08:47:21 +0000864 if (S == ".") {
865 if (CurAddressState)
866 return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
867 Loc};
868 error(Loc + ": unable to get location counter value");
869 return 0;
870 }
Rafael Espindola244ef982017-07-26 18:42:48 +0000871 if (SymbolBody *B = Symtab->find(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000872 if (auto *D = dyn_cast<DefinedRegular>(B))
George Rimar41c7ab42017-06-07 08:54:43 +0000873 return {D->Section, D->Value, Loc};
Petr Hosek30f16b22017-03-23 03:52:34 +0000874 if (auto *C = dyn_cast<DefinedCommon>(B))
George Rimar41c7ab42017-06-07 08:54:43 +0000875 return {InX::Common, C->Offset, Loc};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000876 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000877 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000878 return 0;
879}
880
Rafael Espindola244ef982017-07-26 18:42:48 +0000881bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +0000882
Andrew Ng6e9f98c2017-06-19 15:28:58 +0000883static const size_t NoPhdr = -1;
884
Rafael Espindola2c923c22017-05-10 14:28:31 +0000885// Returns indices of ELF headers containing specific section. Each index is a
886// zero based number of ELF header listed within PHDRS {} script block.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000887std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
Rafael Espindola9f9e99b2017-07-05 22:30:04 +0000888 std::vector<size_t> Ret;
889 for (StringRef PhdrName : Cmd->Phdrs) {
890 size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
891 if (Index != NoPhdr)
892 Ret.push_back(Index);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000893 }
Rafael Espindola9f9e99b2017-07-05 22:30:04 +0000894 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000895}
896
Andrew Ng6e9f98c2017-06-19 15:28:58 +0000897// Returns the index of the segment named PhdrName if found otherwise
898// NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
899// (which can be used to explicitly specify that a section isn't assigned to a
900// segment) then error.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000901size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000902 size_t I = 0;
903 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
904 if (Cmd.Name == PhdrName)
905 return I;
906 ++I;
907 }
Andrew Ng6e9f98c2017-06-19 15:28:58 +0000908 if (PhdrName != "NONE")
909 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
910 return NoPhdr;
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000911}