blob: da765689df521d8f7df712d06c184166c71a33d8 [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 Espindola8c022ca2017-07-27 19:22:43 +000082OutputSection *LinkerScript::createOutputSection(StringRef Name,
83 StringRef Location) {
84 OutputSection *&SecRef = NameToOutputSection[Name];
85 OutputSection *Sec;
86 if (SecRef && SecRef->Location.empty()) {
Rafael Espindola05c4f672017-06-01 01:16:50 +000087 // There was a forward reference.
Rafael Espindola8c022ca2017-07-27 19:22:43 +000088 Sec = SecRef;
Rafael Espindola05c4f672017-06-01 01:16:50 +000089 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +000090 Sec = make<OutputSection>(Name, SHT_PROGBITS, 0);
91 if (!SecRef)
92 SecRef = Sec;
Rafael Espindola05c4f672017-06-01 01:16:50 +000093 }
Rafael Espindola8c022ca2017-07-27 19:22:43 +000094 Sec->Location = Location;
95 return Sec;
George Rimar851dc1e2017-03-14 10:15:53 +000096}
97
Rafael Espindola8c022ca2017-07-27 19:22:43 +000098OutputSection *LinkerScript::getOrCreateOutputSection(StringRef Name) {
99 OutputSection *&CmdRef = NameToOutputSection[Name];
Rafael Espindola05c4f672017-06-01 01:16:50 +0000100 if (!CmdRef)
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000101 CmdRef = make<OutputSection>(Name, SHT_PROGBITS, 0);
Rafael Espindola05c4f672017-06-01 01:16:50 +0000102 return CmdRef;
George Rimard83ce1b2017-03-14 10:24:47 +0000103}
104
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000105void LinkerScript::setDot(Expr E, const Twine &Loc, bool InSec) {
Rafael Espindola72dc1952017-03-17 13:05:04 +0000106 uint64_t Val = E().getValue();
George Rimar8c804d92017-07-12 14:50:25 +0000107 if (Val < Dot && InSec)
108 error(Loc + ": unable to move location counter backward for: " +
Rui Ueyama29b240c2017-10-11 02:45:54 +0000109 Ctx->OutSec->Name);
Rafael Espindola679828f2017-02-17 16:26:13 +0000110 Dot = Val;
Rui Ueyama18d19682017-10-11 01:03:37 +0000111
Rafael Espindola679828f2017-02-17 16:26:13 +0000112 // Update to location counter means update to section size.
113 if (InSec)
Rui Ueyama29b240c2017-10-11 02:45:54 +0000114 Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr;
Rafael Espindola679828f2017-02-17 16:26:13 +0000115}
116
Rui Ueyama5908c2f2017-10-11 02:28:28 +0000117// This function is called from processSectionCommands,
118// while we are fixing the output section layout.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000119void LinkerScript::addSymbol(SymbolAssignment *Cmd) {
Rui Ueyama16024212016-08-11 23:22:52 +0000120 if (Cmd->Name == ".")
Meador Inge8f1f3c42017-01-09 18:36:57 +0000121 return;
122
123 // If a symbol was in PROVIDE(), we need to define it only when
124 // it is a referenced undefined symbol.
Rafael Espindola244ef982017-07-26 18:42:48 +0000125 SymbolBody *B = Symtab->find(Cmd->Name);
Meador Inge8f1f3c42017-01-09 18:36:57 +0000126 if (Cmd->Provide && (!B || B->isDefined()))
127 return;
128
Rui Ueyama18d19682017-10-11 01:03:37 +0000129 // Define a symbol.
130 Symbol *Sym;
131 uint8_t Visibility = Cmd->Hidden ? STV_HIDDEN : STV_DEFAULT;
132 std::tie(Sym, std::ignore) = Symtab->insert(Cmd->Name, /*Type*/ 0, Visibility,
133 /*CanOmitFromDynSym*/ false,
134 /*File*/ nullptr);
135 Sym->Binding = STB_GLOBAL;
136 ExprValue Value = Cmd->Expression();
137 SectionBase *Sec = Value.isAbsolute() ? nullptr : Value.Sec;
138
139 // When this function is called, section addresses have not been
140 // fixed yet. So, we may or may not know the value of the RHS
141 // expression.
142 //
143 // For example, if an expression is `x = 42`, we know x is always 42.
144 // However, if an expression is `x = .`, there's no way to know its
145 // value at the moment.
146 //
147 // We want to set symbol values early if we can. This allows us to
148 // use symbols as variables in linker scripts. Doing so allows us to
149 // write expressions like this: `alignment = 16; . = ALIGN(., alignment)`.
150 uint64_t SymValue = Value.Sec ? 0 : Value.getValue();
151
152 replaceBody<DefinedRegular>(Sym, nullptr, Cmd->Name, /*IsLocal=*/false,
153 Visibility, STT_NOTYPE, SymValue, 0, Sec);
154 Cmd->Sym = cast<DefinedRegular>(Sym->body());
155}
156
157// This function is called from assignAddresses, while we are
158// fixing the output section addresses. This function is supposed
159// to set the final value for a given symbol assignment.
160void LinkerScript::assignSymbol(SymbolAssignment *Cmd, bool InSec) {
161 if (Cmd->Name == ".") {
162 setDot(Cmd->Expression, Cmd->Location, InSec);
163 return;
164 }
165
166 if (!Cmd->Sym)
167 return;
168
169 ExprValue V = Cmd->Expression();
170 if (V.isAbsolute()) {
171 Cmd->Sym->Section = nullptr;
172 Cmd->Sym->Value = V.getValue();
173 } else {
174 Cmd->Sym->Section = V.Sec;
175 Cmd->Sym->Value = V.getSectionOffset();
176 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000177}
178
Rui Ueyama04c9ca72017-10-11 02:54:52 +0000179static std::string getFilename(InputFile *File) {
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000180 if (!File)
Dmitry Mikulinf300ca22017-08-24 22:01:40 +0000181 return "";
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000182 if (File->ArchiveName.empty())
183 return File->getName();
184 return (File->ArchiveName + "(" + File->getName() + ")").str();
Rui Ueyamae0be2902016-11-21 02:10:12 +0000185}
186
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000187bool LinkerScript::shouldKeep(InputSectionBase *S) {
Rui Ueyama04c9ca72017-10-11 02:54:52 +0000188 std::string Filename = getFilename(S->File);
Rui Ueyama7f1c2662017-10-11 01:26:22 +0000189 for (InputSectionDescription *ID : KeptSections)
Dmitry Mikulinf300ca22017-08-24 22:01:40 +0000190 if (ID->FilePat.match(Filename))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000191 for (SectionPattern &P : ID->SectionPatterns)
192 if (P.SectionPat.match(S->Name))
193 return true;
George Rimareea31142016-07-21 14:26:59 +0000194 return false;
195}
196
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000197// A helper function for the SORT() command.
Rafael Espindolac404d502017-02-23 02:32:18 +0000198static std::function<bool(InputSectionBase *, InputSectionBase *)>
George Rimarbe394db2016-09-16 20:21:55 +0000199getComparator(SortSectionPolicy K) {
200 switch (K) {
201 case SortSectionPolicy::Alignment:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000202 return [](InputSectionBase *A, InputSectionBase *B) {
203 // ">" is not a mistake. Sections with larger alignments are placed
204 // before sections with smaller alignments in order to reduce the
205 // amount of padding necessary. This is compatible with GNU.
206 return A->Alignment > B->Alignment;
207 };
George Rimarbe394db2016-09-16 20:21:55 +0000208 case SortSectionPolicy::Name:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000209 return [](InputSectionBase *A, InputSectionBase *B) {
210 return A->Name < B->Name;
211 };
George Rimarbe394db2016-09-16 20:21:55 +0000212 case SortSectionPolicy::Priority:
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000213 return [](InputSectionBase *A, InputSectionBase *B) {
214 return getPriority(A->Name) < getPriority(B->Name);
215 };
George Rimarbe394db2016-09-16 20:21:55 +0000216 default:
217 llvm_unreachable("unknown sort policy");
218 }
Rui Ueyama742c3832016-08-04 22:27:00 +0000219}
George Rimar0702c4e2016-07-29 15:32:46 +0000220
Rui Ueyamaea93fe02017-04-05 00:43:25 +0000221// A helper function for the SORT() command.
Rui Ueyama05433432017-10-11 04:01:13 +0000222static bool matchConstraints(ArrayRef<InputSection *> Sections,
George Rimar06ae6832016-08-12 09:07:57 +0000223 ConstraintKind Kind) {
George Rimar8f66df92016-08-12 20:38:20 +0000224 if (Kind == ConstraintKind::NoConstraint)
225 return true;
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000226
Rui Ueyamab8014412017-10-11 02:55:05 +0000227 bool IsRW = llvm::any_of(
Rui Ueyama05433432017-10-11 04:01:13 +0000228 Sections, [](InputSection *Sec) { return Sec->Flags & SHF_WRITE; });
Rui Ueyama2c7171b2017-04-05 00:43:45 +0000229
Rafael Espindolae746e522016-09-21 18:33:44 +0000230 return (IsRW && Kind == ConstraintKind::ReadWrite) ||
231 (!IsRW && Kind == ConstraintKind::ReadOnly);
George Rimar06ae6832016-08-12 09:07:57 +0000232}
233
Rui Ueyama1f4d7b52017-10-11 03:23:29 +0000234static void sortSections(MutableArrayRef<InputSection *> Vec,
Rui Ueyamaee924702016-09-20 19:42:41 +0000235 SortSectionPolicy K) {
236 if (K != SortSectionPolicy::Default && K != SortSectionPolicy::None)
Rui Ueyama1f4d7b52017-10-11 03:23:29 +0000237 std::stable_sort(Vec.begin(), Vec.end(), getComparator(K));
Rui Ueyamaee924702016-09-20 19:42:41 +0000238}
239
Rafael Espindolad3190792016-09-16 15:10:23 +0000240// Compute and remember which sections the InputSectionDescription matches.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000241std::vector<InputSection *>
Rui Ueyama72e107f2017-04-05 02:05:48 +0000242LinkerScript::computeInputSections(const InputSectionDescription *Cmd) {
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000243 std::vector<InputSection *> Ret;
Rui Ueyama187b67a2017-10-11 03:34:09 +0000244 DenseMap<SectionBase *, int> Order = buildSectionOrder();
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000245
Rui Ueyama72e107f2017-04-05 02:05:48 +0000246 // Collects all sections that satisfy constraints of Cmd.
247 for (const SectionPattern &Pat : Cmd->SectionPatterns) {
248 size_t SizeBefore = Ret.size();
249
250 for (InputSectionBase *Sec : InputSections) {
251 if (Sec->Assigned)
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000252 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000253
Rafael Espindolae39709b2017-05-30 20:40:03 +0000254 if (!Sec->Live) {
255 reportDiscarded(Sec);
256 continue;
257 }
258
Rafael Espindola908a3d32017-02-16 14:36:09 +0000259 // For -emit-relocs we have to ignore entries like
260 // .rela.dyn : { *(.rela.data) }
261 // which are common because they are in the default bfd script.
Rui Ueyama72e107f2017-04-05 02:05:48 +0000262 if (Sec->Type == SHT_REL || Sec->Type == SHT_RELA)
Rafael Espindola908a3d32017-02-16 14:36:09 +0000263 continue;
Rui Ueyama8c6a5aa2016-11-05 22:37:59 +0000264
Rui Ueyama04c9ca72017-10-11 02:54:52 +0000265 std::string Filename = getFilename(Sec->File);
Rui Ueyama72e107f2017-04-05 02:05:48 +0000266 if (!Cmd->FilePat.match(Filename) ||
267 Pat.ExcludedFilePat.match(Filename) ||
268 !Pat.SectionPat.match(Sec->Name))
Rui Ueyamae0be2902016-11-21 02:10:12 +0000269 continue;
Rui Ueyama72e107f2017-04-05 02:05:48 +0000270
Rui Ueyamaec5c4ad2017-10-11 03:23:17 +0000271 // It is safe to assume that Sec is an InputSection
272 // because mergeable or EH input sections have already been
273 // handled and eliminated.
Rafael Espindola6a1aa8d2017-05-23 22:47:31 +0000274 Ret.push_back(cast<InputSection>(Sec));
Rui Ueyama72e107f2017-04-05 02:05:48 +0000275 Sec->Assigned = true;
George Rimar395281c2016-09-16 17:42:10 +0000276 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000277
George Rimar07171f22016-09-21 15:56:44 +0000278 // Sort sections as instructed by SORT-family commands and --sort-section
279 // option. Because SORT-family commands can be nested at most two depth
280 // (e.g. SORT_BY_NAME(SORT_BY_ALIGNMENT(.text.*))) and because the command
281 // line option is respected even if a SORT command is given, the exact
282 // behavior we have here is a bit complicated. Here are the rules.
283 //
284 // 1. If two SORT commands are given, --sort-section is ignored.
285 // 2. If one SORT command is given, and if it is not SORT_NONE,
286 // --sort-section is handled as an inner SORT command.
287 // 3. If one SORT command is given, and if it is SORT_NONE, don't sort.
288 // 4. If no SORT command is given, sort according to --sort-section.
George Rimard6bcde32017-08-04 10:25:29 +0000289 // 5. If no SORT commands are given and --sort-section is not specified,
290 // apply sorting provided by --symbol-ordering-file if any exist.
Rui Ueyama1f4d7b52017-10-11 03:23:29 +0000291 auto Vec = MutableArrayRef<InputSection *>(Ret).slice(SizeBefore);
292
George Rimard6bcde32017-08-04 10:25:29 +0000293 if (Pat.SortOuter == SortSectionPolicy::Default &&
294 Config->SortSection == SortSectionPolicy::Default) {
Rui Ueyama187b67a2017-10-11 03:34:09 +0000295
296 // If -symbol-ordering-file was given, sort accordingly.
297 // Usually, Order is empty.
298 if (!Order.empty())
299 sortByOrder(Vec, [&](InputSectionBase *S) { return Order.lookup(S); });
George Rimard6bcde32017-08-04 10:25:29 +0000300 continue;
301 }
Rui Ueyama1f4d7b52017-10-11 03:23:29 +0000302
George Rimar07171f22016-09-21 15:56:44 +0000303 if (Pat.SortOuter != SortSectionPolicy::None) {
304 if (Pat.SortInner == SortSectionPolicy::Default)
Rui Ueyama1f4d7b52017-10-11 03:23:29 +0000305 sortSections(Vec, Config->SortSection);
George Rimar07171f22016-09-21 15:56:44 +0000306 else
Rui Ueyama1f4d7b52017-10-11 03:23:29 +0000307 sortSections(Vec, Pat.SortInner);
308 sortSections(Vec, Pat.SortOuter);
George Rimar07171f22016-09-21 15:56:44 +0000309 }
Rui Ueyamaee924702016-09-20 19:42:41 +0000310 }
Rui Ueyama72e107f2017-04-05 02:05:48 +0000311 return Ret;
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000312}
313
Rui Ueyama05433432017-10-11 04:01:13 +0000314void LinkerScript::discard(ArrayRef<InputSection *> V) {
315 for (InputSection *S : V) {
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000316 S->Live = false;
Dmitry Mikulin1e30f072017-09-08 16:22:43 +0000317 if (S == InX::ShStrTab || S == InX::Dynamic || S == InX::DynSymTab ||
318 S == InX::DynStrTab)
Rafael Espindola2af64b02017-06-16 23:45:35 +0000319 error("discarding " + S->Name + " section is not allowed");
George Rimar647c1682017-02-17 19:34:05 +0000320 discard(S->DependentSections);
Rafael Espindolabe94e1b2016-09-14 14:32:08 +0000321 }
322}
323
Rui Ueyama05433432017-10-11 04:01:13 +0000324std::vector<InputSection *>
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000325LinkerScript::createInputSectionList(OutputSection &OutCmd) {
Rui Ueyama05433432017-10-11 04:01:13 +0000326 std::vector<InputSection *> Ret;
Rui Ueyamae7f912c2016-08-03 21:12:09 +0000327
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000328 for (BaseCommand *Base : OutCmd.SectionCommands) {
Rui Ueyama05433432017-10-11 04:01:13 +0000329 if (auto *Cmd = dyn_cast<InputSectionDescription>(Base)) {
330 Cmd->Sections = computeInputSections(Cmd);
331 Ret.insert(Ret.end(), Cmd->Sections.begin(), Cmd->Sections.end());
332 }
Rui Ueyama0b9ce6a2016-08-12 03:16:56 +0000333 }
334 return Ret;
335}
336
Rui Ueyama5908c2f2017-10-11 02:28:28 +0000337void LinkerScript::processSectionCommands(OutputSectionFactory &Factory) {
Rafael Espindola5616adf2017-03-08 22:36:28 +0000338 // A symbol can be assigned before any section is mentioned in the linker
339 // script. In an DSO, the symbol values are addresses, so the only important
340 // section values are:
341 // * SHN_UNDEF
342 // * SHN_ABS
343 // * Any value meaning a regular section.
344 // To handle that, create a dummy aether section that fills the void before
345 // the linker scripts switches to another section. It has an index of one
346 // which will map to whatever the first actual section is.
347 Aether = make<OutputSection>("", 0, SHF_ALLOC);
348 Aether->SectionIndex = 1;
Rui Ueyama18d19682017-10-11 01:03:37 +0000349
Rui Ueyama29b240c2017-10-11 02:45:54 +0000350 // Ctx captures the local AddressState and makes it accessible deliberately.
351 // This is needed as there are some cases where we cannot just
Peter Smithc1ace402017-07-11 09:28:27 +0000352 // thread the current state through to a lambda function created by the
353 // script parser.
Rui Ueyama29b240c2017-10-11 02:45:54 +0000354 Ctx = make_unique<AddressState>();
355 Ctx->OutSec = Aether;
Rafael Espindola5616adf2017-03-08 22:36:28 +0000356
Rui Ueyama355a8dd2017-10-11 04:01:24 +0000357 // Add input sections to output sections.
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000358 for (size_t I = 0; I < SectionCommands.size(); ++I) {
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000359 // Handle symbol assignments outside of any output section.
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000360 if (auto *Cmd = dyn_cast<SymbolAssignment>(SectionCommands[I])) {
Rafael Espindola4cd73522017-02-17 16:01:51 +0000361 addSymbol(Cmd);
Rui Ueyama2ab5f732016-08-12 03:33:04 +0000362 continue;
363 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000364
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000365 if (auto *Sec = dyn_cast<OutputSection>(SectionCommands[I])) {
Rui Ueyama05433432017-10-11 04:01:13 +0000366 std::vector<InputSection *> V = createInputSectionList(*Sec);
Rafael Espindola7bd37872016-09-12 16:05:16 +0000367
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000368 // The output section name `/DISCARD/' is special.
369 // Any input section assigned to it is discarded.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000370 if (Sec->Name == "/DISCARD/") {
Rafael Espindola7bd37872016-09-12 16:05:16 +0000371 discard(V);
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000372 continue;
373 }
Eugene Leviantceabe802016-08-11 07:56:43 +0000374
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000375 // This is for ONLY_IF_RO and ONLY_IF_RW. An output section directive
376 // ".foo : ONLY_IF_R[OW] { ... }" is handled only if all member input
377 // sections satisfy a given constraint. If not, a directive is handled
George Rimar07d7c422017-04-05 09:19:29 +0000378 // as if it wasn't present from the beginning.
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000379 //
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000380 // Because we'll iterate over SectionCommands many more times, the easiest
George Rimar07d7c422017-04-05 09:19:29 +0000381 // way to "make it as if it wasn't present" is to just remove it.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000382 if (!matchConstraints(V, Sec->Constraint)) {
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000383 for (InputSectionBase *S : V)
Rui Ueyamaf94efdd2016-11-20 23:15:52 +0000384 S->Assigned = false;
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000385 SectionCommands.erase(SectionCommands.begin() + I);
George Rimar07d7c422017-04-05 09:19:29 +0000386 --I;
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000387 continue;
388 }
389
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000390 // A directive may contain symbol definitions like this:
391 // ".foo : { ...; bar = .; }". Handle them.
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000392 for (BaseCommand *Base : Sec->SectionCommands)
Rui Ueyama8f99f732017-04-05 03:20:42 +0000393 if (auto *OutCmd = dyn_cast<SymbolAssignment>(Base))
Rafael Espindola4cd73522017-02-17 16:01:51 +0000394 addSymbol(OutCmd);
Rafael Espindola7c3ff2e2016-09-16 21:05:36 +0000395
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000396 // Handle subalign (e.g. ".foo : SUBALIGN(32) { ... }"). If subalign
397 // is given, input sections are aligned to that value, whether the
398 // given value is larger or smaller than the original section alignment.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000399 if (Sec->SubalignExpr) {
400 uint32_t Subalign = Sec->SubalignExpr().getValue();
Rafael Espindolab4c9b812017-02-23 02:28:28 +0000401 for (InputSectionBase *S : V)
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000402 S->Alignment = Subalign;
George Rimardb24d9c2016-08-19 15:18:23 +0000403 }
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000404
405 // Add input sections to an output section.
Rui Ueyama05433432017-10-11 04:01:13 +0000406 for (InputSection *S : V)
407 Sec->addSection(S);
Eugene Leviantceabe802016-08-11 07:56:43 +0000408 }
Rui Ueyama48c3f1c2016-08-12 00:27:23 +0000409 }
Rui Ueyama29b240c2017-10-11 02:45:54 +0000410 Ctx = nullptr;
Rui Ueyama355a8dd2017-10-11 04:01:24 +0000411
412 // Output sections are emitted in the exact same order as
413 // appeared in SECTIONS command, so we know their section indices.
414 for (size_t I = 0; I < SectionCommands.size(); ++I) {
415 auto *Sec = dyn_cast<OutputSection>(SectionCommands[I]);
416 if (!Sec)
417 continue;
418 assert(Sec->SectionIndex == INT_MAX);
419 Sec->SectionIndex = I;
420 if (Sec->Noload)
421 Sec->Type = SHT_NOBITS;
422 }
Eugene Leviant20d03192016-09-16 15:30:47 +0000423}
Eugene Leviante63d81b2016-07-20 14:43:20 +0000424
Rui Ueyama2f4c1212017-10-11 04:21:55 +0000425// If no SECTIONS command was given, we create simple SectionCommands
426// as if a minimum SECTIONS command were given. This function does that.
Rafael Espindola02ed7572017-05-04 19:34:17 +0000427void LinkerScript::fabricateDefaultCommands() {
Peter Smithcbfe9e92017-04-19 12:46:32 +0000428 // Define start address
Rui Ueyama761f0b62017-09-25 17:40:21 +0000429 uint64_t StartAddr = UINT64_MAX;
Peter Smithcbfe9e92017-04-19 12:46:32 +0000430
Peter Smithc60b4512017-05-03 08:44:50 +0000431 // The Sections with -T<section> have been sorted in order of ascending
432 // address. We must lower StartAddr if the lowest -T<section address> as
433 // calls to setDot() must be monotonically increasing.
George Rimar67c60722017-07-18 11:55:35 +0000434 for (auto &KV : Config->SectionStartMap)
Peter Smithc60b4512017-05-03 08:44:50 +0000435 StartAddr = std::min(StartAddr, KV.second);
436
Rui Ueyamaf5db0b32017-09-25 17:19:17 +0000437 auto Expr = [=] {
James Hendersonb5ca92e2017-10-10 10:09:35 +0000438 return std::min(StartAddr, Target->getImageBase() + elf::getHeaderSize());
Rui Ueyamaf5db0b32017-09-25 17:19:17 +0000439 };
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000440 SectionCommands.insert(SectionCommands.begin(),
441 make<SymbolAssignment>(".", Expr, ""));
Peter Smithcbfe9e92017-04-19 12:46:32 +0000442}
443
Rui Ueyamad2f225f2017-10-06 23:06:55 +0000444static OutputSection *findByName(ArrayRef<BaseCommand *> Vec,
445 StringRef Name) {
446 for (BaseCommand *Base : Vec)
447 if (auto *Sec = dyn_cast<OutputSection>(Base))
448 if (Sec->Name == Name)
449 return Sec;
450 return nullptr;
451}
452
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000453// Add sections that didn't match any sections command.
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000454void LinkerScript::addOrphanSections(OutputSectionFactory &Factory) {
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000455 unsigned End = SectionCommands.size();
Rui Ueyamad2f225f2017-10-06 23:06:55 +0000456
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000457 for (InputSectionBase *S : InputSections) {
Rafael Espindoladb5e56f2017-05-31 20:17:44 +0000458 if (!S->Live || S->Parent)
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000459 continue;
Rui Ueyamad2f225f2017-10-06 23:06:55 +0000460
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000461 StringRef Name = getOutputSectionName(S->Name);
George Rimar347c70d2017-09-25 09:41:32 +0000462 log(toString(S) + " is being placed in '" + Name + "'");
Rui Ueyamad2f225f2017-10-06 23:06:55 +0000463
Rui Ueyamaac27de92017-10-11 01:19:33 +0000464 if (OutputSection *Sec =
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000465 findByName(makeArrayRef(SectionCommands).slice(0, End), Name)) {
Rui Ueyama0e2bfb12017-10-07 00:43:31 +0000466 Sec->addSection(cast<InputSection>(S));
Rui Ueyamac54d5b12017-10-06 23:34:43 +0000467 continue;
Rafael Espindolade8d9892017-04-29 15:44:03 +0000468 }
Rui Ueyamac54d5b12017-10-06 23:34:43 +0000469
470 if (OutputSection *OS = Factory.addInputSec(S, Name))
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000471 SectionCommands.push_back(OS);
Rui Ueyamac54d5b12017-10-06 23:34:43 +0000472 assert(S->getOutputSection()->SectionIndex == INT_MAX);
Rafael Espindola4f013bb2017-04-26 22:30:15 +0000473 }
Eugene Leviante63d81b2016-07-20 14:43:20 +0000474}
475
Rui Ueyama71f84062017-10-11 02:46:09 +0000476uint64_t LinkerScript::advance(uint64_t Size, unsigned Alignment) {
Rui Ueyama29b240c2017-10-11 02:45:54 +0000477 bool IsTbss =
478 (Ctx->OutSec->Flags & SHF_TLS) && Ctx->OutSec->Type == SHT_NOBITS;
479 uint64_t Start = IsTbss ? Dot + Ctx->ThreadBssOffset : Dot;
Rui Ueyama71f84062017-10-11 02:46:09 +0000480 Start = alignTo(Start, Alignment);
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000481 uint64_t End = Start + Size;
482
483 if (IsTbss)
Rui Ueyama29b240c2017-10-11 02:45:54 +0000484 Ctx->ThreadBssOffset = End - Dot;
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000485 else
486 Dot = End;
487 return End;
Rafael Espindolaa940e532016-09-22 12:35:44 +0000488}
489
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000490void LinkerScript::output(InputSection *S) {
George Rimarf694d332017-07-25 08:29:29 +0000491 uint64_t Before = advance(0, 1);
Rafael Espindola7c4eafa2017-05-04 03:00:27 +0000492 uint64_t Pos = advance(S->getSize(), S->Alignment);
Rui Ueyama29b240c2017-10-11 02:45:54 +0000493 S->OutSecOff = Pos - S->getSize() - Ctx->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000494
495 // Update output section size after adding each section. This is so that
496 // SIZEOF works correctly in the case below:
497 // .foo { *(.aaa) a = SIZEOF(.foo); *(.bbb) }
Rui Ueyama29b240c2017-10-11 02:45:54 +0000498 Ctx->OutSec->Size = Pos - Ctx->OutSec->Addr;
Rafael Espindolad3190792016-09-16 15:10:23 +0000499
Meador Ingeb8897442017-01-24 02:34:00 +0000500 // If there is a memory region associated with this input section, then
501 // place the section in that region and update the region index.
Rui Ueyama29b240c2017-10-11 02:45:54 +0000502 if (Ctx->MemRegion) {
503 uint64_t &CurOffset = Ctx->MemRegionOffset[Ctx->MemRegion];
George Rimarf694d332017-07-25 08:29:29 +0000504 CurOffset += Pos - Before;
Rui Ueyama29b240c2017-10-11 02:45:54 +0000505 uint64_t CurSize = CurOffset - Ctx->MemRegion->Origin;
506 if (CurSize > Ctx->MemRegion->Length) {
507 uint64_t OverflowAmt = CurSize - Ctx->MemRegion->Length;
508 error("section '" + Ctx->OutSec->Name + "' will not fit in region '" +
509 Ctx->MemRegion->Name + "': overflowed by " + Twine(OverflowAmt) +
510 " 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) {
Rui Ueyama29b240c2017-10-11 02:45:54 +0000516 if (Ctx->OutSec == Sec)
Rafael Espindolad3190792016-09-16 15:10:23 +0000517 return;
Rafael Espindolad3190792016-09-16 15:10:23 +0000518
Rui Ueyama29b240c2017-10-11 02:45:54 +0000519 Ctx->OutSec = Sec;
520 Ctx->OutSec->Addr = advance(0, Ctx->OutSec->Alignment);
Eugene Leviantb71d6f72016-10-06 09:39:28 +0000521
522 // If neither AT nor AT> is specified for an allocatable section, the linker
523 // will set the LMA such that the difference between VMA and LMA for the
524 // section is the same as the preceding output section in the same region
525 // https://sourceware.org/binutils/docs-2.20/ld/Output-Section-LMA.html
Rui Ueyama29b240c2017-10-11 02:45:54 +0000526 if (Ctx->LMAOffset)
527 Ctx->OutSec->LMAOffset = Ctx->LMAOffset();
Rafael Espindolad3190792016-09-16 15:10:23 +0000528}
529
Meador Ingeb8897442017-01-24 02:34:00 +0000530// This function searches for a memory region to place the given output
531// section in. If found, a pointer to the appropriate memory region is
532// returned. Otherwise, a nullptr is returned.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000533MemoryRegion *LinkerScript::findMemoryRegion(OutputSection *Sec) {
Meador Ingeb8897442017-01-24 02:34:00 +0000534 // If a memory region name was specified in the output section command,
535 // then try to find that region first.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000536 if (!Sec->MemoryRegionName.empty()) {
Rui Ueyamaac27de92017-10-11 01:19:33 +0000537 auto It = MemoryRegions.find(Sec->MemoryRegionName);
538 if (It != MemoryRegions.end())
George Rimar5f375412017-09-08 08:23:15 +0000539 return It->second;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000540 error("memory region '" + Sec->MemoryRegionName + "' not declared");
Meador Ingeb8897442017-01-24 02:34:00 +0000541 return nullptr;
542 }
543
Rui Ueyamad7c54002017-04-05 03:19:43 +0000544 // If at least one memory region is defined, all sections must
545 // belong to some memory region. Otherwise, we don't need to do
546 // anything for memory regions.
Rui Ueyamaac27de92017-10-11 01:19:33 +0000547 if (MemoryRegions.empty())
Meador Ingeb8897442017-01-24 02:34:00 +0000548 return nullptr;
549
550 // See if a region can be found by matching section flags.
Rui Ueyamaac27de92017-10-11 01:19:33 +0000551 for (auto &Pair : MemoryRegions) {
George Rimar5f375412017-09-08 08:23:15 +0000552 MemoryRegion *M = Pair.second;
553 if ((M->Flags & Sec->Flags) && (M->NegFlags & Sec->Flags) == 0)
554 return M;
Meador Ingeb8897442017-01-24 02:34:00 +0000555 }
556
557 // Otherwise, no suitable region was found.
558 if (Sec->Flags & SHF_ALLOC)
559 error("no memory region specified for section '" + Sec->Name + "'");
560 return nullptr;
561}
562
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000563// This function assigns offsets to input sections and an output section
564// for a single sections command (e.g. ".text { *(.text); }").
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000565void LinkerScript::assignOffsets(OutputSection *Sec) {
Rafael Espindoladece2802017-06-13 20:57:43 +0000566 if (!(Sec->Flags & SHF_ALLOC))
567 Dot = 0;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000568 else if (Sec->AddrExpr)
569 setDot(Sec->AddrExpr, Sec->Location, false);
Rafael Espindola679828f2017-02-17 16:26:13 +0000570
Rui Ueyama29b240c2017-10-11 02:45:54 +0000571 Ctx->MemRegion = Sec->MemRegion;
572 if (Ctx->MemRegion)
573 Dot = Ctx->MemRegionOffset[Ctx->MemRegion];
George Rimarc2dffe32017-09-06 09:35:09 +0000574
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000575 if (Sec->LMAExpr) {
George Rimar0c1c8082017-03-14 10:00:19 +0000576 uint64_t D = Dot;
Rui Ueyama29b240c2017-10-11 02:45:54 +0000577 Ctx->LMAOffset = [=] { return Sec->LMAExpr().getValue() - D; };
Eugene Leviant5784e962017-03-14 08:57:09 +0000578 }
579
Meador Ingeb8897442017-01-24 02:34:00 +0000580 switchTo(Sec);
Rui Ueyama0b1b6952016-11-21 02:11:05 +0000581
George Rimard86a4e52017-05-08 10:18:12 +0000582 // We do not support custom layout for compressed debug sectons.
583 // At this point we already know their size and have compressed content.
Rui Ueyama29b240c2017-10-11 02:45:54 +0000584 if (Ctx->OutSec->Flags & SHF_COMPRESSED)
George Rimard86a4e52017-05-08 10:18:12 +0000585 return;
586
Rui Ueyama2f4c1212017-10-11 04:21:55 +0000587 // We visited SectionsCommands from processSectionCommands to
588 // layout sections. Now, we visit SectionsCommands again to fix
589 // section offsets.
590 for (BaseCommand *Base : Sec->SectionCommands) {
591 // This handles the assignments to symbol or to the dot.
592 if (auto *Cmd = dyn_cast<SymbolAssignment>(Base)) {
593 assignSymbol(Cmd, true);
594 continue;
595 }
596
597 // Handle BYTE(), SHORT(), LONG(), or QUAD().
Rui Ueyamaf0403c62017-10-11 04:22:09 +0000598 if (auto *Cmd = dyn_cast<ByteCommand>(Base)) {
Rui Ueyama2f4c1212017-10-11 04:21:55 +0000599 Cmd->Offset = Dot - Ctx->OutSec->Addr;
600 Dot += Cmd->Size;
601 Ctx->OutSec->Size = Dot - Ctx->OutSec->Addr;
602 continue;
603 }
604
605 // Handle ASSERT().
606 if (auto *Cmd = dyn_cast<AssertCommand>(Base)) {
607 Cmd->Expression();
608 continue;
609 }
610
611 // Handle a single input section description command.
612 // It calculates and assigns the offsets for each section and also
613 // updates the output section size.
614 auto *Cmd = cast<InputSectionDescription>(Base);
615 for (InputSection *Sec : Cmd->Sections) {
616 // We tentatively added all synthetic sections at the beginning and
617 // removed empty ones afterwards (because there is no way to know
618 // whether they were going be empty or not other than actually running
619 // linker scripts.) We need to ignore remains of empty sections.
620 if (auto *S = dyn_cast<SyntheticSection>(Sec))
621 if (S->empty())
622 continue;
623
624 if (!Sec->Live)
625 continue;
626 assert(Ctx->OutSec == Sec->getParent());
627 output(Sec);
628 }
629 }
Rafael Espindolad3190792016-09-16 15:10:23 +0000630}
631
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000632void LinkerScript::removeEmptyCommands() {
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000633 // It is common practice to use very generic linker scripts. So for any
634 // given run some of the output sections in the script will be empty.
635 // We could create corresponding empty output sections, but that would
636 // clutter the output.
637 // We instead remove trivially empty sections. The bfd linker seems even
638 // more aggressive at removing them.
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000639 llvm::erase_if(SectionCommands, [&](BaseCommand *Base) {
George Rimar60608a82017-08-28 09:28:15 +0000640 if (auto *Sec = dyn_cast<OutputSection>(Base))
641 return !Sec->Live;
642 return false;
643 });
Rafael Espindola07fe6122016-11-14 14:23:35 +0000644}
645
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000646static bool isAllSectionDescription(const OutputSection &Cmd) {
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000647 for (BaseCommand *Base : Cmd.SectionCommands)
Rui Ueyama8f99f732017-04-05 03:20:42 +0000648 if (!isa<InputSectionDescription>(*Base))
Rafael Espindola6a537372016-11-14 14:33:49 +0000649 return false;
650 return true;
651}
Rafael Espindola6d38e4d2016-09-20 13:12:07 +0000652
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000653void LinkerScript::adjustSectionsBeforeSorting() {
Rafael Espindola9546fff2016-09-22 14:40:50 +0000654 // If the output section contains only symbol assignments, create a
655 // corresponding output section. The bfd linker seems to only create them if
656 // '.' is assigned to, but creating these section should not have any bad
657 // consequeces and gives us a section to put the symbol in.
George Rimar0c1c8082017-03-14 10:00:19 +0000658 uint64_t Flags = SHF_ALLOC;
Rafael Espindola660c9ab2017-05-05 21:34:26 +0000659
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000660 for (BaseCommand *Cmd : SectionCommands) {
George Rimar8962db92017-09-18 08:43:44 +0000661 auto *Sec = dyn_cast<OutputSection>(Cmd);
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000662 if (!Sec)
Rafael Espindola9546fff2016-09-22 14:40:50 +0000663 continue;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000664 if (Sec->Live) {
Rafael Espindola2b074552017-02-03 22:27:05 +0000665 Flags = Sec->Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000666 continue;
667 }
668
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000669 if (isAllSectionDescription(*Sec))
Rafael Espindola6a537372016-11-14 14:33:49 +0000670 continue;
671
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000672 Sec->Live = true;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000673 Sec->Flags = Flags;
Rafael Espindola9546fff2016-09-22 14:40:50 +0000674 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000675}
676
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000677void LinkerScript::adjustSectionsAfterSorting() {
Rafael Espindolafeed7502017-04-06 21:31:24 +0000678 // Try and find an appropriate memory region to assign offsets in.
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000679 for (BaseCommand *Base : SectionCommands) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000680 if (auto *Sec = dyn_cast<OutputSection>(Base)) {
George Rimarba455842017-10-02 09:11:13 +0000681 if (!Sec->Live)
682 continue;
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000683 Sec->MemRegion = findMemoryRegion(Sec);
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000684 // Handle align (e.g. ".foo : ALIGN(16) { ... }").
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000685 if (Sec->AlignExpr)
Rui Ueyama8befefb2017-10-07 00:58:34 +0000686 Sec->Alignment =
687 std::max<uint32_t>(Sec->Alignment, Sec->AlignExpr().getValue());
Rafael Espindolad1960dc2017-04-06 21:40:22 +0000688 }
689 }
Rafael Espindolafeed7502017-04-06 21:31:24 +0000690
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000691 // If output section command doesn't specify any segments,
692 // and we haven't previously assigned any section to segment,
693 // then we simply assign section to the very first load segment.
694 // Below is an example of such linker script:
695 // PHDRS { seg PT_LOAD; }
696 // SECTIONS { .aaa : { *(.aaa) } }
697 std::vector<StringRef> DefPhdrs;
698 auto FirstPtLoad =
Rui Ueyamaac27de92017-10-11 01:19:33 +0000699 std::find_if(PhdrsCommands.begin(), PhdrsCommands.end(),
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000700 [](const PhdrsCommand &Cmd) { return Cmd.Type == PT_LOAD; });
Rui Ueyamaac27de92017-10-11 01:19:33 +0000701 if (FirstPtLoad != PhdrsCommands.end())
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000702 DefPhdrs.push_back(FirstPtLoad->Name);
703
704 // Walk the commands and propagate the program headers to commands that don't
705 // explicitly specify them.
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000706 for (BaseCommand *Base : SectionCommands) {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000707 auto *Sec = dyn_cast<OutputSection>(Base);
708 if (!Sec)
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000709 continue;
Rui Ueyama8f99f732017-04-05 03:20:42 +0000710
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000711 if (Sec->Phdrs.empty()) {
Andrew Nga020d342017-07-03 10:11:25 +0000712 // To match the bfd linker script behaviour, only propagate program
713 // headers to sections that are allocated.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000714 if (Sec->Flags & SHF_ALLOC)
715 Sec->Phdrs = DefPhdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000716 } else {
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000717 DefPhdrs = Sec->Phdrs;
Andrew Nga020d342017-07-03 10:11:25 +0000718 }
Rafael Espindolaf7a17442016-11-14 15:39:38 +0000719 }
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.
Rui Ueyamaa323e2a2017-10-11 01:34:51 +0000755 uint64_t Base = HasSectionsCommand ? alignDown(Min, Config->MaxPageSize) : 0;
Petr Hosekb93c5b92017-08-23 18:44:34 +0000756 if (HeaderSize <= Min - Base || Script->hasPhdrsCommands()) {
Rafael Espindola1f0fe882017-09-28 18:12:13 +0000757 Min = alignDown(Min - HeaderSize, Config->MaxPageSize);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000758 Out::ElfHeader->Addr = Min;
759 Out::ProgramHeaders->Addr = Min + Out::ElfHeader->Size;
George Rimard971e702017-07-03 16:05:51 +0000760 return;
Rafael Espindola02ed7572017-05-04 19:34:17 +0000761 }
762
George Rimar582ede82017-09-07 10:53:07 +0000763 Out::ElfHeader->PtLoad = nullptr;
764 Out::ProgramHeaders->PtLoad = nullptr;
George Rimar6823c5f2017-09-07 11:01:10 +0000765 FirstPTLoad->FirstSec = findFirstSection(FirstPTLoad);
Rafael Espindola02ed7572017-05-04 19:34:17 +0000766
George Rimar60608a82017-08-28 09:28:15 +0000767 llvm::erase_if(Phdrs,
768 [](const PhdrEntry *E) { return E->p_type == PT_PHDR; });
Rafael Espindola02ed7572017-05-04 19:34:17 +0000769}
770
Rui Ueyamaac27de92017-10-11 01:19:33 +0000771LinkerScript::AddressState::AddressState() {
772 for (auto &MRI : Script->MemoryRegions) {
George Rimar5f375412017-09-08 08:23:15 +0000773 const MemoryRegion *MR = MRI.second;
Peter Smith906e9a12017-07-07 09:11:27 +0000774 MemRegionOffset[MR] = MR->Origin;
775 }
776}
777
James Hendersonb5ca92e2017-10-10 10:09:35 +0000778// Assign addresses as instructed by linker script SECTIONS sub-commands.
Peter Smith5aedebf2017-07-05 09:12:54 +0000779void LinkerScript::assignAddresses() {
James Hendersonb5ca92e2017-10-10 10:09:35 +0000780 // By default linker scripts use an initial value of 0 for '.', but prefer
781 // -image-base if set.
782 Dot = Config->ImageBase ? *Config->ImageBase : 0;
Rui Ueyama18d19682017-10-11 01:03:37 +0000783
Rui Ueyama29b240c2017-10-11 02:45:54 +0000784 // Ctx captures the local AddressState and makes it accessible
Peter Smithc1ace402017-07-11 09:28:27 +0000785 // deliberately. This is needed as there are some cases where we cannot just
786 // thread the current state through to a lambda function created by the
787 // script parser.
Rui Ueyama29b240c2017-10-11 02:45:54 +0000788 Ctx = make_unique<AddressState>();
Rafael Espindola72dc1952017-03-17 13:05:04 +0000789 ErrorOnMissingSection = true;
Rafael Espindola06f47432017-02-06 22:21:46 +0000790 switchTo(Aether);
791
Rui Ueyama6b394ca2017-10-11 01:50:56 +0000792 for (BaseCommand *Base : SectionCommands) {
Rui Ueyama8f99f732017-04-05 03:20:42 +0000793 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
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000803 assignOffsets(cast<OutputSection>(Base));
George Rimar652852c2016-04-16 10:10:32 +0000804 }
Rui Ueyama29b240c2017-10-11 02:45:54 +0000805 Ctx = nullptr;
George Rimar652852c2016-04-16 10:10:32 +0000806}
807
Rui Ueyama464daad2016-08-22 04:55:20 +0000808// Creates program headers as instructed by PHDRS linker script command.
George Rimaraa354182017-07-27 07:46:50 +0000809std::vector<PhdrEntry *> LinkerScript::createPhdrs() {
810 std::vector<PhdrEntry *> Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000811
Rui Ueyama464daad2016-08-22 04:55:20 +0000812 // Process PHDRS and FILEHDR keywords because they are not
813 // real output sections and cannot be added in the following loop.
Rui Ueyamaac27de92017-10-11 01:19:33 +0000814 for (const PhdrsCommand &Cmd : PhdrsCommands) {
Rui Ueyama0ae2c242017-10-08 03:45:49 +0000815 PhdrEntry *Phdr = make<PhdrEntry>(Cmd.Type, Cmd.Flags ? *Cmd.Flags : PF_R);
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);
Rui Ueyamaac27de92017-10-11 01:19:33 +0000834 if (!PhdrsCommands[Id].Flags.hasValue())
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 Ueyamae03ba022017-10-08 03:52:15 +0000841// Returns true if we should emit an .interp section.
842//
843// We usually do. But if PHDRS commands are given, and
844// no PT_INTERP is there, there's no place to emit an
845// .interp, so we don't do that in that case.
846bool LinkerScript::needsInterpSection() {
Rui Ueyamaac27de92017-10-11 01:19:33 +0000847 if (PhdrsCommands.empty())
Rui Ueyamae03ba022017-10-08 03:52:15 +0000848 return true;
Rui Ueyamaac27de92017-10-11 01:19:33 +0000849 for (PhdrsCommand &Cmd : PhdrsCommands)
Rui Ueyamae31d9882017-04-05 05:06:17 +0000850 if (Cmd.Type == PT_INTERP)
Rui Ueyamae03ba022017-10-08 03:52:15 +0000851 return true;
852 return false;
Eugene Leviantf9bc3bd2016-08-16 06:40:58 +0000853}
854
Rui Ueyamab8dd23f2017-03-21 23:02:51 +0000855ExprValue LinkerScript::getSymbolValue(const Twine &Loc, StringRef S) {
George Rimar7e5b0a592017-08-17 08:47:21 +0000856 if (S == ".") {
Rui Ueyama29b240c2017-10-11 02:45:54 +0000857 if (Ctx)
858 return {Ctx->OutSec, false, Dot - Ctx->OutSec->Addr, Loc};
George Rimar7e5b0a592017-08-17 08:47:21 +0000859 error(Loc + ": unable to get location counter value");
860 return 0;
861 }
Rui Ueyamaf5733502017-10-11 04:31:13 +0000862
863 if (auto *Sym = dyn_cast_or_null<DefinedRegular>(Symtab->find(S)))
864 return {Sym->Section, false, Sym->Value, Loc};
865
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
Rui Ueyama656be312017-10-08 02:54:42 +0000870// Returns the index of the segment named Name.
871static Optional<size_t> getPhdrIndex(ArrayRef<PhdrsCommand> Vec,
872 StringRef Name) {
873 for (size_t I = 0; I < Vec.size(); ++I)
874 if (Vec[I].Name == Name)
875 return I;
876 return None;
877}
878
Rafael Espindola2c923c22017-05-10 14:28:31 +0000879// Returns indices of ELF headers containing specific section. Each index is a
880// zero based number of ELF header listed within PHDRS {} script block.
Rafael Espindola8c022ca2017-07-27 19:22:43 +0000881std::vector<size_t> LinkerScript::getPhdrIndices(OutputSection *Cmd) {
Rafael Espindola9f9e99b2017-07-05 22:30:04 +0000882 std::vector<size_t> Ret;
Rui Ueyama656be312017-10-08 02:54:42 +0000883
884 for (StringRef S : Cmd->Phdrs) {
Rui Ueyamaac27de92017-10-11 01:19:33 +0000885 if (Optional<size_t> Idx = getPhdrIndex(PhdrsCommands, S))
Rui Ueyama87223572017-10-08 02:44:08 +0000886 Ret.push_back(*Idx);
Rui Ueyama656be312017-10-08 02:54:42 +0000887 else if (S != "NONE")
888 error(Cmd->Location + ": section header '" + S +
889 "' is not listed in PHDRS");
890 }
Rafael Espindola9f9e99b2017-07-05 22:30:04 +0000891 return Ret;
Eugene Leviantbbe38602016-07-19 09:25:43 +0000892}