blob: af8398290e670476bf4f8a712f6193cb402d830d [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 Espindolaa6acd232017-09-12 00:06:00 +000073uint64_t ExprValue::getSectionOffset() const {
Rafael Espindola8b250342017-09-20 17:43:44 +000074 // If the alignment is trivial, we don't have to compute the full
75 // value to know the offset. This allows this function to succeed in
76 // cases where the output section is not yet known.
77 if (Alignment == 1)
78 return Val;
Rafael Espindolaa6acd232017-09-12 00:06:00 +000079 return getValue() - getSecAddr();
80}
81
Rafael Espindolaa5e8dd32017-07-26 18:47:49 +000082static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000083 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000084 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Rafael Espindola244ef982017-07-26 18:42:48 +000085 std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
86 /*CanOmitFromDynSym*/ false,
87 /*File*/ nullptr);
Petr Hosek5e51f7d2017-02-21 22:32:51 +000088 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +000089 ExprValue Value = Cmd->Expression();
90 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
George Rimar01aa7952017-04-14 09:23:26 +000091
92 // We want to set symbol values early if we can. This allows us to use symbols
93 // as variables in linker scripts. Doing so allows us to write expressions
94 // like this: `alignment = 16; . = ALIGN(., alignment)`
Rafael Espindolae4bad832017-09-20 16:42:56 +000095 uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
Rafael Espindola6e93d052017-08-04 22:31:42 +000096 replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
97 Visibility, STT_NOTYPE, SymValue, 0, Sec);
Meador Inge8f1f3c42017-01-09 18:36:57 +000098 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000099}
100
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000101OutputSection *LinkerScript::createOutputSection(StringRef Name,
102 StringRef Location) {
103 OutputSection *&SecRef = NameToOutputSection[Name];
104 OutputSection *Sec;
105 if (SecRef && SecRef->Location.empty()) {
Rafael Espindola05c4f672017-06-01 01:16:50 +0000106 // There was a forward reference.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000107 Sec = SecRef;
Rafael Espindola05c4f672017-06-01 01:16:50 +0000108 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000109 Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
110 if (!SecRef)
111 SecRef = Sec;
Rafael Espindola05c4f672017-06-01 01:16:50 +0000112 }
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000113 Sec->Location = Location;
114 return Sec;
George Rimar851dc1e2017-03-14 10:15:53 +0000115}
116
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000117OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
118 OutputSection *&CmdRef = NameToOutputSection[Name];
Rafael Espindola05c4f672017-06-01 01:16:50 +0000119 if (!CmdRef)
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000120 CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
Rafael Espindola05c4f672017-06-01 01:16:50 +0000121 return CmdRef;
George Rimard83ce1b2017-03-14 10:24:47 +0000122}
123
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000124void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000125 uint64_t Val = E().getValue();
George Rimar8c804d92017-07-12 14:50:25 +0000126 if (Val < Dot && InSec)
127 error(Loc + ": unable to move location counter backward for: " +
128 CurAddressState->OutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000129 Dot = Val;
130 // Update to location counter means update to section size.
131 if (InSec)
Peter Smith906e9a12017-07-07 09:11:27 +0000132 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
Rafael Espindola679828f2017-02-17 16:26:13 +0000133}
134
George Rimarb2b70972017-02-07 10:23:28 +0000135// Sets value of a symbol. Two kinds of symbols are processed: synthetic
136// symbols, whose value is an offset from beginning of section and regular
137// symbols whose value is absolute.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000138void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000139 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000140 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000141 return;
142 }
143
George Rimarb2b70972017-02-07 10:23:28 +0000144 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000145 return;
146
Rafael Espindola5616adf2017-03-08 22:36:28 +0000147 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000148 ExprValue V = Cmd->Expression();
149 if (V.isAbsolute()) {
150 Sym->Value = V.getValue();
151 } else {
152 Sym->Section = V.Sec;
Rafael Espindolaa6acd232017-09-12 00:06:00 +0000153 Sym->Value = V.getSectionOffset();
Meador Inge8f1f3c42017-01-09 18:36:57 +0000154 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000155}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000156
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000157void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000158 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000159 return;
160
161 // If a symbol was in PROVIDE(), we need to define it only when
162 // it is a referenced undefined symbol.
Rafael Espindola244ef982017-07-26 18:42:48 +0000163 SymbolBody *B = Symtab->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000164 if (Cmd->Provide && (!B || B->isDefined()))
165 return;
166
Rafael Espindolaa5e8dd32017-07-26 18:47:49 +0000167 Cmd->Sym = addRegular(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000168}
169
George Rimar076fe152016-07-21 06:43:01 +0000170bool SymbolAssignment::classof(const BaseCommand *C) {
171 return C->Kind == AssignmentKind;
172}
173
George Rimareea31142016-07-21 14:26:59 +0000174bool InputSectionDescription::classof(const BaseCommand *C) {
175 return C->Kind == InputSectionKind;
176}
177
George Rimareefa7582016-08-04 09:29:31 +0000178bool AssertCommand::classof(const BaseCommand *C) {
179 return C->Kind == AssertKind;
180}
181
George Rimare38cbab2016-09-26 19:22:50 +0000182bool BytesDataCommand::classof(const BaseCommand *C) {
183 return C->Kind == BytesDataKind;
184}
185
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000186static std::string filename(InputFile *File) {
187 if (!File)
Dmitry Mikulinf300ca22017-08-24 22:01:40 +0000188 return "";
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000189 if (File->ArchiveName.empty())
190 return File->getName();
191 return (File->ArchiveName + "(" + File->getName() + ")").str();
Rui Ueyamae0be2902016-11-21 02:10:12 +0000192}
193
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000194bool LinkerScript::shouldKeep(InputSectionBase *S) {
Dmitry Mikulinf300ca22017-08-24 22:01:40 +0000195 for (InputSectionDescription *ID : Opt.KeptSections) {
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000196 std::string Filename = filename(S->File);
Dmitry Mikulinf300ca22017-08-24 22:01:40 +0000197 if (ID->FilePat.match(Filename))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000198 for (SectionPattern &P : ID->SectionPatterns)
199 if (P.SectionPat.match(S->Name))
200 return true;
Dmitry Mikulinf300ca22017-08-24 22:01:40 +0000201 }
George Rimareea31142016-07-21 14:26:59 +0000202 return false;
203}
204
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000205// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000206static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000207getComparator(SortSectionPolicy K) {
208 switch (K) {
209 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000210 return [](InputSectionBase *A, InputSectionBase *B) {
211 // ">" is not a mistake. Sections with larger alignments are placed
212 // before sections with smaller alignments in order to reduce the
213 // amount of padding necessary. This is compatible with GNU.
214 return A->Alignment > B->Alignment;
215 };
George Rimarbe394db2016-09-16 20:21:55 +0000216 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000217 return [](InputSectionBase *A, InputSectionBase *B) {
218 return A->Name < B->Name;
219 };
George Rimarbe394db2016-09-16 20:21:55 +0000220 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000221 return [](InputSectionBase *A, InputSectionBase *B) {
222 return getPriority(A->Name) < getPriority(B->Name);
223 };
George Rimarbe394db2016-09-16 20:21:55 +0000224 default:
225 llvm_unreachable("unknown sort policy");
226 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000227}
George Rimar0702c4e2016-07-29 15:32:46 +0000228
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000229// A helper function for the SORT() command.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000230static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000231 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000232 if (Kind == ConstraintKind::NoConstraint)
233 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000234
235 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
236 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000237 });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000238
Rafael Espindolae746e522016-09-21 18:33:44 +0000239 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
240 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000241}
242
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000243static void sortSections(InputSection **Begin, InputSection **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000244 SortSectionPolicy K) {
245 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000246 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000247}
248
George Rimard6bcde32017-08-04 10:25:29 +0000249static void sortBySymbolOrder(InputSection **Begin, InputSection **End) {
250 if (Config->SymbolOrderingFile.empty())
251 return;
George Rimar696a7f92017-09-19 09:20:54 +0000252 static llvm::DenseMap<SectionBase *, int> Order = buildSectionOrder();
George Rimard6bcde32017-08-04 10:25:29 +0000253 MutableArrayRef<InputSection *> In(Begin, End - Begin);
254 sortByOrder(In, [&](InputSectionBase *S) { return Order.lookup(S); });
255}
256
Rafael Espindolad3190792016-09-16 15:10:23 +0000257// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000258std::vector<InputSection *>
Rui Ueyama72e107f2017-04-05 02:05:48 +0000259LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000260 std::vector<InputSection *> Ret;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000261
Rui Ueyama72e107f2017-04-05 02:05:48 +0000262 // Collects all sections that satisfy constraints of Cmd.
263 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
264 size_t SizeBefore = Ret.size();
265
266 for (InputSectionBase *Sec : InputSections) {
267 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000268 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000269
Rafael Espindolae39709b2017-05-30 20:40:03 +0000270 if (!Sec->Live) {
271 reportDiscarded(Sec);
272 continue;
273 }
274
Rafael Espindola908a3d32017-02-16 14:36:09 +0000275 // For -emit-relocs we have to ignore entries like
276 // .rela.dyn : { *(.rela.data) }
277 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000278 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000279 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000280
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000281 std::string Filename = filename(Sec->File);
Rui Ueyama72e107f2017-04-05 02:05:48 +0000282 if (!Cmd->FilePat.match(Filename) ||
283 Pat.ExcludedFilePat.match(Filename) ||
284 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000285 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000286
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000287 Ret.push_back(cast<InputSection>(Sec));
Rui Ueyama72e107f2017-04-05 02:05:48 +0000288 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000289 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000290
George Rimar07171f22016-09-21 15:56:44 +0000291 // Sort sections as instructed by SORT-family commands and --sort-section
292 // option. Because SORT-family commands can be nested at most two depth
293 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
294 // line option is respected even if a SORT command is given, the exact
295 // behavior we have here is a bit complicated. Here are the rules.
296 //
297 // 1. If two SORT commands are given, --sort-section is ignored.
298 // 2. If one SORT command is given, and if it is not SORT_NONE,
299 // --sort-section is handled as an inner SORT command.
300 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
301 // 4. If no SORT command is given, sort according to --sort-section.
George Rimard6bcde32017-08-04 10:25:29 +0000302 // 5. If no SORT commands are given and --sort-section is not specified,
303 // apply sorting provided by --symbol-ordering-file if any exist.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000304 InputSection **Begin = Ret.data() + SizeBefore;
305 InputSection **End = Ret.data() + Ret.size();
George Rimard6bcde32017-08-04 10:25:29 +0000306 if (Pat.SortOuter == SortSectionPolicy::Default &&
307 Config->SortSection == SortSectionPolicy::Default) {
308 sortBySymbolOrder(Begin, End);
309 continue;
310 }
George Rimar07171f22016-09-21 15:56:44 +0000311 if (Pat.SortOuter != SortSectionPolicy::None) {
312 if (Pat.SortInner == SortSectionPolicy::Default)
313 sortSections(Begin, End, Config->SortSection);
314 else
315 sortSections(Begin, End, Pat.SortInner);
316 sortSections(Begin, End, Pat.SortOuter);
317 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000318 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000319 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000320}
321
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000322void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000323 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000324 S->Live = false;
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000325 if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
326 S == InX::DynStrTab)
Rafael Espindola2af64b02017-06-16 23:45:35 +0000327 error("discarding " + S->Name + " section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000328 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000329 }
330}
331
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000332std::vector<InputSectionBase *>
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000333LinkerScript::createInputSectionList(OutputSection &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000334 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000335
Rui Ueyama8f99f732017-04-05 03:20:42 +0000336 for (BaseCommand *Base : OutCmd.Commands) {
337 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000338 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000339 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000340
341 Cmd->Sections = computeInputSections(Cmd);
Rafael Espindolae4c8b9b2017-04-07 16:10:46 +0000342 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000343 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000344
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000345 return Ret;
346}
347
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000348void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000349 // A symbol can be assigned before any section is mentioned in the linker
350 // script. In an DSO, the symbol values are addresses, so the only important
351 // section values are:
352 // * SHN_UNDEF
353 // * SHN_ABS
354 // * Any value meaning a regular section.
355 // To handle that, create a dummy aether section that fills the void before
356 // the linker scripts switches to another section. It has an index of one
357 // which will map to whatever the first actual section is.
358 Aether = make<OutputSection>("", 0, SHF_ALLOC);
359 Aether->SectionIndex = 1;
Peter Smith906e9a12017-07-07 09:11:27 +0000360 auto State = make_unique<AddressState>(Opt);
Peter Smithc1ace402017-07-11 09:28:27 +0000361 // CurAddressState captures the local AddressState and makes it accessible
362 // deliberately. This is needed as there are some cases where we cannot just
363 // thread the current state through to a lambda function created by the
364 // script parser.
Peter Smith906e9a12017-07-07 09:11:27 +0000365 CurAddressState = State.get();
366 CurAddressState->OutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000367 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000368
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000369 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000370 // Handle symbol assignments outside of any output section.
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000371 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000372 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000373 continue;
374 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000375
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000376 if (auto *Sec = dyn_cast<OutputSection>(Opt.Commands[I])) {
377 std::vector<InputSectionBase *> V = createInputSectionList(*Sec);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000378
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000379 // The output section name `/DISCARD/' is special.
380 // Any input section assigned to it is discarded.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000381 if (Sec->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000382 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000383 continue;
384 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000385
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000386 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
387 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
388 // sections satisfy a given constraint. If not, a directive is handled
George Rimar07d7c422017-04-05 09:19:29 +0000389 // as if it wasn't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000390 //
391 // Because we'll iterate over Commands many more times, the easiest
George Rimar07d7c422017-04-05 09:19:29 +0000392 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000393 if (!matchConstraints(V, Sec->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000394 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000395 S->Assigned = false;
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000396 Opt.Commands.erase(Opt.Commands.begin() + I);
George Rimar07d7c422017-04-05 09:19:29 +0000397 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000398 continue;
399 }
400
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000401 // A directive may contain symbol definitions like this:
402 // ".foo : { ...; bar = .; }". Handle them.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000403 for (BaseCommand *Base : Sec->Commands)
Rui Ueyama8f99f732017-04-05 03:20:42 +0000404 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000405 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000406
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000407 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
408 // is given, input sections are aligned to that value, whether the
409 // given value is larger or smaller than the original section alignment.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000410 if (Sec->SubalignExpr) {
411 uint32_t Subalign = Sec->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000412 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000413 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000414 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000415
416 // Add input sections to an output section.
George Rimard86a4e52017-05-08 10:18:12 +0000417 for (InputSectionBase *S : V)
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000418 Factory.addInputSec(S, Sec->Name, Sec);
419 assert(Sec->SectionIndex == INT_MAX);
420 Sec->SectionIndex = I;
421 if (Sec->Noload)
422 Sec->Type = SHT_NOBITS;
Eugene Leviantceabe802016-08-11 07:56:43 +0000423 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000424 }
Peter Smithc1ace402017-07-11 09:28:27 +0000425 CurAddressState = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000426}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000427
Rafael Espindola02ed7572017-05-04 19:34:17 +0000428void LinkerScript::fabricateDefaultCommands() {
Peter Smithcbfe9e92017-04-19 12:46:32 +0000429 // Define start address
Rafael Espindolae76231b2017-06-08 04:17:04 +0000430 uint64_t StartAddr = -1;
Peter Smithcbfe9e92017-04-19 12:46:32 +0000431
Peter Smithc60b4512017-05-03 08:44:50 +0000432 // The Sections with -T<section> have been sorted in order of ascending
433 // address. We must lower StartAddr if the lowest -T<section address> as
434 // calls to setDot() must be monotonically increasing.
George Rimar67c60722017-07-18 11:55:35 +0000435 for (auto &KV : Config->SectionStartMap)
Peter Smithc60b4512017-05-03 08:44:50 +0000436 StartAddr = std::min(StartAddr, KV.second);
437
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000438 Opt.Commands.insert(Opt.Commands.begin(),
439 make<SymbolAssignment>(".",
440 [=] {
441 return std::min(
442 StartAddr,
443 Config->ImageBase +
444 elf::getHeaderSize());
445 },
446 ""));
Peter Smithcbfe9e92017-04-19 12:46:32 +0000447}
448
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000449// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000450void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rafael Espindolad7faa912017-07-05 17:50:43 +0000451 unsigned NumCommands = Opt.Commands.size();
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000452 for (InputSectionBase *S : InputSections) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000453 if (!S->Live || S->Parent)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000454 continue;
455 StringRef Name = getOutputSectionName(S->Name);
Rafael Espindolad7faa912017-07-05 17:50:43 +0000456 auto End = Opt.Commands.begin() + NumCommands;
457 auto I = std::find_if(Opt.Commands.begin(), End, [&](BaseCommand *Base) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000458 if (auto *Sec = dyn_cast<OutputSection>(Base))
459 return Sec->Name == Name;
George Rimara951d5c2017-07-04 13:10:37 +0000460 return false;
461 });
Rafael Espindolad7faa912017-07-05 17:50:43 +0000462 if (I == End) {
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000463 Factory.addInputSec(S, Name);
Rafael Espindolaa2df2f02017-07-27 21:42:42 +0000464 assert(S->getOutputSection()->SectionIndex == INT_MAX);
Rafael Espindolade8d9892017-04-29 15:44:03 +0000465 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000466 OutputSection *Sec = cast<OutputSection>(*I);
467 Factory.addInputSec(S, Name, Sec);
468 unsigned Index = std::distance(Opt.Commands.begin(), I);
469 assert(Sec->SectionIndex == INT_MAX || Sec->SectionIndex == Index);
470 Sec->SectionIndex = Index;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000471 }
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000472 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000473}
474
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000475uint64_t LinkerScript::advance(uint64_t Size, unsigned Align) {
Peter Smith906e9a12017-07-07 09:11:27 +0000476 bool IsTbss = (CurAddressState->OutSec->Flags & SHF_TLS) &&
477 CurAddressState->OutSec->Type == SHT_NOBITS;
478 uint64_t Start = IsTbss ? Dot + CurAddressState->ThreadBssOffset : Dot;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000479 Start = alignTo(Start, Align);
480 uint64_t End = Start + Size;
481
482 if (IsTbss)
Peter Smith906e9a12017-07-07 09:11:27 +0000483 CurAddressState->ThreadBssOffset = End - Dot;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000484 else
485 Dot = End;
486 return End;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000487}
488
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000489void LinkerScript::output(InputSection *S) {
George Rimarf694d332017-07-25 08:29:29 +0000490 uint64_t Before = advance(0, 1);
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000491 uint64_t Pos = advance(S->getSize(), S->Alignment);
Peter Smith906e9a12017-07-07 09:11:27 +0000492 S->OutSecOff = Pos - S->getSize() - CurAddressState->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000493
494 // Update output section size after adding each section. This is so that
495 // SIZEOF works correctly in the case below:
496 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Peter Smith906e9a12017-07-07 09:11:27 +0000497 CurAddressState->OutSec->Size = Pos - CurAddressState->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000498
Meador Ingeb8897442017-01-24 02:34:00 +0000499 // If there is a memory region associated with this input section, then
500 // place the section in that region and update the region index.
Peter Smith906e9a12017-07-07 09:11:27 +0000501 if (CurAddressState->MemRegion) {
502 uint64_t &CurOffset =
503 CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
George Rimarf694d332017-07-25 08:29:29 +0000504 CurOffset += Pos - Before;
Peter Smith906e9a12017-07-07 09:11:27 +0000505 uint64_t CurSize = CurOffset - CurAddressState->MemRegion->Origin;
506 if (CurSize > CurAddressState->MemRegion->Length) {
507 uint64_t OverflowAmt = CurSize - CurAddressState->MemRegion->Length;
508 error("section '" + CurAddressState->OutSec->Name +
509 "' will not fit in region '" + CurAddressState->MemRegion->Name +
510 "': overflowed by " + Twine(OverflowAmt) + " bytes");
Meador Ingeb8897442017-01-24 02:34:00 +0000511 }
512 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000513}
514
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000515void LinkerScript::switchTo(OutputSection *Sec) {
Peter Smith906e9a12017-07-07 09:11:27 +0000516 if (CurAddressState->OutSec == Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000517 return;
Rafael Espindolad3190792016-09-16 15:10:23 +0000518
Peter Smith906e9a12017-07-07 09:11:27 +0000519 CurAddressState->OutSec = Sec;
520 CurAddressState->OutSec->Addr =
521 advance(0, CurAddressState->OutSec->Alignment);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000522
523 // If neither AT nor AT> is specified for an allocatable section, the linker
524 // will set the LMA such that the difference between VMA and LMA for the
525 // section is the same as the preceding output section in the same region
526 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
Peter Smith906e9a12017-07-07 09:11:27 +0000527 if (CurAddressState->LMAOffset)
528 CurAddressState->OutSec->LMAOffset = CurAddressState->LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000529}
530
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000531void LinkerScript::process(BaseCommand &Base) {
Rui Ueyama2e081a42017-04-05 03:18:46 +0000532 // This handles the assignments to symbol or to the dot.
533 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
534 assignSymbol(Cmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000535 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000536 }
George Rimare38cbab2016-09-26 19:22:50 +0000537
538 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyama2e081a42017-04-05 03:18:46 +0000539 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
Peter Smith906e9a12017-07-07 09:11:27 +0000540 Cmd->Offset = Dot - CurAddressState->OutSec->Addr;
Rui Ueyama2e081a42017-04-05 03:18:46 +0000541 Dot += Cmd->Size;
Peter Smith906e9a12017-07-07 09:11:27 +0000542 CurAddressState->OutSec->Size = Dot - CurAddressState->OutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000543 return;
544 }
545
Rui Ueyama2e081a42017-04-05 03:18:46 +0000546 // Handle ASSERT().
547 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
548 Cmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000549 return;
550 }
551
Rui Ueyama2e081a42017-04-05 03:18:46 +0000552 // Handle a single input section description command.
553 // It calculates and assigns the offsets for each section and also
George Rimare38cbab2016-09-26 19:22:50 +0000554 // updates the output section size.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000555 auto &Cmd = cast<InputSectionDescription>(Base);
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000556 for (InputSection *Sec : Cmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000557 // We tentatively added all synthetic sections at the beginning and removed
558 // empty ones afterwards (because there is no way to know whether they were
559 // going be empty or not other than actually running linker scripts.)
560 // We need to ignore remains of empty sections.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000561 if (auto *S = dyn_cast<SyntheticSection>(Sec))
562 if (S->empty())
George Rimar3fb5a6d2016-11-29 16:05:27 +0000563 continue;
564
Rui Ueyama2e081a42017-04-05 03:18:46 +0000565 if (!Sec->Live)
George Rimar78ef6452017-02-21 15:46:43 +0000566 continue;
Peter Smith906e9a12017-07-07 09:11:27 +0000567 assert(CurAddressState->OutSec == Sec->getParent());
Rafael Espindolaa85e8dd2017-05-30 20:24:52 +0000568 output(Sec);
Eugene Leviantceabe802016-08-11 07:56:43 +0000569 }
570}
571
Meador Ingeb8897442017-01-24 02:34:00 +0000572// This function searches for a memory region to place the given output
573// section in. If found, a pointer to the appropriate memory region is
574// returned. Otherwise, a nullptr is returned.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000575MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000576 // If a memory region name was specified in the output section command,
577 // then try to find that region first.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000578 if (!Sec->MemoryRegionName.empty()) {
579 auto It = Opt.MemoryRegions.find(Sec->MemoryRegionName);
Meador Ingeb8897442017-01-24 02:34:00 +0000580 if (It != Opt.MemoryRegions.end())
George Rimar5f375412017-09-08 08:23:15 +0000581 return It->second;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000582 error("memory region '" + Sec->MemoryRegionName + "' not declared");
Meador Ingeb8897442017-01-24 02:34:00 +0000583 return nullptr;
584 }
585
Rui Ueyamad7c54002017-04-05 03:19:43 +0000586 // If at least one memory region is defined, all sections must
587 // belong to some memory region. Otherwise, we don't need to do
588 // anything for memory regions.
Rui Ueyamacc400cc2017-04-05 03:19:24 +0000589 if (Opt.MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000590 return nullptr;
591
592 // See if a region can be found by matching section flags.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000593 for (auto &Pair : Opt.MemoryRegions) {
George Rimar5f375412017-09-08 08:23:15 +0000594 MemoryRegion *M = Pair.second;
595 if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
596 return M;
Meador Ingeb8897442017-01-24 02:34:00 +0000597 }
598
599 // Otherwise, no suitable region was found.
600 if (Sec->Flags & SHF_ALLOC)
601 error("no memory region specified for section '" + Sec->Name + "'");
602 return nullptr;
603}
604
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000605// This function assigns offsets to input sections and an output section
606// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000607void LinkerScript::assignOffsets(OutputSection *Sec) {
Rafael Espindoladece2802017-06-13 20:57:43 +0000608 if (!(Sec->Flags & SHF_ALLOC))
609 Dot = 0;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000610 else if (Sec->AddrExpr)
611 setDot(Sec->AddrExpr, Sec->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000612
George Rimarc2dffe32017-09-06 09:35:09 +0000613 CurAddressState->MemRegion = Sec->MemRegion;
614 if (CurAddressState->MemRegion)
615 Dot = CurAddressState->MemRegionOffset[CurAddressState->MemRegion];
616
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000617 if (Sec->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000618 uint64_t D = Dot;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000619 CurAddressState->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000620 }
621
Meador Ingeb8897442017-01-24 02:34:00 +0000622 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000623
George Rimard86a4e52017-05-08 10:18:12 +0000624 // We do not support custom layout for compressed debug sectons.
625 // At this point we already know their size and have compressed content.
Peter Smith906e9a12017-07-07 09:11:27 +0000626 if (CurAddressState->OutSec->Flags & SHF_COMPRESSED)
George Rimard86a4e52017-05-08 10:18:12 +0000627 return;
628
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000629 for (BaseCommand *C : Sec->Commands)
Rafael Espindolade8d9892017-04-29 15:44:03 +0000630 process(*C);
Rafael Espindolad3190792016-09-16 15:10:23 +0000631}
632
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000633void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000634 // It is common practice to use very generic linker scripts. So for any
635 // given run some of the output sections in the script will be empty.
636 // We could create corresponding empty output sections, but that would
637 // clutter the output.
638 // We instead remove trivially empty sections. The bfd linker seems even
639 // more aggressive at removing them.
George Rimar60608a82017-08-28 09:28:15 +0000640 llvm::erase_if(Opt.Commands, [&](BaseCommand *Base) {
641 if (auto *Sec = dyn_cast<OutputSection>(Base))
642 return !Sec->Live;
643 return false;
644 });
Rafael Espindola07fe6122016-11-14 14:23:35 +0000645}
646
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000647static bool isAllSectionDescription(const OutputSection &Cmd) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000648 for (BaseCommand *Base : Cmd.Commands)
649 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000650 return false;
651 return true;
652}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000653
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000654void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000655 // If the output section contains only symbol assignments, create a
656 // corresponding output section. The bfd linker seems to only create them if
657 // '.' is assigned to, but creating these section should not have any bad
658 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000659 uint64_t Flags = SHF_ALLOC;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000660
George Rimar8962db92017-09-18 08:43:44 +0000661 for (BaseCommand * Cmd : Opt.Commands) {
662 auto *Sec = dyn_cast<OutputSection>(Cmd);
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000663 if (!Sec)
Rafael Espindola9546fff2016-09-22 14:40:50 +0000664 continue;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000665 if (Sec->Live) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000666 Flags = Sec->Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000667 continue;
668 }
669
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000670 if (isAllSectionDescription(*Sec))
Rafael Espindola6a537372016-11-14 14:33:49 +0000671 continue;
672
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000673 Sec->Live = true;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000674 Sec->Flags = Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000675 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000676}
677
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000678void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000679 // Try and find an appropriate memory region to assign offsets in.
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000680 for (BaseCommand *Base : Opt.Commands) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000681 if (auto *Sec = dyn_cast<OutputSection>(Base)) {
682 Sec->MemRegion = findMemoryRegion(Sec);
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000683 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000684 if (Sec->AlignExpr)
685 Sec->updateAlignment(Sec->AlignExpr().getValue());
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000686 }
687 }
Rafael Espindolafeed7502017-04-06 21:31:24 +0000688
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000689 // If output section command doesn't specify any segments,
690 // and we haven't previously assigned any section to segment,
691 // then we simply assign section to the very first load segment.
692 // Below is an example of such linker script:
693 // PHDRS { seg PT_LOAD; }
694 // SECTIONS { .aaa : { *(.aaa) } }
695 std::vector<StringRef> DefPhdrs;
696 auto FirstPtLoad =
697 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
698 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
699 if (FirstPtLoad != Opt.PhdrsCommands.end())
700 DefPhdrs.push_back(FirstPtLoad->Name);
701
702 // Walk the commands and propagate the program headers to commands that don't
703 // explicitly specify them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000704 for (BaseCommand *Base : Opt.Commands) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000705 auto *Sec = dyn_cast<OutputSection>(Base);
706 if (!Sec)
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000707 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000708
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000709 if (Sec->Phdrs.empty()) {
Andrew Nga020d342017-07-03 10:11:25 +0000710 // To match the bfd linker script behaviour, only propagate program
711 // headers to sections that are allocated.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000712 if (Sec->Flags & SHF_ALLOC)
713 Sec->Phdrs = DefPhdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000714 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000715 DefPhdrs = Sec->Phdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000716 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000717 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000718
719 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000720}
721
George Rimar582ede82017-09-07 10:53:07 +0000722static OutputSection *findFirstSection(PhdrEntry *Load) {
723 for (OutputSection *Sec : OutputSections)
724 if (Sec->PtLoad == Load)
725 return Sec;
726 return nullptr;
727}
728
Petr Hosekb93c5b92017-08-23 18:44:34 +0000729// Try to find an address for the file and program headers output sections,
730// which were unconditionally added to the first PT_LOAD segment earlier.
731//
732// When using the default layout, we check if the headers fit below the first
733// allocated section. When using a linker script, we also check if the headers
734// are covered by the output section. This allows omitting the headers by not
735// leaving enough space for them in the linker script; this pattern is common
736// in embedded systems.
737//
738// If there isn't enough space for these sections, we'll remove them from the
739// PT_LOAD segment, and we'll also remove the PT_PHDR segment.
George Rimaraa354182017-07-27 07:46:50 +0000740void LinkerScript::allocateHeaders(std::vector<PhdrEntry *> &Phdrs) {
Peter Smith5aedebf2017-07-05 09:12:54 +0000741 uint64_t Min = std::numeric_limits<uint64_t>::max();
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000742 for (OutputSection *Sec : OutputSections)
Peter Smith5aedebf2017-07-05 09:12:54 +0000743 if (Sec->Flags & SHF_ALLOC)
744 Min = std::min<uint64_t>(Min, Sec->Addr);
Peter Smith5aedebf2017-07-05 09:12:54 +0000745
George Rimaraa354182017-07-27 07:46:50 +0000746 auto It = llvm::find_if(
747 Phdrs, [](const PhdrEntry *E) { return E->p_type == PT_LOAD; });
748 if (It == Phdrs.end())
George Rimard971e702017-07-03 16:05:51 +0000749 return;
George Rimaraa354182017-07-27 07:46:50 +0000750 PhdrEntry *FirstPTLoad = *It;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000751
752 uint64_t HeaderSize = getHeaderSize();
Petr Hosekb93c5b92017-08-23 18:44:34 +0000753 // When linker script with SECTIONS is being used, don't output headers
754 // unless there's a space for them.
755 uint64_t Base = Opt.HasSections ? alignDown(Min, Config->MaxPageSize) : 0;
756 if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
757 Min = Opt.HasSections ? Base
758 : alignDown(Min - HeaderSize, Config->MaxPageSize);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000759 Out::ElfHeader->Addr = Min;
760 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
George Rimard971e702017-07-03 16:05:51 +0000761 return;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000762 }
763
George Rimar582ede82017-09-07 10:53:07 +0000764 Out::ElfHeader->PtLoad = nullptr;
765 Out::ProgramHeaders->PtLoad = nullptr;
George Rimar6823c5f2017-09-07 11:01:10 +0000766 FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000767
George Rimar60608a82017-08-28 09:28:15 +0000768 llvm::erase_if(Phdrs,
769 [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
Rafael Espindola02ed7572017-05-04 19:34:17 +0000770}
771
Peter Smith906e9a12017-07-07 09:11:27 +0000772LinkerScript::AddressState::AddressState(const ScriptConfiguration &Opt) {
773 for (auto &MRI : Opt.MemoryRegions) {
George Rimar5f375412017-09-08 08:23:15 +0000774 const MemoryRegion *MR = MRI.second;
Peter Smith906e9a12017-07-07 09:11:27 +0000775 MemRegionOffset[MR] = MR->Origin;
776 }
777}
778
Peter Smith5aedebf2017-07-05 09:12:54 +0000779void LinkerScript::assignAddresses() {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000780 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000781 Dot = 0;
Peter Smith906e9a12017-07-07 09:11:27 +0000782 auto State = make_unique<AddressState>(Opt);
Peter Smithc1ace402017-07-11 09:28:27 +0000783 // CurAddressState captures the local AddressState and makes it accessible
784 // deliberately. This is needed as there are some cases where we cannot just
785 // thread the current state through to a lambda function created by the
786 // script parser.
Peter Smith906e9a12017-07-07 09:11:27 +0000787 CurAddressState = State.get();
Rafael Espindola72dc1952017-03-17 13:05:04 +0000788 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000789 switchTo(Aether);
790
Rui Ueyama8f99f732017-04-05 03:20:42 +0000791 for (BaseCommand *Base : Opt.Commands) {
792 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
Rui Ueyamad379f732017-04-05 03:20:22 +0000793 assignSymbol(Cmd, false);
George Rimar652852c2016-04-16 10:10:32 +0000794 continue;
795 }
796
Rui Ueyama8f99f732017-04-05 03:20:42 +0000797 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000798 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000799 continue;
800 }
801
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000802 assignOffsets(cast<OutputSection>(Base));
George Rimar652852c2016-04-16 10:10:32 +0000803 }
Peter Smithc1ace402017-07-11 09:28:27 +0000804 CurAddressState = nullptr;
George Rimar652852c2016-04-16 10:10:32 +0000805}
806
Rui Ueyama464daad2016-08-22 04:55:20 +0000807// Creates program headers as instructed by PHDRS linker script command.
George Rimaraa354182017-07-27 07:46:50 +0000808std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
809 std::vector<PhdrEntry *> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000810
Rui Ueyama464daad2016-08-22 04:55:20 +0000811 // Process PHDRS and FILEHDR keywords because they are not
812 // real output sections and cannot be added in the following loop.
Eugene Leviantbbe38602016-07-19 09:25:43 +0000813 for (const PhdrsCommand &Cmd : Opt.PhdrsCommands) {
George Rimaraa354182017-07-27 07:46:50 +0000814 PhdrEntry *Phdr =
815 make<PhdrEntry>(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000816
817 if (Cmd.HasFilehdr)
George Rimaraa354182017-07-27 07:46:50 +0000818 Phdr->add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000819 if (Cmd.HasPhdrs)
George Rimaraa354182017-07-27 07:46:50 +0000820 Phdr->add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000821
822 if (Cmd.LMAExpr) {
George Rimaraa354182017-07-27 07:46:50 +0000823 Phdr->p_paddr = Cmd.LMAExpr().getValue();
824 Phdr->HasLMA = true;
Eugene Leviant56b21c82016-09-09 09:46:16 +0000825 }
George Rimaraa354182017-07-27 07:46:50 +0000826 Ret.push_back(Phdr);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000827 }
828
Rui Ueyama464daad2016-08-22 04:55:20 +0000829 // Add output sections to program headers.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000830 for (OutputSection *Sec : OutputSections) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000831 // Assign headers specified by linker script
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000832 for (size_t Id : getPhdrIndices(Sec)) {
George Rimaraa354182017-07-27 07:46:50 +0000833 Ret[Id]->add(Sec);
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000834 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
George Rimaraa354182017-07-27 07:46:50 +0000835 Ret[Id]->p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000836 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000837 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000838 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000839}
840
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000841bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000842 // Ignore .interp section in case we have PHDRS specification
843 // and PT_INTERP isn't listed.
Rui Ueyamae31d9882017-04-05 05:06:17 +0000844 if (Opt.PhdrsCommands.empty())
845 return false;
846 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
847 if (Cmd.Type == PT_INTERP)
848 return false;
849 return true;
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000850}
851
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000852ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar7e5b0a592017-08-17 08:47:21 +0000853 if (S == ".") {
854 if (CurAddressState)
855 return {CurAddressState->OutSec, Dot - CurAddressState->OutSec->Addr,
856 Loc};
857 error(Loc + ": unable to get location counter value");
858 return 0;
859 }
Rafael Espindola244ef982017-07-26 18:42:48 +0000860 if (SymbolBody *B = Symtab->find(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000861 if (auto *D = dyn_cast<DefinedRegular>(B))
George Rimar41c7ab42017-06-07 08:54:43 +0000862 return {D->Section, D->Value, Loc};
Petr Hosek30f16b22017-03-23 03:52:34 +0000863 if (auto *C = dyn_cast<DefinedCommon>(B))
Rafael Espindola67df57a2017-09-12 21:19:09 +0000864 return {C->Section, 0, Loc};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000865 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000866 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000867 return 0;
868}
869
Rafael Espindola244ef982017-07-26 18:42:48 +0000870bool LinkerScript::isDefined(StringRef S) { return Symtab->find(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +0000871
Andrew Ng6e9f98c2017-06-19 15:28:58 +0000872static const size_t NoPhdr = -1;
873
Rafael Espindola2c923c22017-05-10 14:28:31 +0000874// Returns indices of ELF headers containing specific section. Each index is a
875// zero based number of ELF header listed within PHDRS {} script block.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000876std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
Rafael Espindola9f9e99b2017-07-05 22:30:04 +0000877 std::vector<size_t> Ret;
878 for (StringRef PhdrName : Cmd->Phdrs) {
879 size_t Index = getPhdrIndex(Cmd->Location, PhdrName);
880 if (Index != NoPhdr)
881 Ret.push_back(Index);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000882 }
Rafael Espindola9f9e99b2017-07-05 22:30:04 +0000883 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000884}
885
Andrew Ng6e9f98c2017-06-19 15:28:58 +0000886// Returns the index of the segment named PhdrName if found otherwise
887// NoPhdr. When not found, if PhdrName is not the special case value 'NONE'
888// (which can be used to explicitly specify that a section isn't assigned to a
889// segment) then error.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000890size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000891 size_t I = 0;
892 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
893 if (Cmd.Name == PhdrName)
894 return I;
895 ++I;
896 }
Andrew Ng6e9f98c2017-06-19 15:28:58 +0000897 if (PhdrName != "NONE")
898 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
899 return NoPhdr;
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000900}