blob: e79d30131e53fc9e1fc6d14b4d5cb216b90698bd [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam Cleggc94d3932017-11-17 18:14:09 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000010#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000011#include "InputChunks.h"
Heejin Ahne915a712018-12-08 06:17:43 +000012#include "InputEvent.h"
Sam Clegg93102972018-02-23 05:08:53 +000013#include "InputGlobal.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000014#include "OutputSections.h"
15#include "OutputSegment.h"
Sam Clegg8fcf0122019-05-21 09:13:09 +000016#include "Relocations.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000017#include "SymbolTable.h"
Sam Clegg8fcf0122019-05-21 09:13:09 +000018#include "SyntheticSections.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000019#include "WriterUtils.h"
20#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000021#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000022#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000023#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000024#include "llvm/ADT/DenseSet.h"
Thomas Livelyf6f4f842019-03-20 20:26:45 +000025#include "llvm/ADT/SmallSet.h"
Thomas Lively2a0868f2019-01-17 02:29:41 +000026#include "llvm/ADT/SmallVector.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000027#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000028#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000029#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000030#include "llvm/Support/FileOutputBuffer.h"
31#include "llvm/Support/Format.h"
32#include "llvm/Support/FormatVariadic.h"
33#include "llvm/Support/LEB128.h"
34
35#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000036#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000037
38#define DEBUG_TYPE "lld"
39
40using namespace llvm;
41using namespace llvm::wasm;
42using namespace lld;
43using namespace lld::wasm;
44
Heejin Ahna1cc4ea2019-02-04 19:13:46 +000045static constexpr int StackAlignment = 16;
Sam Cleggc94d3932017-11-17 18:14:09 +000046
47namespace {
48
Sam Cleggc94d3932017-11-17 18:14:09 +000049// The writer writes a SymbolTable result to a file.
50class Writer {
51public:
52 void run();
53
54private:
55 void openFile();
56
Thomas Lively6004d9a2019-07-03 22:04:54 +000057 void createInitMemoryFunction();
Sam Clegg09137be2019-04-04 18:40:51 +000058 void createApplyRelocationsFunction();
59 void createCallCtorsFunction();
60
Sam Clegg8d146bb2018-01-09 23:56:44 +000061 void assignIndexes();
Sam Clegg8fcf0122019-05-21 09:13:09 +000062 void populateSymtab();
63 void populateProducers();
64 void populateTargetFeatures();
65 void calculateInitFunctions();
Sam Cleggc94d3932017-11-17 18:14:09 +000066 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000067 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000068 void calculateCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000069 void calculateTypes();
70 void createOutputSegments();
71 void layoutMemory();
72 void createHeader();
Sam Cleggc94d3932017-11-17 18:14:09 +000073
Sam Clegg8fcf0122019-05-21 09:13:09 +000074 void addSection(OutputSection *Sec);
75
76 void addSections();
Sam Clegg4bce63a2019-05-23 10:06:03 +000077
Sam Clegg80ba4382018-04-10 16:12:49 +000078 void createCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +000079 void createSyntheticSections();
80 void finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000081
82 // Custom sections
83 void createRelocSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000084
85 void writeHeader();
86 void writeSections();
87
88 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +000089 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000090
Sam Clegg93102972018-02-23 05:08:53 +000091 std::vector<WasmInitEntry> InitFunctions;
Sam Clegg80ba4382018-04-10 16:12:49 +000092 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
93
Sam Cleggc94d3932017-11-17 18:14:09 +000094 // Elements that are used to construct the final output
95 std::string Header;
96 std::vector<OutputSection *> OutputSections;
97
98 std::unique_ptr<FileOutputBuffer> Buffer;
99
100 std::vector<OutputSegment *> Segments;
101 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
102};
103
104} // anonymous namespace
105
Sam Cleggd177ab22018-05-04 23:14:42 +0000106void Writer::calculateCustomSections() {
107 log("calculateCustomSections");
108 bool StripDebug = Config->StripDebug || Config->StripAll;
109 for (ObjFile *File : Symtab->ObjectFiles) {
110 for (InputSection *Section : File->CustomSections) {
111 StringRef Name = Section->getName();
112 // These custom sections are known the linker and synthesized rather than
113 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000114 if (Name == "linking" || Name == "name" || Name == "producers" ||
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000115 Name == "target_features" || Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000116 continue;
117 // .. or it is a debug section
118 if (StripDebug && Name.startswith(".debug_"))
119 continue;
120 CustomSectionMapping[Name].push_back(Section);
121 }
122 }
123}
124
Sam Clegg80ba4382018-04-10 16:12:49 +0000125void Writer::createCustomSections() {
126 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000127 for (auto &Pair : CustomSectionMapping) {
128 StringRef Name = Pair.first();
Nicola Zaghene7245b42018-05-15 13:36:20 +0000129 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000130
131 OutputSection *Sec = make<CustomSection>(Name, Pair.second);
Sam Clegg35be7ff2019-05-24 13:28:27 +0000132 if (Config->Relocatable || Config->EmitRelocs) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000133 auto *Sym = make<OutputSectionSymbol>(Sec);
134 Out.LinkingSec->addToSymtab(Sym);
135 Sec->SectionSym = Sym;
136 }
137 addSection(Sec);
Sam Clegg80ba4382018-04-10 16:12:49 +0000138 }
139}
140
Sam Cleggd451da12017-12-19 19:56:27 +0000141// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000142// These are only created when relocatable output is requested.
143void Writer::createRelocSections() {
144 log("createRelocSections");
145 // Don't use iterator here since we are adding to OutputSection
146 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000147 for (size_t I = 0; I < OrigSize; I++) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000148 LLVM_DEBUG(dbgs() << "check section " << I << "\n");
149 OutputSection *Sec = OutputSections[I];
150
151 // Count the number of needed sections.
152 uint32_t Count = Sec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000153 if (!Count)
154 continue;
155
Rui Ueyama37254062018-02-28 00:01:31 +0000156 StringRef Name;
Sam Clegg8fcf0122019-05-21 09:13:09 +0000157 if (Sec->Type == WASM_SEC_DATA)
Rui Ueyama37254062018-02-28 00:01:31 +0000158 Name = "reloc.DATA";
Sam Clegg8fcf0122019-05-21 09:13:09 +0000159 else if (Sec->Type == WASM_SEC_CODE)
Rui Ueyama37254062018-02-28 00:01:31 +0000160 Name = "reloc.CODE";
Sam Clegg8fcf0122019-05-21 09:13:09 +0000161 else if (Sec->Type == WASM_SEC_CUSTOM)
162 Name = Saver.save("reloc." + Sec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000163 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000164 llvm_unreachable(
165 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000166
Sam Clegg8fcf0122019-05-21 09:13:09 +0000167 addSection(make<RelocSection>(Name, Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000168 }
169}
170
Sam Clegg8fcf0122019-05-21 09:13:09 +0000171void Writer::populateProducers() {
Thomas Lively2a0868f2019-01-17 02:29:41 +0000172 for (ObjFile *File : Symtab->ObjectFiles) {
173 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000174 Out.ProducersSec->addInfo(Info);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000175 }
176}
177
Sam Cleggc94d3932017-11-17 18:14:09 +0000178void Writer::writeHeader() {
179 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
180}
181
182void Writer::writeSections() {
183 uint8_t *Buf = Buffer->getBufferStart();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000184 parallelForEach(OutputSections, [Buf](OutputSection *S) {
185 assert(S->isNeeded());
186 S->writeTo(Buf);
187 });
Sam Cleggc94d3932017-11-17 18:14:09 +0000188}
189
190// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000191// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000192// The default memory layout is as follows, from low to high.
193//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000194// - initialized data (starting at Config->GlobalBase)
195// - BSS data (not currently implemented in llvm)
196// - explicit stack (Config->ZStackSize)
197// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000198//
199// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000200// This can be useful since it means that stack overflow traps immediately
201// rather than overwriting global data, but also increases code size since all
202// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000203void Writer::layoutMemory() {
Sam Clegga0f095e2018-05-03 17:21:53 +0000204 uint32_t MemoryPtr = 0;
205
206 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000207 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000208 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000209 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
210 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
211 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000212 log("mem: stack size = " + Twine(Config->ZStackSize));
213 log("mem: stack base = " + Twine(MemoryPtr));
214 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000215 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
216 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000217 log("mem: stack top = " + Twine(MemoryPtr));
218 };
219
220 if (Config->StackFirst) {
221 PlaceStack();
222 } else {
223 MemoryPtr = Config->GlobalBase;
224 log("mem: global base = " + Twine(Config->GlobalBase));
225 }
226
Guanzhong Chene15dc952019-06-26 20:12:33 +0000227 if (WasmSym::GlobalBase)
228 WasmSym::GlobalBase->setVirtualAddress(Config->GlobalBase);
229
Sam Clegga0f095e2018-05-03 17:21:53 +0000230 uint32_t DataStart = MemoryPtr;
231
Sam Cleggf0d433d2018-02-02 22:59:56 +0000232 // Arbitrarily set __dso_handle handle to point to the start of the data
233 // segments.
234 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000235 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000236
Sam Clegg8fcf0122019-05-21 09:13:09 +0000237 Out.DylinkSec->MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000238 for (OutputSegment *Seg : Segments) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000239 Out.DylinkSec->MemAlign = std::max(Out.DylinkSec->MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000240 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000241 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000242 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
243 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000244 MemoryPtr += Seg->Size;
245 }
246
Sam Cleggf0d433d2018-02-02 22:59:56 +0000247 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000248 if (WasmSym::DataEnd)
249 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000250
Sam Clegga0f095e2018-05-03 17:21:53 +0000251 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000252
Sam Clegg2dad4e22018-11-15 18:15:54 +0000253 if (Config->Shared) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000254 Out.DylinkSec->MemSize = MemoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000255 return;
256 }
257
Sam Clegga0f095e2018-05-03 17:21:53 +0000258 if (!Config->StackFirst)
259 PlaceStack();
260
261 // Set `__heap_base` to directly follow the end of the stack or global data.
262 // The fact that this comes last means that a malloc/brk implementation
263 // can grow the heap at runtime.
Sam Clegg7d4ec5a2019-05-31 22:51:59 +0000264 log("mem: heap base = " + Twine(MemoryPtr));
265 if (WasmSym::HeapBase)
Sam Cleggf0d433d2018-02-02 22:59:56 +0000266 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000267
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000268 if (Config->InitialMemory != 0) {
269 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
270 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
271 if (MemoryPtr > Config->InitialMemory)
272 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
273 else
274 MemoryPtr = Config->InitialMemory;
275 }
Sam Clegg8fcf0122019-05-21 09:13:09 +0000276 Out.DylinkSec->MemSize = MemoryPtr;
277 Out.MemorySec->NumMemoryPages =
278 alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
279 log("mem: total pages = " + Twine(Out.MemorySec->NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000280
Thomas Lively06391f32019-03-29 20:43:49 +0000281 // Check max if explicitly supplied or required by shared memory
282 if (Config->MaxMemory != 0 || Config->SharedMemory) {
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000283 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
284 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
285 if (MemoryPtr > Config->MaxMemory)
286 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000287 Out.MemorySec->MaxMemoryPages = Config->MaxMemory / WasmPageSize;
288 log("mem: max pages = " + Twine(Out.MemorySec->MaxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000289 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000290}
291
Sam Clegg8fcf0122019-05-21 09:13:09 +0000292void Writer::addSection(OutputSection *Sec) {
293 if (!Sec->isNeeded())
294 return;
295 log("addSection: " + toString(*Sec));
296 Sec->SectionIndex = OutputSections.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000297 OutputSections.push_back(Sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000298}
299
Sam Clegg4bce63a2019-05-23 10:06:03 +0000300// If a section name is valid as a C identifier (which is rare because of
301// the leading '.'), linkers are expected to define __start_<secname> and
302// __stop_<secname> symbols. They are at beginning and end of the section,
303// respectively. This is not requested by the ELF standard, but GNU ld and
304// gold provide the feature, and used by many programs.
Sam Clegg15006462019-07-08 10:35:08 +0000305static void addStartStopSymbols(const OutputSegment *Seg) {
306 StringRef Name = Seg->Name;
Sam Clegg15006462019-07-08 10:35:08 +0000307 if (!isValidCIdentifier(Name))
Sam Clegg4bce63a2019-05-23 10:06:03 +0000308 return;
Sam Clegg51c2b992019-07-09 19:47:32 +0000309 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << Name << "\n");
Sam Clegg15006462019-07-08 10:35:08 +0000310 uint32_t Start = Seg->StartVA;
311 uint32_t Stop = Start + Seg->Size;
312 Symtab->addOptionalDataSymbol(Saver.save("__start_" + Name), Start);
313 Symtab->addOptionalDataSymbol(Saver.save("__stop_" + Name), Stop);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000314}
315
Sam Clegg8fcf0122019-05-21 09:13:09 +0000316void Writer::addSections() {
317 addSection(Out.DylinkSec);
318 addSection(Out.TypeSec);
319 addSection(Out.ImportSec);
320 addSection(Out.FunctionSec);
321 addSection(Out.TableSec);
322 addSection(Out.MemorySec);
323 addSection(Out.GlobalSec);
324 addSection(Out.EventSec);
325 addSection(Out.ExportSec);
326 addSection(Out.ElemSec);
327 addSection(Out.DataCountSec);
328
329 addSection(make<CodeSection>(Out.FunctionSec->InputFunctions));
330 addSection(make<DataSection>(Segments));
331
Sam Clegg80ba4382018-04-10 16:12:49 +0000332 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000333
Sam Clegg8fcf0122019-05-21 09:13:09 +0000334 addSection(Out.LinkingSec);
Sam Clegg35be7ff2019-05-24 13:28:27 +0000335 if (Config->EmitRelocs || Config->Relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000336 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000337 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000338
Sam Clegg8fcf0122019-05-21 09:13:09 +0000339 addSection(Out.NameSec);
340 addSection(Out.ProducersSec);
341 addSection(Out.TargetFeaturesSec);
342}
Sam Cleggc94d3932017-11-17 18:14:09 +0000343
Sam Clegg8fcf0122019-05-21 09:13:09 +0000344void Writer::finalizeSections() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000345 for (OutputSection *S : OutputSections) {
346 S->setOffset(FileSize);
347 S->finalizeContents();
348 FileSize += S->getSize();
349 }
350}
351
Sam Clegg8fcf0122019-05-21 09:13:09 +0000352void Writer::populateTargetFeatures() {
Thomas Lively86e73f52019-05-30 21:57:23 +0000353 StringMap<std::string> Used;
354 StringMap<std::string> Required;
355 StringMap<std::string> Disallowed;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000356
Thomas Lively82de51a2019-03-26 04:11:05 +0000357 // Only infer used features if user did not specify features
358 bool InferFeatures = !Config->Features.hasValue();
359
360 if (!InferFeatures) {
361 for (auto &Feature : Config->Features.getValue())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000362 Out.TargetFeaturesSec->Features.insert(Feature);
Thomas Lively82de51a2019-03-26 04:11:05 +0000363 // No need to read or check features
364 if (!Config->CheckFeatures)
365 return;
366 }
367
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000368 // Find the sets of used, required, and disallowed features
369 for (ObjFile *File : Symtab->ObjectFiles) {
Thomas Lively86e73f52019-05-30 21:57:23 +0000370 StringRef FileName(File->getName());
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000371 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
372 switch (Feature.Prefix) {
373 case WASM_FEATURE_PREFIX_USED:
Thomas Lively86e73f52019-05-30 21:57:23 +0000374 Used.insert({Feature.Name, FileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000375 break;
376 case WASM_FEATURE_PREFIX_REQUIRED:
Thomas Lively86e73f52019-05-30 21:57:23 +0000377 Used.insert({Feature.Name, FileName});
378 Required.insert({Feature.Name, FileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000379 break;
380 case WASM_FEATURE_PREFIX_DISALLOWED:
Thomas Lively86e73f52019-05-30 21:57:23 +0000381 Disallowed.insert({Feature.Name, FileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000382 break;
383 default:
384 error("Unrecognized feature policy prefix " +
385 std::to_string(Feature.Prefix));
386 }
387 }
388 }
389
Thomas Lively82de51a2019-03-26 04:11:05 +0000390 if (InferFeatures)
Thomas Lively86e73f52019-05-30 21:57:23 +0000391 Out.TargetFeaturesSec->Features.insert(Used.keys().begin(),
392 Used.keys().end());
Thomas Lively82de51a2019-03-26 04:11:05 +0000393
Thomas Lively86e73f52019-05-30 21:57:23 +0000394 if (Out.TargetFeaturesSec->Features.count("atomics") &&
395 !Config->SharedMemory) {
396 if (InferFeatures)
397 error(Twine("'atomics' feature is used by ") + Used["atomics"] +
398 ", so --shared-memory must be used");
399 else
400 error("'atomics' feature is used, so --shared-memory must be used");
401 }
Thomas Lively06391f32019-03-29 20:43:49 +0000402
Thomas Lively82de51a2019-03-26 04:11:05 +0000403 if (!Config->CheckFeatures)
404 return;
405
Thomas Lively06391f32019-03-29 20:43:49 +0000406 if (Disallowed.count("atomics") && Config->SharedMemory)
Thomas Lively86e73f52019-05-30 21:57:23 +0000407 error("'atomics' feature is disallowed by " + Disallowed["atomics"] +
408 ", so --shared-memory must not be used");
Thomas Lively06391f32019-03-29 20:43:49 +0000409
Thomas Lively6004d9a2019-07-03 22:04:54 +0000410 if (!Used.count("bulk-memory") && Config->PassiveSegments)
411 error("'bulk-memory' feature must be used in order to emit passive "
412 "segments");
413
Thomas Lively82de51a2019-03-26 04:11:05 +0000414 // Validate that used features are allowed in output
415 if (!InferFeatures) {
Thomas Lively86e73f52019-05-30 21:57:23 +0000416 for (auto &Feature : Used.keys()) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000417 if (!Out.TargetFeaturesSec->Features.count(Feature))
Thomas Lively86e73f52019-05-30 21:57:23 +0000418 error(Twine("Target feature '") + Feature + "' used by " +
419 Used[Feature] + " is not allowed.");
Thomas Lively82de51a2019-03-26 04:11:05 +0000420 }
421 }
422
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000423 // Validate the required and disallowed constraints for each file
424 for (ObjFile *File : Symtab->ObjectFiles) {
Thomas Lively86e73f52019-05-30 21:57:23 +0000425 StringRef FileName(File->getName());
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000426 SmallSet<std::string, 8> ObjectFeatures;
427 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
428 if (Feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
429 continue;
430 ObjectFeatures.insert(Feature.Name);
431 if (Disallowed.count(Feature.Name))
Thomas Lively86e73f52019-05-30 21:57:23 +0000432 error(Twine("Target feature '") + Feature.Name + "' used in " +
433 FileName + " is disallowed by " + Disallowed[Feature.Name] +
434 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000435 }
Thomas Lively86e73f52019-05-30 21:57:23 +0000436 for (auto &Feature : Required.keys()) {
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000437 if (!ObjectFeatures.count(Feature))
Thomas Lively86e73f52019-05-30 21:57:23 +0000438 error(Twine("Missing target feature '") + Feature + "' in " + FileName +
439 ", required by " + Required[Feature] +
440 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000441 }
442 }
443}
444
Sam Cleggc94d3932017-11-17 18:14:09 +0000445void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000446 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000447 if (!Sym->isUndefined())
448 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000449 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000450 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000451 if (!Sym->isLive())
452 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000453 if (!Sym->IsUsedInRegularObj)
454 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000455 // We don't generate imports for data symbols. They however can be imported
456 // as GOT entries.
457 if (isa<DataSymbol>(Sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000458 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000459
Nicola Zaghene7245b42018-05-15 13:36:20 +0000460 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000461 Out.ImportSec->addImport(Sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000462 }
463}
464
Sam Cleggd3052d52018-01-18 23:40:49 +0000465void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000466 if (Config->Relocatable)
467 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000468
Sam Cleggd6beb322018-05-10 18:10:34 +0000469 if (!Config->Relocatable && !Config->ImportMemory)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000470 Out.ExportSec->Exports.push_back(
471 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000472
473 if (!Config->Relocatable && Config->ExportTable)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000474 Out.ExportSec->Exports.push_back(
475 WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000476
Sam Clegg8fcf0122019-05-21 09:13:09 +0000477 unsigned FakeGlobalIndex =
Sam Cleggb9889bb2019-05-23 09:41:03 +0000478 Out.ImportSec->numImportedGlobals() + Out.GlobalSec->InputGlobals.size();
Sam Cleggd6beb322018-05-10 18:10:34 +0000479
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000480 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000481 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000482 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000483 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000484 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000485
Sam Cleggd6beb322018-05-10 18:10:34 +0000486 StringRef Name = Sym->getName();
487 WasmExport Export;
488 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
489 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
490 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000491 // TODO(sbc): Remove this check once to mutable global proposal is
492 // implement in all major browsers.
493 // See: https://github.com/WebAssembly/mutable-global
494 if (G->getGlobalType()->Mutable) {
495 // Only the __stack_pointer should ever be create as mutable.
496 assert(G == WasmSym::StackPointer);
497 continue;
498 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000499 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000500 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
501 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000502 } else {
503 auto *D = cast<DefinedData>(Sym);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000504 Out.GlobalSec->DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000505 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
506 }
507
Nicola Zaghene7245b42018-05-15 13:36:20 +0000508 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000509 Out.ExportSec->Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000510 }
Sam Clegg93102972018-02-23 05:08:53 +0000511}
512
Sam Clegg8fcf0122019-05-21 09:13:09 +0000513void Writer::populateSymtab() {
Sam Clegg35be7ff2019-05-24 13:28:27 +0000514 if (!Config->Relocatable && !Config->EmitRelocs)
Sam Clegg93102972018-02-23 05:08:53 +0000515 return;
516
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000517 for (Symbol *Sym : Symtab->getSymbols())
Sam Clegg35be7ff2019-05-24 13:28:27 +0000518 if (Sym->IsUsedInRegularObj && Sym->isLive())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000519 Out.LinkingSec->addToSymtab(Sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000520
521 for (ObjFile *File : Symtab->ObjectFiles) {
522 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
523 for (Symbol *Sym : File->getSymbols())
Sam Clegg35be7ff2019-05-24 13:28:27 +0000524 if (Sym->isLocal() && !isa<SectionSymbol>(Sym) && Sym->isLive())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000525 Out.LinkingSec->addToSymtab(Sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000526 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000527}
528
Sam Cleggc94d3932017-11-17 18:14:09 +0000529void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000530 // The output type section is the union of the following sets:
531 // 1. Any signature used in the TYPE relocation
532 // 2. The signatures of all imported functions
533 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000534 // 4. The signatures of all imported events
535 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000536
Sam Cleggc94d3932017-11-17 18:14:09 +0000537 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000538 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
539 for (uint32_t I = 0; I < Types.size(); I++)
540 if (File->TypeIsUsed[I])
Sam Clegg8fcf0122019-05-21 09:13:09 +0000541 File->TypeMap[I] = Out.TypeSec->registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000542 }
Sam Clegg50686852018-01-12 18:35:13 +0000543
Sam Clegg8fcf0122019-05-21 09:13:09 +0000544 for (const Symbol *Sym : Out.ImportSec->ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000545 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Sam Clegg8fcf0122019-05-21 09:13:09 +0000546 Out.TypeSec->registerType(*F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000547 else if (auto *E = dyn_cast<EventSymbol>(Sym))
Sam Clegg8fcf0122019-05-21 09:13:09 +0000548 Out.TypeSec->registerType(*E->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000549 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000550
Sam Clegg8fcf0122019-05-21 09:13:09 +0000551 for (const InputFunction *F : Out.FunctionSec->InputFunctions)
552 Out.TypeSec->registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000553
Sam Clegg8fcf0122019-05-21 09:13:09 +0000554 for (const InputEvent *E : Out.EventSec->InputEvents)
555 Out.TypeSec->registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000556}
557
Sam Clegg8fcf0122019-05-21 09:13:09 +0000558static void scanRelocations() {
559 for (ObjFile *File : Symtab->ObjectFiles) {
560 LLVM_DEBUG(dbgs() << "scanRelocations: " << File->getName() << "\n");
561 for (InputChunk *Chunk : File->Functions)
562 scanRelocations(Chunk);
563 for (InputChunk *Chunk : File->Segments)
564 scanRelocations(Chunk);
565 for (auto &P : File->CustomSections)
566 scanRelocations(P);
Sam Clegg632c21792019-03-16 01:18:12 +0000567 }
568}
569
Sam Clegg8d146bb2018-01-09 23:56:44 +0000570void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000571 // Seal the import section, since other index spaces such as function and
572 // global are effected by the number of imports.
573 Out.ImportSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000574
Nicholas Wilson5639da82018-03-12 15:44:07 +0000575 for (InputFunction *Func : Symtab->SyntheticFunctions)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000576 Out.FunctionSec->addFunction(Func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000577
Sam Clegg87e61922018-01-08 23:39:11 +0000578 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000579 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000580 for (InputFunction *Func : File->Functions)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000581 Out.FunctionSec->addFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000582 }
583
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000584 for (InputGlobal *Global : Symtab->SyntheticGlobals)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000585 Out.GlobalSec->addGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000586
587 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000588 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000589 for (InputGlobal *Global : File->Globals)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000590 Out.GlobalSec->addGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000591 }
Heejin Ahne915a712018-12-08 06:17:43 +0000592
Heejin Ahne915a712018-12-08 06:17:43 +0000593 for (ObjFile *File : Symtab->ObjectFiles) {
594 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
595 for (InputEvent *Event : File->Events)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000596 Out.EventSec->addEvent(Event);
Heejin Ahne915a712018-12-08 06:17:43 +0000597 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000598}
599
600static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000601 // With PIC code we currently only support a single data segment since
602 // we only have a single __memory_base to use as our base address.
603 if (Config->Pic)
Sam Clegg51c2b992019-07-09 19:47:32 +0000604 return ".data";
Sam Clegg66844762018-05-10 18:23:51 +0000605 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +0000606 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000607 if (Name.startswith(".text."))
608 return ".text";
609 if (Name.startswith(".data."))
610 return ".data";
611 if (Name.startswith(".bss."))
612 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +0000613 if (Name.startswith(".rodata."))
614 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 return Name;
616}
617
618void Writer::createOutputSegments() {
619 for (ObjFile *File : Symtab->ObjectFiles) {
620 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000621 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000622 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000623 StringRef Name = getOutputDataSegmentName(Segment->getName());
624 OutputSegment *&S = SegmentMap[Name];
625 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000626 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000627 S = make<OutputSegment>(Name, Segments.size());
Thomas Lively6004d9a2019-07-03 22:04:54 +0000628 if (Config->PassiveSegments)
629 S->InitFlags = WASM_SEGMENT_IS_PASSIVE;
Sam Cleggc94d3932017-11-17 18:14:09 +0000630 Segments.push_back(S);
631 }
632 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +0000633 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 }
635 }
636}
637
Thomas Lively6004d9a2019-07-03 22:04:54 +0000638static void CreateFunction(DefinedFunction *Func, StringRef BodyContent) {
639 std::string FunctionBody;
640 {
641 raw_string_ostream OS(FunctionBody);
642 writeUleb128(OS, BodyContent.size(), "function size");
643 OS << BodyContent;
644 }
645 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
646 cast<SyntheticFunction>(Func->Function)->setBody(Body);
647}
648
649void Writer::createInitMemoryFunction() {
650 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
651 std::string BodyContent;
652 {
653 raw_string_ostream OS(BodyContent);
654 writeUleb128(OS, 0, "num locals");
655
656 // initialize passive data segments
657 for (const OutputSegment *S : Segments) {
658 if (S->InitFlags & WASM_SEGMENT_IS_PASSIVE) {
659 // destination address
660 writeU8(OS, WASM_OPCODE_I32_CONST, "i32.const");
661 writeUleb128(OS, S->StartVA, "destination address");
662 // source segment offset
663 writeU8(OS, WASM_OPCODE_I32_CONST, "i32.const");
664 writeUleb128(OS, 0, "segment offset");
665 // memory region size
666 writeU8(OS, WASM_OPCODE_I32_CONST, "i32.const");
667 writeUleb128(OS, S->Size, "memory region size");
668 // memory.init instruction
669 writeU8(OS, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
670 writeUleb128(OS, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
671 writeUleb128(OS, S->Index, "segment index immediate");
672 writeU8(OS, 0, "memory index immediate");
673 // data.drop instruction
674 writeU8(OS, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
675 writeUleb128(OS, WASM_OPCODE_DATA_DROP, "DATA.DROP");
676 writeUleb128(OS, S->Index, "segment index immediate");
677 }
678 }
679 writeU8(OS, WASM_OPCODE_END, "END");
680 }
681
682 CreateFunction(WasmSym::InitMemory, BodyContent);
683}
684
Sam Clegg09137be2019-04-04 18:40:51 +0000685// For -shared (PIC) output, we create create a synthetic function which will
686// apply any relocations to the data segments on startup. This function is
Thomas Lively6004d9a2019-07-03 22:04:54 +0000687// called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
688// before any of the constructors run.
Sam Clegg09137be2019-04-04 18:40:51 +0000689void Writer::createApplyRelocationsFunction() {
690 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
691 // First write the body's contents to a string.
692 std::string BodyContent;
693 {
694 raw_string_ostream OS(BodyContent);
695 writeUleb128(OS, 0, "num locals");
696 for (const OutputSegment *Seg : Segments)
697 for (const InputSegment *InSeg : Seg->InputSegments)
698 InSeg->generateRelocationCode(OS);
699 writeU8(OS, WASM_OPCODE_END, "END");
700 }
701
Thomas Lively6004d9a2019-07-03 22:04:54 +0000702 CreateFunction(WasmSym::ApplyRelocs, BodyContent);
Sam Clegg09137be2019-04-04 18:40:51 +0000703}
Sam Clegg50686852018-01-12 18:35:13 +0000704
705// Create synthetic "__wasm_call_ctors" function based on ctor functions
706// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000707void Writer::createCallCtorsFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000708 if (!WasmSym::CallCtors->isLive())
709 return;
710
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000711 // First write the body's contents to a string.
712 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000713 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000714 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000715 writeUleb128(OS, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000716
717 if (Config->PassiveSegments) {
718 writeU8(OS, WASM_OPCODE_CALL, "CALL");
719 writeUleb128(OS, WasmSym::InitMemory->getFunctionIndex(),
720 "function index");
721 }
722
Sam Clegg09137be2019-04-04 18:40:51 +0000723 if (Config->Pic) {
724 writeU8(OS, WASM_OPCODE_CALL, "CALL");
725 writeUleb128(OS, WasmSym::ApplyRelocs->getFunctionIndex(),
726 "function index");
727 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000728
729 // Call constructors
Sam Clegg93102972018-02-23 05:08:53 +0000730 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg09137be2019-04-04 18:40:51 +0000731 writeU8(OS, WASM_OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000732 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000733 }
Sam Clegg09137be2019-04-04 18:40:51 +0000734 writeU8(OS, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000735 }
736
Thomas Lively6004d9a2019-07-03 22:04:54 +0000737 CreateFunction(WasmSym::CallCtors, BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000738}
739
740// Populate InitFunctions vector with init functions from all input objects.
741// This is then used either when creating the output linking section or to
742// synthesize the "__wasm_call_ctors" function.
743void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +0000744 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
745 return;
746
Sam Clegg50686852018-01-12 18:35:13 +0000747 for (ObjFile *File : Symtab->ObjectFiles) {
748 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000749 for (const WasmInitFunc &F : L.InitFunctions) {
750 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Cleggfd54fa52019-06-07 06:00:46 +0000751 // comdat exclusions can cause init functions be discarded.
752 if (Sym->isDiscarded())
753 continue;
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000754 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +0000755 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000756 error("invalid signature for init func: " + toString(*Sym));
757 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
758 }
Sam Clegg50686852018-01-12 18:35:13 +0000759 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000760
Sam Clegg50686852018-01-12 18:35:13 +0000761 // Sort in order of priority (lowest first) so that they are called
762 // in the correct order.
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000763 llvm::stable_sort(InitFunctions,
764 [](const WasmInitEntry &L, const WasmInitEntry &R) {
765 return L.Priority < R.Priority;
766 });
Sam Clegg50686852018-01-12 18:35:13 +0000767}
768
Sam Clegg8fcf0122019-05-21 09:13:09 +0000769void Writer::createSyntheticSections() {
770 Out.DylinkSec = make<DylinkSection>();
771 Out.TypeSec = make<TypeSection>();
772 Out.ImportSec = make<ImportSection>();
773 Out.FunctionSec = make<FunctionSection>();
774 Out.TableSec = make<TableSection>();
775 Out.MemorySec = make<MemorySection>();
776 Out.GlobalSec = make<GlobalSection>();
777 Out.EventSec = make<EventSection>();
778 Out.ExportSec = make<ExportSection>();
779 Out.ElemSec = make<ElemSection>(TableBase);
780 Out.DataCountSec = make<DataCountSection>(Segments.size());
781 Out.LinkingSec = make<LinkingSection>(InitFunctions, Segments);
782 Out.NameSec = make<NameSection>();
783 Out.ProducersSec = make<ProducersSection>();
784 Out.TargetFeaturesSec = make<TargetFeaturesSection>();
785}
786
Sam Cleggc94d3932017-11-17 18:14:09 +0000787void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000788 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +0000789 Config->GlobalBase = 0;
790
Sam Cleggbfb75342018-11-15 00:37:21 +0000791 // For PIC code the table base is assigned dynamically by the loader.
792 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
793 if (!Config->Pic)
794 TableBase = 1;
795
Sam Clegg8fcf0122019-05-21 09:13:09 +0000796 log("-- createOutputSegments");
797 createOutputSegments();
798 log("-- createSyntheticSections");
799 createSyntheticSections();
800 log("-- populateProducers");
801 populateProducers();
802 log("-- populateTargetFeatures");
803 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +0000804 log("-- calculateImports");
805 calculateImports();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000806 log("-- layoutMemory");
807 layoutMemory();
808
809 if (!Config->Relocatable) {
810 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
811 // This has to be done after memory layout is performed.
812 for (const OutputSegment *Seg : Segments)
Sam Clegg15006462019-07-08 10:35:08 +0000813 addStartStopSymbols(Seg);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000814 }
815
Sam Cleggb9889bb2019-05-23 09:41:03 +0000816 log("-- scanRelocations");
817 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000818 log("-- assignIndexes");
819 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000820 log("-- calculateInitFunctions");
821 calculateInitFunctions();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000822
Sam Clegg7804dbd2019-05-21 10:07:30 +0000823 if (!Config->Relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000824 // Create linker synthesized functions
Thomas Lively6004d9a2019-07-03 22:04:54 +0000825 if (Config->PassiveSegments)
826 createInitMemoryFunction();
Sam Clegg09137be2019-04-04 18:40:51 +0000827 if (Config->Pic)
828 createApplyRelocationsFunction();
829 createCallCtorsFunction();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000830
831 // Make sure we have resolved all symbols.
832 if (!Config->AllowUndefined)
833 Symtab->reportRemainingUndefines();
834
835 if (errorCount())
836 return;
Sam Clegg09137be2019-04-04 18:40:51 +0000837 }
Sam Clegg4bce63a2019-05-23 10:06:03 +0000838
839 log("-- calculateTypes");
840 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000841 log("-- calculateExports");
842 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +0000843 log("-- calculateCustomSections");
844 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000845 log("-- populateSymtab");
846 populateSymtab();
847 log("-- addSections");
848 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000849
850 if (errorHandler().Verbose) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000851 log("Defined Functions: " + Twine(Out.FunctionSec->InputFunctions.size()));
852 log("Defined Globals : " + Twine(Out.GlobalSec->InputGlobals.size()));
853 log("Defined Events : " + Twine(Out.EventSec->InputEvents.size()));
Sam Cleggb9889bb2019-05-23 09:41:03 +0000854 log("Function Imports : " + Twine(Out.ImportSec->numImportedFunctions()));
855 log("Global Imports : " + Twine(Out.ImportSec->numImportedGlobals()));
856 log("Event Imports : " + Twine(Out.ImportSec->numImportedEvents()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000857 for (ObjFile *File : Symtab->ObjectFiles)
858 File->dumpInfo();
859 }
860
Sam Cleggc94d3932017-11-17 18:14:09 +0000861 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000862 log("-- finalizeSections");
863 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000864
865 log("-- openFile");
866 openFile();
867 if (errorCount())
868 return;
869
870 writeHeader();
871
872 log("-- writeSections");
873 writeSections();
874 if (errorCount())
875 return;
876
877 if (Error E = Buffer->commit())
878 fatal("failed to write the output file: " + toString(std::move(E)));
879}
880
881// Open a result file.
882void Writer::openFile() {
883 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000884
885 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
886 FileOutputBuffer::create(Config->OutputFile, FileSize,
887 FileOutputBuffer::F_executable);
888
889 if (!BufferOrErr)
890 error("failed to open " + Config->OutputFile + ": " +
891 toString(BufferOrErr.takeError()));
892 else
893 Buffer = std::move(*BufferOrErr);
894}
895
896void Writer::createHeader() {
897 raw_string_ostream OS(Header);
898 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
899 writeU32(OS, WasmVersion, "wasm version");
900 OS.flush();
901 FileSize += Header.size();
902}
903
904void lld::wasm::writeResult() { Writer().run(); }