blob: 9e39a5de32e7f21b3442d2070e56b1d0a257c655 [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"
Eugene Leviantbbe38602016-07-19 09:25:43 +000023#include "Writer.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000024#include "llvm/ADT/STLExtras.h"
25#include "llvm/ADT/StringRef.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000026#include "llvm/Support/Casting.h"
George Rimar652852c2016-04-16 10:10:32 +000027#include "llvm/Support/ELF.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000028#include "llvm/Support/Endian.h"
29#include "llvm/Support/ErrorHandling.h"
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000030#include "llvm/Support/FileSystem.h"
Rui Ueyamaf03f3cc2015-10-13 00:09:21 +000031#include "llvm/Support/Path.h"
Eugene Zelenko22886a22016-11-05 01:00:56 +000032#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <cstdint>
36#include <iterator>
37#include <limits>
Eugene Zelenko22886a22016-11-05 01:00:56 +000038#include <string>
Eugene Zelenko22886a22016-11-05 01:00:56 +000039#include <vector>
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000040
41using namespace llvm;
George Rimar652852c2016-04-16 10:10:32 +000042using namespace llvm::ELF;
Rui Ueyama1ebc8ed2016-02-12 21:47:28 +000043using namespace llvm::object;
George Rimare38cbab2016-09-26 19:22:50 +000044using namespace llvm::support::endian;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000045using namespace lld;
Rafael Espindolae0df00b2016-02-28 00:25:54 +000046using namespace lld::elf;
Rui Ueyamaf7c5fbb2015-09-30 17:23:26 +000047
Rui Ueyamaa34da932017-03-21 23:03:09 +000048LinkerScript *elf::Script;
49
Rafael Espindola72dc1952017-03-17 13:05:04 +000050uint64_t ExprValue::getValue() const {
51 if (Sec)
52 return Sec->getOffset(Val) + Sec->getOutputSection()->Addr;
53 return Val;
54}
55
Rafael Espindola7ba5f472017-03-17 14:55:36 +000056uint64_t ExprValue::getSecAddr() const {
57 if (Sec)
58 return Sec->getOffset(0) + Sec->getOutputSection()->Addr;
59 return 0;
60}
61
Meador Inge8f1f3c42017-01-09 18:36:57 +000062template <class ELFT> static SymbolBody *addRegular(SymbolAssignment *Cmd) {
Petr Hosek5e51f7d2017-02-21 22:32:51 +000063 Symbol *Sym;
Rafael Espindola3dabfc62016-10-31 13:14:53 +000064 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
Petr Hosek5e51f7d2017-02-21 22:32:51 +000065 std::tie(Sym, std::ignore) = Symtab<ELFT>::X->insert(
66 Cmd->Name, /*Type*/ 0, Visibility, /*CanOmitFromDynSym*/ false,
67 /*File*/ nullptr);
68 Sym->Binding = STB_GLOBAL;
Rafael Espindola72dc1952017-03-17 13:05:04 +000069 ExprValue Value = Cmd->Expression();
70 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
Rui Ueyama80474a22017-02-28 19:29:55 +000071 replaceBody<DefinedRegular>(Sym, Cmd->Name, /*IsLocal=*/false, Visibility,
Rafael Espindola5616adf2017-03-08 22:36:28 +000072 STT_NOTYPE, 0, 0, Sec, nullptr);
Meador Inge8f1f3c42017-01-09 18:36:57 +000073 return Sym->body();
Eugene Leviantceabe802016-08-11 07:56:43 +000074}
75
Rui Ueyamab8dd23f2017-03-21 23:02:51 +000076OutputSection *LinkerScript::getOutputSection(const Twine &Loc,
77 StringRef Name) {
George Rimar851dc1e2017-03-14 10:15:53 +000078 for (OutputSection *Sec : *OutputSections)
79 if (Sec->Name == Name)
80 return Sec;
81
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +000082 static OutputSection Dummy("", 0, 0);
Rafael Espindola72dc1952017-03-17 13:05:04 +000083 if (ErrorOnMissingSection)
84 error(Loc + ": undefined section " + Name);
Rui Ueyamaa08fa2e2017-04-05 00:42:45 +000085 return &Dummy;
George Rimar851dc1e2017-03-14 10:15:53 +000086}
87
George Rimard83ce1b2017-03-14 10:24:47 +000088// This function is essentially the same as getOutputSection(Name)->Size,
89// but it won't print out an error message if a given section is not found.
90//
91// Linker script does not create an output section if its content is empty.
92// We want to allow SIZEOF(.foo) where .foo is a section which happened to
93// be empty. That is why this function is different from getOutputSection().
Rui Ueyamab8dd23f2017-03-21 23:02:51 +000094uint64_t LinkerScript::getOutputSectionSize(StringRef Name) {
George Rimard83ce1b2017-03-14 10:24:47 +000095 for (OutputSection *Sec : *OutputSections)
96 if (Sec->Name == Name)
97 return Sec->Size;
98 return 0;
99}
100
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000101void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000102 uint64_t Val = E().getValue();
Rafael Espindola679828f2017-02-17 16:26:13 +0000103 if (Val < Dot) {
104 if (InSec)
George Rimar2ee2d2d2017-02-21 14:50:38 +0000105 error(Loc + ": unable to move location counter backward for: " +
106 CurOutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000107 else
George Rimar2ee2d2d2017-02-21 14:50:38 +0000108 error(Loc + ": unable to move location counter backward");
Rafael Espindola679828f2017-02-17 16:26:13 +0000109 }
110 Dot = Val;
111 // Update to location counter means update to section size.
112 if (InSec)
113 CurOutSec->Size = Dot - CurOutSec->Addr;
114}
115
George Rimarb2b70972017-02-07 10:23:28 +0000116// Sets value of a symbol. Two kinds of symbols are processed: synthetic
117// symbols, whose value is an offset from beginning of section and regular
118// symbols whose value is absolute.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000119void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000120 if (Cmd->Name == ".") {
George Rimar2ee2d2d2017-02-21 14:50:38 +0000121 setDot(Cmd->Expression, Cmd->Location, InSec);
Rafael Espindola4cd73522017-02-17 16:01:51 +0000122 return;
123 }
124
George Rimarb2b70972017-02-07 10:23:28 +0000125 if (!Cmd->Sym)
Meador Inge8f1f3c42017-01-09 18:36:57 +0000126 return;
127
Rafael Espindola5616adf2017-03-08 22:36:28 +0000128 auto *Sym = cast<DefinedRegular>(Cmd->Sym);
Rafael Espindola72dc1952017-03-17 13:05:04 +0000129 ExprValue V = Cmd->Expression();
130 if (V.isAbsolute()) {
131 Sym->Value = V.getValue();
132 } else {
133 Sym->Section = V.Sec;
134 if (Sym->Section->Flags & SHF_ALLOC)
135 Sym->Value = V.Val;
136 else
137 Sym->Value = V.getValue();
Meador Inge8f1f3c42017-01-09 18:36:57 +0000138 }
Eugene Leviantdb741e72016-09-07 07:08:43 +0000139}
Meador Inge8f1f3c42017-01-09 18:36:57 +0000140
George Rimara8dba482017-03-20 10:09:58 +0000141static SymbolBody *findSymbol(StringRef S) {
142 switch (Config->EKind) {
143 case ELF32LEKind:
144 return Symtab<ELF32LE>::X->find(S);
145 case ELF32BEKind:
146 return Symtab<ELF32BE>::X->find(S);
147 case ELF64LEKind:
148 return Symtab<ELF64LE>::X->find(S);
149 case ELF64BEKind:
150 return Symtab<ELF64BE>::X->find(S);
151 default:
152 llvm_unreachable("unknown Config->EKind");
153 }
154}
155
156static SymbolBody *addRegularSymbol(SymbolAssignment *Cmd) {
157 switch (Config->EKind) {
158 case ELF32LEKind:
159 return addRegular<ELF32LE>(Cmd);
160 case ELF32BEKind:
161 return addRegular<ELF32BE>(Cmd);
162 case ELF64LEKind:
163 return addRegular<ELF64LE>(Cmd);
164 case ELF64BEKind:
165 return addRegular<ELF64BE>(Cmd);
166 default:
167 llvm_unreachable("unknown Config->EKind");
168 }
169}
170
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000171void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000172 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000173 return;
174
175 // If a symbol was in PROVIDE(), we need to define it only when
176 // it is a referenced undefined symbol.
George Rimara8dba482017-03-20 10:09:58 +0000177 SymbolBody *B = findSymbol(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000178 if (Cmd->Provide && (!B || B->isDefined()))
179 return;
180
George Rimara8dba482017-03-20 10:09:58 +0000181 Cmd->Sym = addRegularSymbol(Cmd);
Eugene Leviantceabe802016-08-11 07:56:43 +0000182}
183
George Rimar076fe152016-07-21 06:43:01 +0000184bool SymbolAssignment::classof(const BaseCommand *C) {
185 return C->Kind == AssignmentKind;
186}
187
188bool OutputSectionCommand::classof(const BaseCommand *C) {
189 return C->Kind == OutputSectionKind;
190}
191
George Rimareea31142016-07-21 14:26:59 +0000192bool InputSectionDescription::classof(const BaseCommand *C) {
193 return C->Kind == InputSectionKind;
194}
195
George Rimareefa7582016-08-04 09:29:31 +0000196bool AssertCommand::classof(const BaseCommand *C) {
197 return C->Kind == AssertKind;
198}
199
George Rimare38cbab2016-09-26 19:22:50 +0000200bool BytesDataCommand::classof(const BaseCommand *C) {
201 return C->Kind == BytesDataKind;
202}
203
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000204static StringRef basename(InputSectionBase *S) {
205 if (S->File)
206 return sys::path::filename(S->File->getName());
Rui Ueyamae0be2902016-11-21 02:10:12 +0000207 return "";
208}
209
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000210bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyamae0be2902016-11-21 02:10:12 +0000211 for (InputSectionDescription *ID : Opt.KeptSections)
212 if (ID->FilePat.match(basename(S)))
213 for (SectionPattern &P : ID->SectionPatterns)
214 if (P.SectionPat.match(S->Name))
215 return true;
George Rimareea31142016-07-21 14:26:59 +0000216 return false;
217}
218
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000219// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000220static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000221getComparator(SortSectionPolicy K) {
222 switch (K) {
223 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000224 return [](InputSectionBase *A, InputSectionBase *B) {
225 // ">" is not a mistake. Sections with larger alignments are placed
226 // before sections with smaller alignments in order to reduce the
227 // amount of padding necessary. This is compatible with GNU.
228 return A->Alignment > B->Alignment;
229 };
George Rimarbe394db2016-09-16 20:21:55 +0000230 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000231 return [](InputSectionBase *A, InputSectionBase *B) {
232 return A->Name < B->Name;
233 };
George Rimarbe394db2016-09-16 20:21:55 +0000234 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000235 return [](InputSectionBase *A, InputSectionBase *B) {
236 return getPriority(A->Name) < getPriority(B->Name);
237 };
George Rimarbe394db2016-09-16 20:21:55 +0000238 default:
239 llvm_unreachable("unknown sort policy");
240 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000241}
George Rimar0702c4e2016-07-29 15:32:46 +0000242
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000243// A helper function for the SORT() command.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000244static bool matchConstraints(ArrayRef<InputSectionBase *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000245 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000246 if (Kind == ConstraintKind::NoConstraint)
247 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000248
249 bool IsRW = llvm::any_of(Sections, [](InputSectionBase *Sec) {
250 return static_cast<InputSectionBase *>(Sec)->Flags & SHF_WRITE;
George Rimar06ae6832016-08-12 09:07:57 +0000251 });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000252
Rafael Espindolae746e522016-09-21 18:33:44 +0000253 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
254 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000255}
256
Rafael Espindolac404d502017-02-23 02:32:18 +0000257static void sortSections(InputSectionBase **Begin, InputSectionBase **End,
Rui Ueyamaee924702016-09-20 19:42:41 +0000258 SortSectionPolicy K) {
259 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
George Rimar07171f22016-09-21 15:56:44 +0000260 std::stable_sort(Begin, End, getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000261}
262
Rafael Espindolad3190792016-09-16 15:10:23 +0000263// Compute and remember which sections the InputSectionDescription matches.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000264std::vector<InputSectionBase *>
265LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
266 std::vector<InputSectionBase *> Ret;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000267
Rui Ueyama72e107f2017-04-05 02:05:48 +0000268 // Collects all sections that satisfy constraints of Cmd.
269 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
270 size_t SizeBefore = Ret.size();
271
272 for (InputSectionBase *Sec : InputSections) {
273 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000274 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000275
Rafael Espindola908a3d32017-02-16 14:36:09 +0000276 // For -emit-relocs we have to ignore entries like
277 // .rela.dyn : { *(.rela.data) }
278 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000279 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000280 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000281
Rui Ueyama72e107f2017-04-05 02:05:48 +0000282 StringRef Filename = basename(Sec);
283 if (!Cmd->FilePat.match(Filename) ||
284 Pat.ExcludedFilePat.match(Filename) ||
285 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000286 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000287
288 Ret.push_back(Sec);
289 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000290 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000291
George Rimar07171f22016-09-21 15:56:44 +0000292 // Sort sections as instructed by SORT-family commands and --sort-section
293 // option. Because SORT-family commands can be nested at most two depth
294 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
295 // line option is respected even if a SORT command is given, the exact
296 // behavior we have here is a bit complicated. Here are the rules.
297 //
298 // 1. If two SORT commands are given, --sort-section is ignored.
299 // 2. If one SORT command is given, and if it is not SORT_NONE,
300 // --sort-section is handled as an inner SORT command.
301 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
302 // 4. If no SORT command is given, sort according to --sort-section.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000303 InputSectionBase **Begin = Ret.data() + SizeBefore;
304 InputSectionBase **End = Ret.data() + Ret.size();
George Rimar07171f22016-09-21 15:56:44 +0000305 if (Pat.SortOuter != SortSectionPolicy::None) {
306 if (Pat.SortInner == SortSectionPolicy::Default)
307 sortSections(Begin, End, Config->SortSection);
308 else
309 sortSections(Begin, End, Pat.SortInner);
310 sortSections(Begin, End, Pat.SortOuter);
311 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000312 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000313 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000314}
315
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000316void LinkerScript::discard(ArrayRef<InputSectionBase *> V) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000317 for (InputSectionBase *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000318 S->Live = false;
George Rimar503206c2017-03-15 15:42:44 +0000319 if (S == InX::ShStrTab)
Rafael Espindolaecbfd872017-02-17 17:35:07 +0000320 error("discarding .shstrtab section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000321 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000322 }
323}
324
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000325std::vector<InputSectionBase *>
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000326LinkerScript::createInputSectionList(OutputSectionCommand &OutCmd) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000327 std::vector<InputSectionBase *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000328
Rui Ueyama8f99f732017-04-05 03:20:42 +0000329 for (BaseCommand *Base : OutCmd.Commands) {
330 auto *Cmd = dyn_cast<InputSectionDescription>(Base);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000331 if (!Cmd)
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000332 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000333
334 Cmd->Sections = computeInputSections(Cmd);
Rafael Espindolac404d502017-02-23 02:32:18 +0000335 for (InputSectionBase *S : Cmd->Sections)
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000336 Ret.push_back(static_cast<InputSectionBase *>(S));
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000337 }
Rafael Espindolae71a3f8a2016-09-16 20:34:02 +0000338
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000339 return Ret;
340}
341
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000342void LinkerScript::processCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000343 // A symbol can be assigned before any section is mentioned in the linker
344 // script. In an DSO, the symbol values are addresses, so the only important
345 // section values are:
346 // * SHN_UNDEF
347 // * SHN_ABS
348 // * Any value meaning a regular section.
349 // To handle that, create a dummy aether section that fills the void before
350 // the linker scripts switches to another section. It has an index of one
351 // which will map to whatever the first actual section is.
352 Aether = make<OutputSection>("", 0, SHF_ALLOC);
353 Aether->SectionIndex = 1;
354 CurOutSec = Aether;
Rafael Espindola49592cf2017-03-20 14:33:33 +0000355 Dot = 0;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000356
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000357 for (size_t I = 0; I < Opt.Commands.size(); ++I) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000358 // Handle symbol assignments outside of any output section.
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000359 if (auto *Cmd = dyn_cast<SymbolAssignment>(Opt.Commands[I])) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000360 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000361 continue;
362 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000363
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000364 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I])) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000365 std::vector<InputSectionBase *> V = createInputSectionList(*Cmd);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000366
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000367 // The output section name `/DISCARD/' is special.
368 // Any input section assigned to it is discarded.
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000369 if (Cmd->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000370 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000371 continue;
372 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000373
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000374 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
375 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
376 // sections satisfy a given constraint. If not, a directive is handled
George Rimar07d7c422017-04-05 09:19:29 +0000377 // as if it wasn't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000378 //
379 // Because we'll iterate over Commands many more times, the easiest
George Rimar07d7c422017-04-05 09:19:29 +0000380 // way to "make it as if it wasn't present" is to just remove it.
George Rimarf7f0d082017-03-14 11:23:33 +0000381 if (!matchConstraints(V, Cmd->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000382 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000383 S->Assigned = false;
Rui Ueyama92a5ba62017-04-05 16:07:44 +0000384 Opt.Commands.erase(Opt.Commands.begin() + I);
George Rimar07d7c422017-04-05 09:19:29 +0000385 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000386 continue;
387 }
388
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000389 // A directive may contain symbol definitions like this:
390 // ".foo : { ...; bar = .; }". Handle them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000391 for (BaseCommand *Base : Cmd->Commands)
392 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000393 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000394
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000395 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
396 // is given, input sections are aligned to that value, whether the
397 // given value is larger or smaller than the original section alignment.
398 if (Cmd->SubalignExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000399 uint32_t Subalign = Cmd->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000400 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000401 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000402 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000403
404 // Add input sections to an output section.
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000405 for (InputSectionBase *S : V)
George Rimare21c3af2017-03-14 09:30:25 +0000406 Factory.addInputSec(S, Cmd->Name);
Eugene Leviantceabe802016-08-11 07:56:43 +0000407 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000408 }
Rafael Espindola5616adf2017-03-08 22:36:28 +0000409 CurOutSec = nullptr;
Eugene Leviant20d03192016-09-16 15:30:47 +0000410}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000411
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000412// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000413void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama536a2672017-02-27 02:32:08 +0000414 for (InputSectionBase *S : InputSections)
Rafael Espindola8f9026b2016-11-08 18:23:02 +0000415 if (S->Live && !S->OutSec)
George Rimare21c3af2017-03-14 09:30:25 +0000416 Factory.addInputSec(S, getOutputSectionName(S->Name));
Eugene Leviante63d81b2016-07-20 14:43:20 +0000417}
418
George Rimarf7f0d082017-03-14 11:23:33 +0000419static bool isTbss(OutputSection *Sec) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000420 return (Sec->Flags & SHF_TLS) && Sec->Type == SHT_NOBITS;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000421}
422
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000423void LinkerScript::output(InputSection *S) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000424 if (!AlreadyOutputIS.insert(S).second)
425 return;
George Rimarf7f0d082017-03-14 11:23:33 +0000426 bool IsTbss = isTbss(CurOutSec);
Eugene Leviant20889c52016-08-31 08:13:33 +0000427
George Rimar0c1c8082017-03-14 10:00:19 +0000428 uint64_t Pos = IsTbss ? Dot + ThreadBssOffset : Dot;
Rafael Espindolad3190792016-09-16 15:10:23 +0000429 Pos = alignTo(Pos, S->Alignment);
Rafael Espindola04a2e342016-11-09 01:42:41 +0000430 S->OutSecOff = Pos - CurOutSec->Addr;
Rafael Espindola76b6bd32017-03-08 15:44:30 +0000431 Pos += S->getSize();
Rafael Espindolad3190792016-09-16 15:10:23 +0000432
433 // Update output section size after adding each section. This is so that
434 // SIZEOF works correctly in the case below:
435 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rafael Espindola04a2e342016-11-09 01:42:41 +0000436 CurOutSec->Size = Pos - CurOutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000437
Meador Ingeb8897442017-01-24 02:34:00 +0000438 // If there is a memory region associated with this input section, then
439 // place the section in that region and update the region index.
440 if (CurMemRegion) {
441 CurMemRegion->Offset += CurOutSec->Size;
442 uint64_t CurSize = CurMemRegion->Offset - CurMemRegion->Origin;
443 if (CurSize > CurMemRegion->Length) {
444 uint64_t OverflowAmt = CurSize - CurMemRegion->Length;
445 error("section '" + CurOutSec->Name + "' will not fit in region '" +
446 CurMemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
447 " bytes");
448 }
449 }
450
Rafael Espindola7252ae52016-09-22 12:00:08 +0000451 if (IsTbss)
452 ThreadBssOffset = Pos - Dot;
453 else
Rafael Espindolad3190792016-09-16 15:10:23 +0000454 Dot = Pos;
455}
456
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000457void LinkerScript::flush() {
Rafael Espindolabd12e2a2017-03-01 14:12:21 +0000458 assert(CurOutSec);
459 if (!AlreadyOutputOS.insert(CurOutSec).second)
Rafael Espindola65499b92016-09-23 20:10:47 +0000460 return;
Rafael Espindola24e6f362017-02-24 15:07:30 +0000461 for (InputSection *I : CurOutSec->Sections)
462 output(I);
Eugene Leviant20889c52016-08-31 08:13:33 +0000463}
464
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000465void LinkerScript::switchTo(OutputSection *Sec) {
Rafael Espindolad3190792016-09-16 15:10:23 +0000466 if (CurOutSec == Sec)
467 return;
468 if (AlreadyOutputOS.count(Sec))
469 return;
470
Rafael Espindolad3190792016-09-16 15:10:23 +0000471 CurOutSec = Sec;
472
Rafael Espindola37707632017-03-07 14:55:52 +0000473 Dot = alignTo(Dot, CurOutSec->Alignment);
George Rimarf7f0d082017-03-14 11:23:33 +0000474 CurOutSec->Addr = isTbss(CurOutSec) ? Dot + ThreadBssOffset : Dot;
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000475
476 // If neither AT nor AT> is specified for an allocatable section, the linker
477 // will set the LMA such that the difference between VMA and LMA for the
478 // section is the same as the preceding output section in the same region
479 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
George Rimar21467872017-02-23 07:57:55 +0000480 if (LMAOffset)
Rafael Espindola29c1afb2017-02-24 14:34:12 +0000481 CurOutSec->LMAOffset = LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000482}
483
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000484void LinkerScript::process(BaseCommand &Base) {
Rui Ueyama2e081a42017-04-05 03:18:46 +0000485 // This handles the assignments to symbol or to the dot.
486 if (auto *Cmd = dyn_cast<SymbolAssignment>(&Base)) {
487 assignSymbol(Cmd, true);
Eugene Leviantceabe802016-08-11 07:56:43 +0000488 return;
Rui Ueyama2de509c2016-08-12 00:55:08 +0000489 }
George Rimare38cbab2016-09-26 19:22:50 +0000490
491 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyama2e081a42017-04-05 03:18:46 +0000492 if (auto *Cmd = dyn_cast<BytesDataCommand>(&Base)) {
493 Cmd->Offset = Dot - CurOutSec->Addr;
494 Dot += Cmd->Size;
Rafael Espindola04a2e342016-11-09 01:42:41 +0000495 CurOutSec->Size = Dot - CurOutSec->Addr;
George Rimare38cbab2016-09-26 19:22:50 +0000496 return;
497 }
498
Rui Ueyama2e081a42017-04-05 03:18:46 +0000499 // Handle ASSERT().
500 if (auto *Cmd = dyn_cast<AssertCommand>(&Base)) {
501 Cmd->Expression();
Meador Ingeb2d99d62016-11-22 18:01:50 +0000502 return;
503 }
504
Rui Ueyama2e081a42017-04-05 03:18:46 +0000505 // Handle a single input section description command.
506 // It calculates and assigns the offsets for each section and also
George Rimare38cbab2016-09-26 19:22:50 +0000507 // updates the output section size.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000508 auto &Cmd = cast<InputSectionDescription>(Base);
509 for (InputSectionBase *Sec : Cmd.Sections) {
George Rimar3fb5a6d2016-11-29 16:05:27 +0000510 // We tentatively added all synthetic sections at the beginning and removed
511 // empty ones afterwards (because there is no way to know whether they were
512 // going be empty or not other than actually running linker scripts.)
513 // We need to ignore remains of empty sections.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000514 if (auto *S = dyn_cast<SyntheticSection>(Sec))
515 if (S->empty())
George Rimar3fb5a6d2016-11-29 16:05:27 +0000516 continue;
517
Rui Ueyama2e081a42017-04-05 03:18:46 +0000518 if (!Sec->Live)
George Rimar78ef6452017-02-21 15:46:43 +0000519 continue;
Rui Ueyama2e081a42017-04-05 03:18:46 +0000520 assert(CurOutSec == Sec->OutSec || AlreadyOutputOS.count(Sec->OutSec));
521 output(cast<InputSection>(Sec));
Eugene Leviantceabe802016-08-11 07:56:43 +0000522 }
523}
524
Rafael Espindola24e6f362017-02-24 15:07:30 +0000525static OutputSection *
526findSection(StringRef Name, const std::vector<OutputSection *> &Sections) {
Rui Ueyama0b2381e2017-04-05 03:19:06 +0000527 for (OutputSection *Sec : Sections)
528 if (Sec->Name == Name)
529 return Sec;
530 return nullptr;
George Rimar8f66df92016-08-12 20:38:20 +0000531}
532
Meador Ingeb8897442017-01-24 02:34:00 +0000533// This function searches for a memory region to place the given output
534// section in. If found, a pointer to the appropriate memory region is
535// returned. Otherwise, a nullptr is returned.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000536MemoryRegion *LinkerScript::findMemoryRegion(OutputSectionCommand *Cmd,
537 OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000538 // If a memory region name was specified in the output section command,
539 // then try to find that region first.
540 if (!Cmd->MemoryRegionName.empty()) {
541 auto It = Opt.MemoryRegions.find(Cmd->MemoryRegionName);
542 if (It != Opt.MemoryRegions.end())
543 return &It->second;
544 error("memory region '" + Cmd->MemoryRegionName + "' not declared");
545 return nullptr;
546 }
547
Rui Ueyamad7c54002017-04-05 03:19:43 +0000548 // If at least one memory region is defined, all sections must
549 // belong to some memory region. Otherwise, we don't need to do
550 // anything for memory regions.
Rui Ueyamacc400cc2017-04-05 03:19:24 +0000551 if (Opt.MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000552 return nullptr;
553
554 // See if a region can be found by matching section flags.
Rui Ueyama2e081a42017-04-05 03:18:46 +0000555 for (auto &Pair : Opt.MemoryRegions) {
556 MemoryRegion &M = Pair.second;
557 if ((M.Flags & Sec->Flags) && (M.NegFlags & Sec->Flags) == 0)
558 return &M;
Meador Ingeb8897442017-01-24 02:34:00 +0000559 }
560
561 // Otherwise, no suitable region was found.
562 if (Sec->Flags & SHF_ALLOC)
563 error("no memory region specified for section '" + Sec->Name + "'");
564 return nullptr;
565}
566
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000567// This function assigns offsets to input sections and an output section
568// for a single sections command (e.g. ".text { *(.text); }").
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000569void LinkerScript::assignOffsets(OutputSectionCommand *Cmd) {
George Rimar23e6a022017-03-14 11:31:28 +0000570 OutputSection *Sec = findSection(Cmd->Name, *OutputSections);
Rafael Espindola2b074552017-02-03 22:27:05 +0000571 if (!Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000572 return;
Meador Ingeb8897442017-01-24 02:34:00 +0000573
Rui Ueyamacba41012017-04-05 03:20:03 +0000574 if (Cmd->AddrExpr && (Sec->Flags & SHF_ALLOC))
Rui Ueyamad379f732017-04-05 03:20:22 +0000575 setDot(Cmd->AddrExpr, Cmd->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000576
Eugene Leviant5784e962017-03-14 08:57:09 +0000577 if (Cmd->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000578 uint64_t D = Dot;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000579 LMAOffset = [=] { return Cmd->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000580 }
581
Petr Hosek165088a2017-02-07 23:42:31 +0000582 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
583 if (Cmd->AlignExpr)
Rafael Espindola72dc1952017-03-17 13:05:04 +0000584 Sec->updateAlignment(Cmd->AlignExpr().getValue());
Petr Hosek165088a2017-02-07 23:42:31 +0000585
Meador Ingeb8897442017-01-24 02:34:00 +0000586 // Try and find an appropriate memory region to assign offsets in.
587 CurMemRegion = findMemoryRegion(Cmd, Sec);
588 if (CurMemRegion)
589 Dot = CurMemRegion->Offset;
590 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000591
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000592 // flush() may add orphan sections, so the order of flush() and
593 // symbol assignments is important. We want to call flush() first so
594 // that symbols pointing the end of the current section points to
595 // the location after orphan sections.
596 auto Mid =
Rui Ueyama8f99f732017-04-05 03:20:42 +0000597 std::find_if(Cmd->Commands.rbegin(), Cmd->Commands.rend(),
598 [](BaseCommand *Cmd) { return !isa<SymbolAssignment>(Cmd); })
599 .base();
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000600 for (auto I = Cmd->Commands.begin(); I != Mid; ++I)
Rafael Espindolad3190792016-09-16 15:10:23 +0000601 process(**I);
Rafael Espindola65499b92016-09-23 20:10:47 +0000602 flush();
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000603 for (auto I = Mid, E = Cmd->Commands.end(); I != E; ++I)
604 process(**I);
Rafael Espindolad3190792016-09-16 15:10:23 +0000605}
606
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000607void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000608 // It is common practice to use very generic linker scripts. So for any
609 // given run some of the output sections in the script will be empty.
610 // We could create corresponding empty output sections, but that would
611 // clutter the output.
612 // We instead remove trivially empty sections. The bfd linker seems even
613 // more aggressive at removing them.
614 auto Pos = std::remove_if(
Rui Ueyama8f99f732017-04-05 03:20:42 +0000615 Opt.Commands.begin(), Opt.Commands.end(), [&](BaseCommand *Base) {
616 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
George Rimar23e6a022017-03-14 11:31:28 +0000617 return !findSection(Cmd->Name, *OutputSections);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000618 return false;
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000619 });
620 Opt.Commands.erase(Pos, Opt.Commands.end());
Rafael Espindola07fe6122016-11-14 14:23:35 +0000621}
622
Rafael Espindola6a537372016-11-14 14:33:49 +0000623static bool isAllSectionDescription(const OutputSectionCommand &Cmd) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000624 for (BaseCommand *Base : Cmd.Commands)
625 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000626 return false;
627 return true;
628}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000629
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000630void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000631 // If the output section contains only symbol assignments, create a
632 // corresponding output section. The bfd linker seems to only create them if
633 // '.' is assigned to, but creating these section should not have any bad
634 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000635 uint64_t Flags = SHF_ALLOC;
Rafael Espindolaf93b8c22016-11-26 06:55:35 +0000636 uint32_t Type = SHT_NOBITS;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000637 for (BaseCommand *Base : Opt.Commands) {
638 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000639 if (!Cmd)
640 continue;
George Rimar23e6a022017-03-14 11:31:28 +0000641 if (OutputSection *Sec = findSection(Cmd->Name, *OutputSections)) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000642 Flags = Sec->Flags;
643 Type = Sec->Type;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000644 continue;
645 }
646
Rafael Espindola6a537372016-11-14 14:33:49 +0000647 if (isAllSectionDescription(*Cmd))
648 continue;
649
Rafael Espindola24e6f362017-02-24 15:07:30 +0000650 auto *OutSec = make<OutputSection>(Cmd->Name, Type, Flags);
Rafael Espindola9546fff2016-09-22 14:40:50 +0000651 OutputSections->push_back(OutSec);
652 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000653}
654
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000655void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000656 placeOrphanSections();
657
658 // If output section command doesn't specify any segments,
659 // and we haven't previously assigned any section to segment,
660 // then we simply assign section to the very first load segment.
661 // Below is an example of such linker script:
662 // PHDRS { seg PT_LOAD; }
663 // SECTIONS { .aaa : { *(.aaa) } }
664 std::vector<StringRef> DefPhdrs;
665 auto FirstPtLoad =
666 std::find_if(Opt.PhdrsCommands.begin(), Opt.PhdrsCommands.end(),
667 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
668 if (FirstPtLoad != Opt.PhdrsCommands.end())
669 DefPhdrs.push_back(FirstPtLoad->Name);
670
671 // Walk the commands and propagate the program headers to commands that don't
672 // explicitly specify them.
Rui Ueyama8f99f732017-04-05 03:20:42 +0000673 for (BaseCommand *Base : Opt.Commands) {
674 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000675 if (!Cmd)
676 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000677
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000678 if (Cmd->Phdrs.empty())
679 Cmd->Phdrs = DefPhdrs;
680 else
681 DefPhdrs = Cmd->Phdrs;
682 }
Rafael Espindola6a537372016-11-14 14:33:49 +0000683
684 removeEmptyCommands();
Rafael Espindola9546fff2016-09-22 14:40:50 +0000685}
686
Rafael Espindola15c57952016-09-22 18:05:49 +0000687// When placing orphan sections, we want to place them after symbol assignments
688// so that an orphan after
689// begin_foo = .;
690// foo : { *(foo) }
691// end_foo = .;
692// doesn't break the intended meaning of the begin/end symbols.
693// We don't want to go over sections since Writer<ELFT>::sortSections is the
694// one in charge of deciding the order of the sections.
695// We don't want to go over alignments, since doing so in
696// rx_sec : { *(rx_sec) }
697// . = ALIGN(0x1000);
698// /* The RW PT_LOAD starts here*/
699// rw_sec : { *(rw_sec) }
700// would mean that the RW PT_LOAD would become unaligned.
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000701static bool shouldSkip(BaseCommand *Cmd) {
Rafael Espindola15c57952016-09-22 18:05:49 +0000702 if (isa<OutputSectionCommand>(Cmd))
703 return false;
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000704 if (auto *Assign = dyn_cast<SymbolAssignment>(Cmd))
705 return Assign->Name != ".";
706 return true;
Rafael Espindola15c57952016-09-22 18:05:49 +0000707}
708
Rui Ueyama6697ec22017-02-02 23:26:12 +0000709// Orphan sections are sections present in the input files which are
710// not explicitly placed into the output file by the linker script.
711//
712// When the control reaches this function, Opt.Commands contains
713// output section commands for non-orphan sections only. This function
Rui Ueyama81cb7102017-03-24 00:15:57 +0000714// adds new elements for orphan sections so that all sections are
715// explicitly handled by Opt.Commands.
Rui Ueyama6697ec22017-02-02 23:26:12 +0000716//
717// Writer<ELFT>::sortSections has already sorted output sections.
718// What we need to do is to scan OutputSections vector and
719// Opt.Commands in parallel to find orphan sections. If there is an
720// output section that doesn't have a corresponding entry in
721// Opt.Commands, we will insert a new entry to Opt.Commands.
722//
723// There is some ambiguity as to where exactly a new entry should be
724// inserted, because Opt.Commands contains not only output section
Rui Ueyama81cb7102017-03-24 00:15:57 +0000725// commands but also other types of commands such as symbol assignment
Rui Ueyama6697ec22017-02-02 23:26:12 +0000726// expressions. There's no correct answer here due to the lack of the
727// formal specification of the linker script. We use heuristics to
728// determine whether a new output command should be added before or
729// after another commands. For the details, look at shouldSkip
730// function.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000731void LinkerScript::placeOrphanSections() {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000732 // The OutputSections are already in the correct order.
733 // This loops creates or moves commands as needed so that they are in the
734 // correct order.
735 int CmdIndex = 0;
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000736
737 // As a horrible special case, skip the first . assignment if it is before any
738 // section. We do this because it is common to set a load address by starting
739 // the script with ". = 0xabcd" and the expectation is that every section is
740 // after that.
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000741 auto FirstSectionOrDotAssignment =
742 std::find_if(Opt.Commands.begin(), Opt.Commands.end(),
743 [](BaseCommand *Cmd) { return !shouldSkip(Cmd); });
Rafael Espindola5fcc99c2016-11-27 09:44:45 +0000744 if (FirstSectionOrDotAssignment != Opt.Commands.end()) {
745 CmdIndex = FirstSectionOrDotAssignment - Opt.Commands.begin();
746 if (isa<SymbolAssignment>(**FirstSectionOrDotAssignment))
747 ++CmdIndex;
748 }
749
Rafael Espindola24e6f362017-02-24 15:07:30 +0000750 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola40849412017-02-24 14:28:00 +0000751 StringRef Name = Sec->Name;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000752
753 // Find the last spot where we can insert a command and still get the
Rafael Espindola15c57952016-09-22 18:05:49 +0000754 // correct result.
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000755 auto CmdIter = Opt.Commands.begin() + CmdIndex;
756 auto E = Opt.Commands.end();
Rui Ueyama4e1e88e2017-04-05 03:52:28 +0000757 while (CmdIter != E && shouldSkip(*CmdIter)) {
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000758 ++CmdIter;
759 ++CmdIndex;
760 }
761
Rui Ueyama8f99f732017-04-05 03:20:42 +0000762 auto Pos = std::find_if(CmdIter, E, [&](BaseCommand *Base) {
763 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
764 return Cmd && Cmd->Name == Name;
765 });
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000766 if (Pos == E) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000767 Opt.Commands.insert(CmdIter, make<OutputSectionCommand>(Name));
Rafael Espindola15c57952016-09-22 18:05:49 +0000768 ++CmdIndex;
769 continue;
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000770 }
Rafael Espindola15c57952016-09-22 18:05:49 +0000771
772 // Continue from where we found it.
773 CmdIndex = (Pos - Opt.Commands.begin()) + 1;
George Rimar652852c2016-04-16 10:10:32 +0000774 }
Rafael Espindola337f9032016-11-14 14:13:32 +0000775}
776
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000777void LinkerScript::processNonSectionCommands() {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000778 for (BaseCommand *Base : Opt.Commands) {
779 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base))
Rui Ueyamad379f732017-04-05 03:20:22 +0000780 assignSymbol(Cmd, false);
Rui Ueyama8f99f732017-04-05 03:20:42 +0000781 else if (auto *Cmd = dyn_cast<AssertCommand>(Base))
Petr Hosek02ad5162017-03-15 03:33:23 +0000782 Cmd->Expression();
783 }
784}
785
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000786void LinkerScript::assignAddresses(std::vector<PhdrEntry> &Phdrs) {
Rui Ueyama7c18c282016-04-18 21:00:40 +0000787 // Assign addresses as instructed by linker script SECTIONS sub-commands.
Rafael Espindolabe607332016-09-30 00:16:11 +0000788 Dot = 0;
Rafael Espindola72dc1952017-03-17 13:05:04 +0000789 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000790 switchTo(Aether);
791
Rui Ueyama8f99f732017-04-05 03:20:42 +0000792 for (BaseCommand *Base : Opt.Commands) {
793 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
Rui Ueyamad379f732017-04-05 03:20:22 +0000794 assignSymbol(Cmd, false);
George Rimar652852c2016-04-16 10:10:32 +0000795 continue;
796 }
797
Rui Ueyama8f99f732017-04-05 03:20:42 +0000798 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000799 Cmd->Expression();
George Rimareefa7582016-08-04 09:29:31 +0000800 continue;
801 }
802
Rui Ueyama8f99f732017-04-05 03:20:42 +0000803 auto *Cmd = cast<OutputSectionCommand>(Base);
Rafael Espindolad3190792016-09-16 15:10:23 +0000804 assignOffsets(Cmd);
George Rimar652852c2016-04-16 10:10:32 +0000805 }
Rui Ueyama52c4e172016-07-01 10:42:25 +0000806
George Rimar0c1c8082017-03-14 10:00:19 +0000807 uint64_t MinVA = std::numeric_limits<uint64_t>::max();
Rafael Espindola24e6f362017-02-24 15:07:30 +0000808 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000809 if (Sec->Flags & SHF_ALLOC)
Rafael Espindolae08e78d2016-11-09 23:23:45 +0000810 MinVA = std::min<uint64_t>(MinVA, Sec->Addr);
Rafael Espindolaea590d92017-02-08 15:19:03 +0000811 else
812 Sec->Addr = 0;
813 }
Rafael Espindolaaab6d5c2016-09-16 21:29:07 +0000814
George Rimar2d262102017-03-14 09:03:53 +0000815 allocateHeaders(Phdrs, *OutputSections, MinVA);
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.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000819std::vector<PhdrEntry> LinkerScript::createPhdrs() {
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000820 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) {
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000825 Ret.emplace_back(Cmd.Type, Cmd.Flags == UINT_MAX ? PF_R : Cmd.Flags);
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000826 PhdrEntry &Phdr = Ret.back();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000827
828 if (Cmd.HasFilehdr)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000829 Phdr.add(Out::ElfHeader);
Eugene Leviantbbe38602016-07-19 09:25:43 +0000830 if (Cmd.HasPhdrs)
Rui Ueyama9d1bacb12017-02-27 02:31:26 +0000831 Phdr.add(Out::ProgramHeaders);
Eugene Leviant56b21c82016-09-09 09:46:16 +0000832
833 if (Cmd.LMAExpr) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000834 Phdr.p_paddr = Cmd.LMAExpr().getValue();
Eugene Leviant56b21c82016-09-09 09:46:16 +0000835 Phdr.HasLMA = true;
836 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000837 }
838
Rui Ueyama464daad2016-08-22 04:55:20 +0000839 // Add output sections to program headers.
Rafael Espindola24e6f362017-02-24 15:07:30 +0000840 for (OutputSection *Sec : *OutputSections) {
Rafael Espindola04a2e342016-11-09 01:42:41 +0000841 if (!(Sec->Flags & SHF_ALLOC))
Eugene Leviantbbe38602016-07-19 09:25:43 +0000842 break;
843
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000844 // Assign headers specified by linker script
Rafael Espindola40849412017-02-24 14:28:00 +0000845 for (size_t Id : getPhdrIndices(Sec->Name)) {
Eugene Leviantce30b1c2016-10-19 15:04:49 +0000846 Ret[Id].add(Sec);
847 if (Opt.PhdrsCommands[Id].Flags == UINT_MAX)
Rafael Espindola17cb7c02016-12-19 17:01:01 +0000848 Ret[Id].p_flags |= Sec->getPhdrFlags();
Eugene Leviantbbe38602016-07-19 09:25:43 +0000849 }
Eugene Leviantbbe38602016-07-19 09:25:43 +0000850 }
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000851 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000852}
853
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000854bool LinkerScript::ignoreInterpSection() {
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000855 // Ignore .interp section in case we have PHDRS specification
856 // and PT_INTERP isn't listed.
Rui Ueyamae31d9882017-04-05 05:06:17 +0000857 if (Opt.PhdrsCommands.empty())
858 return false;
859 for (PhdrsCommand &Cmd : Opt.PhdrsCommands)
860 if (Cmd.Type == PT_INTERP)
861 return false;
862 return true;
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000863}
864
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000865uint32_t LinkerScript::getFiller(StringRef Name) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000866 for (BaseCommand *Base : Opt.Commands)
867 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
George Rimarf6c3cce2016-07-21 07:48:54 +0000868 if (Cmd->Name == Name)
869 return Cmd->Filler;
Rui Ueyama16068ae2016-11-19 18:05:56 +0000870 return 0;
George Rimare2ee72b2016-02-26 14:48:31 +0000871}
872
George Rimare38cbab2016-09-26 19:22:50 +0000873static void writeInt(uint8_t *Buf, uint64_t Data, uint64_t Size) {
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000874 if (Size == 1)
875 *Buf = Data;
876 else if (Size == 2)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000877 write16(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000878 else if (Size == 4)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000879 write32(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000880 else if (Size == 8)
Rui Ueyamaf93ed4d2017-03-21 21:40:08 +0000881 write64(Buf, Data, Config->Endianness);
Rui Ueyamaf62d2602017-04-05 05:06:37 +0000882 else
George Rimare38cbab2016-09-26 19:22:50 +0000883 llvm_unreachable("unsupported Size argument");
George Rimare38cbab2016-09-26 19:22:50 +0000884}
885
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000886void LinkerScript::writeDataBytes(StringRef Name, uint8_t *Buf) {
George Rimare38cbab2016-09-26 19:22:50 +0000887 int I = getSectionIndex(Name);
888 if (I == INT_MAX)
889 return;
890
Rui Ueyama8f99f732017-04-05 03:20:42 +0000891 auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]);
892 for (BaseCommand *Base : Cmd->Commands)
893 if (auto *Data = dyn_cast<BytesDataCommand>(Base))
George Rimara8dba482017-03-20 10:09:58 +0000894 writeInt(Buf + Data->Offset, Data->Expression().getValue(), Data->Size);
George Rimare38cbab2016-09-26 19:22:50 +0000895}
896
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000897bool LinkerScript::hasLMA(StringRef Name) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000898 for (BaseCommand *Base : Opt.Commands)
899 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Base))
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000900 if (Cmd->LMAExpr && Cmd->Name == Name)
901 return true;
902 return false;
George Rimar8ceadb32016-08-17 07:44:19 +0000903}
904
Rui Ueyamac3e2a4b2016-04-21 20:30:00 +0000905// Returns the index of the given section name in linker script
906// SECTIONS commands. Sections are laid out as the same order as they
907// were in the script. If a given name did not appear in the script,
908// it returns INT_MAX, so that it will be laid out at end of file.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000909int LinkerScript::getSectionIndex(StringRef Name) {
Rui Ueyama6e68c5e2016-11-19 18:05:58 +0000910 for (int I = 0, E = Opt.Commands.size(); I != E; ++I)
Rui Ueyama8f99f732017-04-05 03:20:42 +0000911 if (auto *Cmd = dyn_cast<OutputSectionCommand>(Opt.Commands[I]))
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000912 if (Cmd->Name == Name)
913 return I;
Rui Ueyamaf510fa62016-07-26 00:21:15 +0000914 return INT_MAX;
George Rimar71b26e92016-04-21 10:22:02 +0000915}
916
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000917ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
Rafael Espindola4595df92017-03-10 16:04:26 +0000918 if (S == ".")
Rafael Espindola72dc1952017-03-17 13:05:04 +0000919 return {CurOutSec, Dot - CurOutSec->Addr};
George Rimara8dba482017-03-20 10:09:58 +0000920 if (SymbolBody *B = findSymbol(S)) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000921 if (auto *D = dyn_cast<DefinedRegular>(B))
922 return {D->Section, D->Value};
Petr Hosek30f16b22017-03-23 03:52:34 +0000923 if (auto *C = dyn_cast<DefinedCommon>(B))
924 return {InX::Common, C->Offset};
Rafael Espindola72dc1952017-03-17 13:05:04 +0000925 }
Eugene Leviantf6aeed32016-12-22 13:13:12 +0000926 error(Loc + ": symbol not found: " + S);
George Rimar884e7862016-09-08 08:19:13 +0000927 return 0;
928}
929
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000930bool LinkerScript::isDefined(StringRef S) { return findSymbol(S) != nullptr; }
George Rimarf34f45f2016-09-23 13:17:23 +0000931
Eugene Leviantbbe38602016-07-19 09:25:43 +0000932// Returns indices of ELF headers containing specific section, identified
933// by Name. Each index is a zero based number of ELF header listed within
934// PHDRS {} script block.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000935std::vector<size_t> LinkerScript::getPhdrIndices(StringRef SectionName) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000936 for (BaseCommand *Base : Opt.Commands) {
937 auto *Cmd = dyn_cast<OutputSectionCommand>(Base);
Rui Ueyamaedebbdf2016-07-24 23:47:31 +0000938 if (!Cmd || Cmd->Name != SectionName)
George Rimar31d842f2016-07-20 16:43:03 +0000939 continue;
940
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000941 std::vector<size_t> Ret;
942 for (StringRef PhdrName : Cmd->Phdrs)
Eugene Leviant2a942c42016-12-05 16:38:32 +0000943 Ret.push_back(getPhdrIndex(Cmd->Location, PhdrName));
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000944 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000945 }
George Rimar31d842f2016-07-20 16:43:03 +0000946 return {};
Eugene Leviantbbe38602016-07-19 09:25:43 +0000947}
948
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000949size_t LinkerScript::getPhdrIndex(const Twine &Loc, StringRef PhdrName) {
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000950 size_t I = 0;
951 for (PhdrsCommand &Cmd : Opt.PhdrsCommands) {
952 if (Cmd.Name == PhdrName)
953 return I;
954 ++I;
955 }
Eugene Leviant2a942c42016-12-05 16:38:32 +0000956 error(Loc + ": section header '" + PhdrName + "' is not listed in PHDRS");
Rui Ueyama29c5a2a2016-07-26 00:27:36 +0000957 return 0;
958}