blob: 01dbd82dc3549b9268195245799d33a9fb4c7cda [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
Sam Clegg09137be2019-04-04 18:40:51 +000057 void createApplyRelocationsFunction();
58 void createCallCtorsFunction();
59
Sam Clegg8d146bb2018-01-09 23:56:44 +000060 void assignIndexes();
Sam Clegg8fcf0122019-05-21 09:13:09 +000061 void populateSymtab();
62 void populateProducers();
63 void populateTargetFeatures();
64 void calculateInitFunctions();
Sam Cleggc94d3932017-11-17 18:14:09 +000065 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000066 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000067 void calculateCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000068 void calculateTypes();
69 void createOutputSegments();
70 void layoutMemory();
71 void createHeader();
Sam Cleggc94d3932017-11-17 18:14:09 +000072
Sam Clegg8fcf0122019-05-21 09:13:09 +000073 void addSection(OutputSection *Sec);
74
75 void addSections();
Sam Clegg80ba4382018-04-10 16:12:49 +000076 void createCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +000077 void createSyntheticSections();
78 void finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000079
80 // Custom sections
81 void createRelocSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000082
83 void writeHeader();
84 void writeSections();
85
86 uint64_t FileSize = 0;
Sam Cleggbfb75342018-11-15 00:37:21 +000087 uint32_t TableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000088
Sam Clegg93102972018-02-23 05:08:53 +000089 std::vector<WasmInitEntry> InitFunctions;
Sam Clegg80ba4382018-04-10 16:12:49 +000090 llvm::StringMap<std::vector<InputSection *>> CustomSectionMapping;
91
Sam Cleggc94d3932017-11-17 18:14:09 +000092 // Elements that are used to construct the final output
93 std::string Header;
94 std::vector<OutputSection *> OutputSections;
95
96 std::unique_ptr<FileOutputBuffer> Buffer;
97
98 std::vector<OutputSegment *> Segments;
99 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
100};
101
102} // anonymous namespace
103
Sam Cleggd177ab22018-05-04 23:14:42 +0000104void Writer::calculateCustomSections() {
105 log("calculateCustomSections");
106 bool StripDebug = Config->StripDebug || Config->StripAll;
107 for (ObjFile *File : Symtab->ObjectFiles) {
108 for (InputSection *Section : File->CustomSections) {
109 StringRef Name = Section->getName();
110 // These custom sections are known the linker and synthesized rather than
111 // blindly copied
Thomas Lively2a0868f2019-01-17 02:29:41 +0000112 if (Name == "linking" || Name == "name" || Name == "producers" ||
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000113 Name == "target_features" || Name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000114 continue;
115 // .. or it is a debug section
116 if (StripDebug && Name.startswith(".debug_"))
117 continue;
118 CustomSectionMapping[Name].push_back(Section);
119 }
120 }
121}
122
Sam Clegg80ba4382018-04-10 16:12:49 +0000123void Writer::createCustomSections() {
124 log("createCustomSections");
Sam Clegg80ba4382018-04-10 16:12:49 +0000125 for (auto &Pair : CustomSectionMapping) {
126 StringRef Name = Pair.first();
Nicola Zaghene7245b42018-05-15 13:36:20 +0000127 LLVM_DEBUG(dbgs() << "createCustomSection: " << Name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000128
129 OutputSection *Sec = make<CustomSection>(Name, Pair.second);
130 if (Config->Relocatable) {
131 auto *Sym = make<OutputSectionSymbol>(Sec);
132 Out.LinkingSec->addToSymtab(Sym);
133 Sec->SectionSym = Sym;
134 }
135 addSection(Sec);
Sam Clegg80ba4382018-04-10 16:12:49 +0000136 }
137}
138
Sam Cleggd451da12017-12-19 19:56:27 +0000139// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000140// These are only created when relocatable output is requested.
141void Writer::createRelocSections() {
142 log("createRelocSections");
143 // Don't use iterator here since we are adding to OutputSection
144 size_t OrigSize = OutputSections.size();
Rui Ueyamaffa650a2018-04-24 23:09:57 +0000145 for (size_t I = 0; I < OrigSize; I++) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000146 LLVM_DEBUG(dbgs() << "check section " << I << "\n");
147 OutputSection *Sec = OutputSections[I];
148
149 // Count the number of needed sections.
150 uint32_t Count = Sec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000151 if (!Count)
152 continue;
153
Rui Ueyama37254062018-02-28 00:01:31 +0000154 StringRef Name;
Sam Clegg8fcf0122019-05-21 09:13:09 +0000155 if (Sec->Type == WASM_SEC_DATA)
Rui Ueyama37254062018-02-28 00:01:31 +0000156 Name = "reloc.DATA";
Sam Clegg8fcf0122019-05-21 09:13:09 +0000157 else if (Sec->Type == WASM_SEC_CODE)
Rui Ueyama37254062018-02-28 00:01:31 +0000158 Name = "reloc.CODE";
Sam Clegg8fcf0122019-05-21 09:13:09 +0000159 else if (Sec->Type == WASM_SEC_CUSTOM)
160 Name = Saver.save("reloc." + Sec->Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000161 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000162 llvm_unreachable(
163 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000164
Sam Clegg8fcf0122019-05-21 09:13:09 +0000165 addSection(make<RelocSection>(Name, Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000166 }
167}
168
Sam Clegg8fcf0122019-05-21 09:13:09 +0000169void Writer::populateProducers() {
Thomas Lively2a0868f2019-01-17 02:29:41 +0000170 for (ObjFile *File : Symtab->ObjectFiles) {
171 const WasmProducerInfo &Info = File->getWasmObj()->getProducerInfo();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000172 Out.ProducersSec->addInfo(Info);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000173 }
174}
175
Sam Cleggc94d3932017-11-17 18:14:09 +0000176void Writer::writeHeader() {
177 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
178}
179
180void Writer::writeSections() {
181 uint8_t *Buf = Buffer->getBufferStart();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000182 parallelForEach(OutputSections, [Buf](OutputSection *S) {
183 assert(S->isNeeded());
184 S->writeTo(Buf);
185 });
Sam Cleggc94d3932017-11-17 18:14:09 +0000186}
187
188// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000189// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000190// The default memory layout is as follows, from low to high.
191//
Sam Cleggf0d433d2018-02-02 22:59:56 +0000192// - initialized data (starting at Config->GlobalBase)
193// - BSS data (not currently implemented in llvm)
194// - explicit stack (Config->ZStackSize)
195// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000196//
197// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000198// This can be useful since it means that stack overflow traps immediately
199// rather than overwriting global data, but also increases code size since all
200// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000201void Writer::layoutMemory() {
Sam Clegga0f095e2018-05-03 17:21:53 +0000202 uint32_t MemoryPtr = 0;
203
204 auto PlaceStack = [&]() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000205 if (Config->Relocatable || Config->Shared)
Sam Clegga0f095e2018-05-03 17:21:53 +0000206 return;
Heejin Ahna1cc4ea2019-02-04 19:13:46 +0000207 MemoryPtr = alignTo(MemoryPtr, StackAlignment);
208 if (Config->ZStackSize != alignTo(Config->ZStackSize, StackAlignment))
209 error("stack size must be " + Twine(StackAlignment) + "-byte aligned");
Sam Clegga0f095e2018-05-03 17:21:53 +0000210 log("mem: stack size = " + Twine(Config->ZStackSize));
211 log("mem: stack base = " + Twine(MemoryPtr));
212 MemoryPtr += Config->ZStackSize;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000213 auto *SP = cast<DefinedGlobal>(WasmSym::StackPointer);
214 SP->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000215 log("mem: stack top = " + Twine(MemoryPtr));
216 };
217
218 if (Config->StackFirst) {
219 PlaceStack();
220 } else {
221 MemoryPtr = Config->GlobalBase;
222 log("mem: global base = " + Twine(Config->GlobalBase));
223 }
224
225 uint32_t DataStart = MemoryPtr;
226
Sam Cleggf0d433d2018-02-02 22:59:56 +0000227 // Arbitrarily set __dso_handle handle to point to the start of the data
228 // segments.
229 if (WasmSym::DsoHandle)
Sam Clegga0f095e2018-05-03 17:21:53 +0000230 WasmSym::DsoHandle->setVirtualAddress(DataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000231
Sam Clegg8fcf0122019-05-21 09:13:09 +0000232 Out.DylinkSec->MemAlign = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000233 for (OutputSegment *Seg : Segments) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000234 Out.DylinkSec->MemAlign = std::max(Out.DylinkSec->MemAlign, Seg->Alignment);
Sam Clegg622ad042019-01-17 22:09:09 +0000235 MemoryPtr = alignTo(MemoryPtr, 1ULL << Seg->Alignment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000236 Seg->StartVA = MemoryPtr;
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000237 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", Seg->Name,
238 MemoryPtr, Seg->Size, Seg->Alignment));
Sam Cleggc94d3932017-11-17 18:14:09 +0000239 MemoryPtr += Seg->Size;
240 }
241
Sam Cleggf0d433d2018-02-02 22:59:56 +0000242 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000243 if (WasmSym::DataEnd)
244 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000245
Sam Clegga0f095e2018-05-03 17:21:53 +0000246 log("mem: static data = " + Twine(MemoryPtr - DataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000247
Sam Clegg2dad4e22018-11-15 18:15:54 +0000248 if (Config->Shared) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000249 Out.DylinkSec->MemSize = MemoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000250 return;
251 }
252
Sam Clegga0f095e2018-05-03 17:21:53 +0000253 if (!Config->StackFirst)
254 PlaceStack();
255
256 // Set `__heap_base` to directly follow the end of the stack or global data.
257 // The fact that this comes last means that a malloc/brk implementation
258 // can grow the heap at runtime.
Sam Cleggc94d3932017-11-17 18:14:09 +0000259 if (!Config->Relocatable) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000260 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Nicholas Wilsona06a3552018-03-14 13:50:20 +0000261 log("mem: heap base = " + Twine(MemoryPtr));
Sam Cleggc94d3932017-11-17 18:14:09 +0000262 }
263
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000264 if (Config->InitialMemory != 0) {
265 if (Config->InitialMemory != alignTo(Config->InitialMemory, WasmPageSize))
266 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
267 if (MemoryPtr > Config->InitialMemory)
268 error("initial memory too small, " + Twine(MemoryPtr) + " bytes needed");
269 else
270 MemoryPtr = Config->InitialMemory;
271 }
Sam Clegg8fcf0122019-05-21 09:13:09 +0000272 Out.DylinkSec->MemSize = MemoryPtr;
273 Out.MemorySec->NumMemoryPages =
274 alignTo(MemoryPtr, WasmPageSize) / WasmPageSize;
275 log("mem: total pages = " + Twine(Out.MemorySec->NumMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000276
Thomas Lively06391f32019-03-29 20:43:49 +0000277 // Check max if explicitly supplied or required by shared memory
278 if (Config->MaxMemory != 0 || Config->SharedMemory) {
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000279 if (Config->MaxMemory != alignTo(Config->MaxMemory, WasmPageSize))
280 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
281 if (MemoryPtr > Config->MaxMemory)
282 error("maximum memory too small, " + Twine(MemoryPtr) + " bytes needed");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000283 Out.MemorySec->MaxMemoryPages = Config->MaxMemory / WasmPageSize;
284 log("mem: max pages = " + Twine(Out.MemorySec->MaxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000285 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000286}
287
Sam Clegg8fcf0122019-05-21 09:13:09 +0000288void Writer::addSection(OutputSection *Sec) {
289 if (!Sec->isNeeded())
290 return;
291 log("addSection: " + toString(*Sec));
292 Sec->SectionIndex = OutputSections.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000293 OutputSections.push_back(Sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000294}
295
Sam Clegg8fcf0122019-05-21 09:13:09 +0000296void Writer::addSections() {
297 addSection(Out.DylinkSec);
298 addSection(Out.TypeSec);
299 addSection(Out.ImportSec);
300 addSection(Out.FunctionSec);
301 addSection(Out.TableSec);
302 addSection(Out.MemorySec);
303 addSection(Out.GlobalSec);
304 addSection(Out.EventSec);
305 addSection(Out.ExportSec);
306 addSection(Out.ElemSec);
307 addSection(Out.DataCountSec);
308
309 addSection(make<CodeSection>(Out.FunctionSec->InputFunctions));
310 addSection(make<DataSection>(Segments));
311
Sam Clegg80ba4382018-04-10 16:12:49 +0000312 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000313
Sam Clegg8fcf0122019-05-21 09:13:09 +0000314 addSection(Out.LinkingSec);
Sam Clegg99eb42c2018-02-27 23:58:03 +0000315 if (Config->Relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000316 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000317 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000318
Sam Clegg8fcf0122019-05-21 09:13:09 +0000319 addSection(Out.NameSec);
320 addSection(Out.ProducersSec);
321 addSection(Out.TargetFeaturesSec);
322}
Sam Cleggc94d3932017-11-17 18:14:09 +0000323
Sam Clegg8fcf0122019-05-21 09:13:09 +0000324void Writer::finalizeSections() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000325 for (OutputSection *S : OutputSections) {
326 S->setOffset(FileSize);
327 S->finalizeContents();
328 FileSize += S->getSize();
329 }
330}
331
Sam Clegg8fcf0122019-05-21 09:13:09 +0000332void Writer::populateTargetFeatures() {
Thomas Lively82de51a2019-03-26 04:11:05 +0000333 SmallSet<std::string, 8> Used;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000334 SmallSet<std::string, 8> Required;
335 SmallSet<std::string, 8> Disallowed;
336
Thomas Lively82de51a2019-03-26 04:11:05 +0000337 // Only infer used features if user did not specify features
338 bool InferFeatures = !Config->Features.hasValue();
339
340 if (!InferFeatures) {
341 for (auto &Feature : Config->Features.getValue())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000342 Out.TargetFeaturesSec->Features.insert(Feature);
Thomas Lively82de51a2019-03-26 04:11:05 +0000343 // No need to read or check features
344 if (!Config->CheckFeatures)
345 return;
346 }
347
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000348 // Find the sets of used, required, and disallowed features
349 for (ObjFile *File : Symtab->ObjectFiles) {
350 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
351 switch (Feature.Prefix) {
352 case WASM_FEATURE_PREFIX_USED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000353 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000354 break;
355 case WASM_FEATURE_PREFIX_REQUIRED:
Thomas Lively82de51a2019-03-26 04:11:05 +0000356 Used.insert(Feature.Name);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000357 Required.insert(Feature.Name);
358 break;
359 case WASM_FEATURE_PREFIX_DISALLOWED:
360 Disallowed.insert(Feature.Name);
361 break;
362 default:
363 error("Unrecognized feature policy prefix " +
364 std::to_string(Feature.Prefix));
365 }
366 }
367 }
368
Thomas Lively82de51a2019-03-26 04:11:05 +0000369 if (InferFeatures)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000370 Out.TargetFeaturesSec->Features.insert(Used.begin(), Used.end());
Thomas Lively82de51a2019-03-26 04:11:05 +0000371
Sam Clegg8fcf0122019-05-21 09:13:09 +0000372 if (Out.TargetFeaturesSec->Features.count("atomics") && !Config->SharedMemory)
Thomas Lively06391f32019-03-29 20:43:49 +0000373 error("'atomics' feature is used, so --shared-memory must be used");
374
Thomas Lively82de51a2019-03-26 04:11:05 +0000375 if (!Config->CheckFeatures)
376 return;
377
Thomas Lively06391f32019-03-29 20:43:49 +0000378 if (Disallowed.count("atomics") && Config->SharedMemory)
379 error(
380 "'atomics' feature is disallowed, so --shared-memory must not be used");
381
Thomas Lively82de51a2019-03-26 04:11:05 +0000382 // Validate that used features are allowed in output
383 if (!InferFeatures) {
384 for (auto &Feature : Used) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000385 if (!Out.TargetFeaturesSec->Features.count(Feature))
Thomas Lively82de51a2019-03-26 04:11:05 +0000386 error(Twine("Target feature '") + Feature + "' is not allowed.");
387 }
388 }
389
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000390 // Validate the required and disallowed constraints for each file
391 for (ObjFile *File : Symtab->ObjectFiles) {
392 SmallSet<std::string, 8> ObjectFeatures;
393 for (auto &Feature : File->getWasmObj()->getTargetFeatures()) {
394 if (Feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
395 continue;
396 ObjectFeatures.insert(Feature.Name);
397 if (Disallowed.count(Feature.Name))
Thomas Lively82de51a2019-03-26 04:11:05 +0000398 error(Twine("Target feature '") + Feature.Name +
399 "' is disallowed. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000400 }
401 for (auto &Feature : Required) {
402 if (!ObjectFeatures.count(Feature))
Thomas Lively82de51a2019-03-26 04:11:05 +0000403 error(Twine("Missing required target feature '") + Feature +
404 "'. Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000405 }
406 }
407}
408
Sam Cleggc94d3932017-11-17 18:14:09 +0000409void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000410 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000411 if (!Sym->isUndefined())
412 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000413 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000414 continue;
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000415 if (!Sym->isLive())
416 continue;
Sam Cleggc729c1b2018-05-30 18:07:52 +0000417 if (!Sym->IsUsedInRegularObj)
418 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000419 // We don't generate imports for data symbols. They however can be imported
420 // as GOT entries.
421 if (isa<DataSymbol>(Sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000422 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000423
Nicola Zaghene7245b42018-05-15 13:36:20 +0000424 LLVM_DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000425 Out.ImportSec->addImport(Sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000426 }
427}
428
Sam Cleggd3052d52018-01-18 23:40:49 +0000429void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000430 if (Config->Relocatable)
431 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000432
Sam Cleggd6beb322018-05-10 18:10:34 +0000433 if (!Config->Relocatable && !Config->ImportMemory)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000434 Out.ExportSec->Exports.push_back(
435 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000436
437 if (!Config->Relocatable && Config->ExportTable)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000438 Out.ExportSec->Exports.push_back(
439 WasmExport{FunctionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000440
Sam Clegg8fcf0122019-05-21 09:13:09 +0000441 unsigned FakeGlobalIndex =
Sam Cleggb9889bb2019-05-23 09:41:03 +0000442 Out.ImportSec->numImportedGlobals() + Out.GlobalSec->InputGlobals.size();
Sam Cleggd6beb322018-05-10 18:10:34 +0000443
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000444 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggce004bf2018-06-28 17:04:58 +0000445 if (!Sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000446 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000447 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000448 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000449
Sam Cleggd6beb322018-05-10 18:10:34 +0000450 StringRef Name = Sym->getName();
451 WasmExport Export;
452 if (auto *F = dyn_cast<DefinedFunction>(Sym)) {
453 Export = {Name, WASM_EXTERNAL_FUNCTION, F->getFunctionIndex()};
454 } else if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000455 // TODO(sbc): Remove this check once to mutable global proposal is
456 // implement in all major browsers.
457 // See: https://github.com/WebAssembly/mutable-global
458 if (G->getGlobalType()->Mutable) {
459 // Only the __stack_pointer should ever be create as mutable.
460 assert(G == WasmSym::StackPointer);
461 continue;
462 }
Sam Cleggd6beb322018-05-10 18:10:34 +0000463 Export = {Name, WASM_EXTERNAL_GLOBAL, G->getGlobalIndex()};
Heejin Ahne915a712018-12-08 06:17:43 +0000464 } else if (auto *E = dyn_cast<DefinedEvent>(Sym)) {
465 Export = {Name, WASM_EXTERNAL_EVENT, E->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000466 } else {
467 auto *D = cast<DefinedData>(Sym);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000468 Out.GlobalSec->DefinedFakeGlobals.emplace_back(D);
Sam Cleggd6beb322018-05-10 18:10:34 +0000469 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
470 }
471
Nicola Zaghene7245b42018-05-15 13:36:20 +0000472 LLVM_DEBUG(dbgs() << "Export: " << Name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000473 Out.ExportSec->Exports.push_back(Export);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000474 }
Sam Clegg93102972018-02-23 05:08:53 +0000475}
476
Sam Clegg8fcf0122019-05-21 09:13:09 +0000477void Writer::populateSymtab() {
Sam Clegg93102972018-02-23 05:08:53 +0000478 if (!Config->Relocatable)
479 return;
480
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000481 for (Symbol *Sym : Symtab->getSymbols())
Sam Cleggd15a41542019-03-08 21:10:48 +0000482 if (Sym->IsUsedInRegularObj)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000483 Out.LinkingSec->addToSymtab(Sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000484
485 for (ObjFile *File : Symtab->ObjectFiles) {
486 LLVM_DEBUG(dbgs() << "Local symtab entries: " << File->getName() << "\n");
487 for (Symbol *Sym : File->getSymbols())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000488 if (Sym->isLocal() && !isa<SectionSymbol>(Sym))
489 Out.LinkingSec->addToSymtab(Sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000490 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000491}
492
Sam Cleggc94d3932017-11-17 18:14:09 +0000493void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000494 // The output type section is the union of the following sets:
495 // 1. Any signature used in the TYPE relocation
496 // 2. The signatures of all imported functions
497 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000498 // 4. The signatures of all imported events
499 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000500
Sam Cleggc94d3932017-11-17 18:14:09 +0000501 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000502 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
503 for (uint32_t I = 0; I < Types.size(); I++)
504 if (File->TypeIsUsed[I])
Sam Clegg8fcf0122019-05-21 09:13:09 +0000505 File->TypeMap[I] = Out.TypeSec->registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000506 }
Sam Clegg50686852018-01-12 18:35:13 +0000507
Sam Clegg8fcf0122019-05-21 09:13:09 +0000508 for (const Symbol *Sym : Out.ImportSec->ImportedSymbols) {
Sam Clegg93102972018-02-23 05:08:53 +0000509 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
Sam Clegg8fcf0122019-05-21 09:13:09 +0000510 Out.TypeSec->registerType(*F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000511 else if (auto *E = dyn_cast<EventSymbol>(Sym))
Sam Clegg8fcf0122019-05-21 09:13:09 +0000512 Out.TypeSec->registerType(*E->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000513 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000514
Sam Clegg8fcf0122019-05-21 09:13:09 +0000515 for (const InputFunction *F : Out.FunctionSec->InputFunctions)
516 Out.TypeSec->registerType(F->Signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000517
Sam Clegg8fcf0122019-05-21 09:13:09 +0000518 for (const InputEvent *E : Out.EventSec->InputEvents)
519 Out.TypeSec->registerType(E->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000520}
521
Sam Clegg8fcf0122019-05-21 09:13:09 +0000522static void scanRelocations() {
523 for (ObjFile *File : Symtab->ObjectFiles) {
524 LLVM_DEBUG(dbgs() << "scanRelocations: " << File->getName() << "\n");
525 for (InputChunk *Chunk : File->Functions)
526 scanRelocations(Chunk);
527 for (InputChunk *Chunk : File->Segments)
528 scanRelocations(Chunk);
529 for (auto &P : File->CustomSections)
530 scanRelocations(P);
Sam Clegg632c21792019-03-16 01:18:12 +0000531 }
532}
533
Sam Clegg8d146bb2018-01-09 23:56:44 +0000534void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000535 // Seal the import section, since other index spaces such as function and
536 // global are effected by the number of imports.
537 Out.ImportSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000538
Nicholas Wilson5639da82018-03-12 15:44:07 +0000539 for (InputFunction *Func : Symtab->SyntheticFunctions)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000540 Out.FunctionSec->addFunction(Func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000541
Sam Clegg87e61922018-01-08 23:39:11 +0000542 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000543 LLVM_DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000544 for (InputFunction *Func : File->Functions)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000545 Out.FunctionSec->addFunction(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000546 }
547
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000548 for (InputGlobal *Global : Symtab->SyntheticGlobals)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000549 Out.GlobalSec->addGlobal(Global);
Sam Clegg93102972018-02-23 05:08:53 +0000550
551 for (ObjFile *File : Symtab->ObjectFiles) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000552 LLVM_DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000553 for (InputGlobal *Global : File->Globals)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000554 Out.GlobalSec->addGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000555 }
Heejin Ahne915a712018-12-08 06:17:43 +0000556
Heejin Ahne915a712018-12-08 06:17:43 +0000557 for (ObjFile *File : Symtab->ObjectFiles) {
558 LLVM_DEBUG(dbgs() << "Events: " << File->getName() << "\n");
559 for (InputEvent *Event : File->Events)
Sam Clegg8fcf0122019-05-21 09:13:09 +0000560 Out.EventSec->addEvent(Event);
Heejin Ahne915a712018-12-08 06:17:43 +0000561 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000562}
563
564static StringRef getOutputDataSegmentName(StringRef Name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000565 // With PIC code we currently only support a single data segment since
566 // we only have a single __memory_base to use as our base address.
567 if (Config->Pic)
568 return "data";
Sam Clegg66844762018-05-10 18:23:51 +0000569 if (!Config->MergeDataSegments)
Sam Cleggc94d3932017-11-17 18:14:09 +0000570 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000571 if (Name.startswith(".text."))
572 return ".text";
573 if (Name.startswith(".data."))
574 return ".data";
575 if (Name.startswith(".bss."))
576 return ".bss";
Sam Clegg57694c52018-08-08 18:02:55 +0000577 if (Name.startswith(".rodata."))
578 return ".rodata";
Sam Cleggc94d3932017-11-17 18:14:09 +0000579 return Name;
580}
581
582void Writer::createOutputSegments() {
583 for (ObjFile *File : Symtab->ObjectFiles) {
584 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000585 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000586 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000587 StringRef Name = getOutputDataSegmentName(Segment->getName());
588 OutputSegment *&S = SegmentMap[Name];
589 if (S == nullptr) {
Nicola Zaghene7245b42018-05-15 13:36:20 +0000590 LLVM_DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000591 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000592 Segments.push_back(S);
593 }
594 S->addInputSegment(Segment);
Nicola Zaghene7245b42018-05-15 13:36:20 +0000595 LLVM_DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000596 }
597 }
598}
599
Sam Clegg09137be2019-04-04 18:40:51 +0000600// For -shared (PIC) output, we create create a synthetic function which will
601// apply any relocations to the data segments on startup. This function is
602// called __wasm_apply_relocs and is added at the very beginning of
603// __wasm_call_ctors before any of the constructors run.
604void Writer::createApplyRelocationsFunction() {
605 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
606 // First write the body's contents to a string.
607 std::string BodyContent;
608 {
609 raw_string_ostream OS(BodyContent);
610 writeUleb128(OS, 0, "num locals");
611 for (const OutputSegment *Seg : Segments)
612 for (const InputSegment *InSeg : Seg->InputSegments)
613 InSeg->generateRelocationCode(OS);
614 writeU8(OS, WASM_OPCODE_END, "END");
615 }
616
617 // Once we know the size of the body we can create the final function body
618 std::string FunctionBody;
619 {
620 raw_string_ostream OS(FunctionBody);
621 writeUleb128(OS, BodyContent.size(), "function size");
622 OS << BodyContent;
623 }
624
625 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
626 cast<SyntheticFunction>(WasmSym::ApplyRelocs->Function)->setBody(Body);
627}
Sam Clegg50686852018-01-12 18:35:13 +0000628
629// Create synthetic "__wasm_call_ctors" function based on ctor functions
630// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000631void Writer::createCallCtorsFunction() {
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000632 if (!WasmSym::CallCtors->isLive())
633 return;
634
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000635 // First write the body's contents to a string.
636 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000637 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000638 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000639 writeUleb128(OS, 0, "num locals");
Sam Clegg09137be2019-04-04 18:40:51 +0000640 if (Config->Pic) {
641 writeU8(OS, WASM_OPCODE_CALL, "CALL");
642 writeUleb128(OS, WasmSym::ApplyRelocs->getFunctionIndex(),
643 "function index");
644 }
Sam Clegg93102972018-02-23 05:08:53 +0000645 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg09137be2019-04-04 18:40:51 +0000646 writeU8(OS, WASM_OPCODE_CALL, "CALL");
Sam Clegge3f3ccf2018-03-12 19:56:23 +0000647 writeUleb128(OS, F.Sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000648 }
Sam Clegg09137be2019-04-04 18:40:51 +0000649 writeU8(OS, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000650 }
651
652 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000653 std::string FunctionBody;
654 {
655 raw_string_ostream OS(FunctionBody);
656 writeUleb128(OS, BodyContent.size(), "function size");
657 OS << BodyContent;
658 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000659
Sam Cleggea656472018-10-22 08:35:39 +0000660 ArrayRef<uint8_t> Body = arrayRefFromStringRef(Saver.save(FunctionBody));
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000661 cast<SyntheticFunction>(WasmSym::CallCtors->Function)->setBody(Body);
Sam Clegg50686852018-01-12 18:35:13 +0000662}
663
664// Populate InitFunctions vector with init functions from all input objects.
665// This is then used either when creating the output linking section or to
666// synthesize the "__wasm_call_ctors" function.
667void Writer::calculateInitFunctions() {
Sam Clegg61f13b32019-03-02 04:55:02 +0000668 if (!Config->Relocatable && !WasmSym::CallCtors->isLive())
669 return;
670
Sam Clegg50686852018-01-12 18:35:13 +0000671 for (ObjFile *File : Symtab->ObjectFiles) {
672 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000673 for (const WasmInitFunc &F : L.InitFunctions) {
674 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000675 assert(Sym->isLive());
Heejin Ahne915a712018-12-08 06:17:43 +0000676 if (*Sym->Signature != WasmSignature{{}, {}})
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000677 error("invalid signature for init func: " + toString(*Sym));
678 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
679 }
Sam Clegg50686852018-01-12 18:35:13 +0000680 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000681
Sam Clegg50686852018-01-12 18:35:13 +0000682 // Sort in order of priority (lowest first) so that they are called
683 // in the correct order.
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000684 llvm::stable_sort(InitFunctions,
685 [](const WasmInitEntry &L, const WasmInitEntry &R) {
686 return L.Priority < R.Priority;
687 });
Sam Clegg50686852018-01-12 18:35:13 +0000688}
689
Sam Clegg8fcf0122019-05-21 09:13:09 +0000690void Writer::createSyntheticSections() {
691 Out.DylinkSec = make<DylinkSection>();
692 Out.TypeSec = make<TypeSection>();
693 Out.ImportSec = make<ImportSection>();
694 Out.FunctionSec = make<FunctionSection>();
695 Out.TableSec = make<TableSection>();
696 Out.MemorySec = make<MemorySection>();
697 Out.GlobalSec = make<GlobalSection>();
698 Out.EventSec = make<EventSection>();
699 Out.ExportSec = make<ExportSection>();
700 Out.ElemSec = make<ElemSection>(TableBase);
701 Out.DataCountSec = make<DataCountSection>(Segments.size());
702 Out.LinkingSec = make<LinkingSection>(InitFunctions, Segments);
703 Out.NameSec = make<NameSection>();
704 Out.ProducersSec = make<ProducersSection>();
705 Out.TargetFeaturesSec = make<TargetFeaturesSection>();
706}
707
Sam Cleggc94d3932017-11-17 18:14:09 +0000708void Writer::run() {
Sam Cleggbfb75342018-11-15 00:37:21 +0000709 if (Config->Relocatable || Config->Pic)
Sam Clegg99eb42c2018-02-27 23:58:03 +0000710 Config->GlobalBase = 0;
711
Sam Cleggbfb75342018-11-15 00:37:21 +0000712 // For PIC code the table base is assigned dynamically by the loader.
713 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
714 if (!Config->Pic)
715 TableBase = 1;
716
Sam Clegg8fcf0122019-05-21 09:13:09 +0000717 log("-- createOutputSegments");
718 createOutputSegments();
719 log("-- createSyntheticSections");
720 createSyntheticSections();
721 log("-- populateProducers");
722 populateProducers();
723 log("-- populateTargetFeatures");
724 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +0000725 log("-- calculateImports");
726 calculateImports();
Sam Cleggb9889bb2019-05-23 09:41:03 +0000727 log("-- scanRelocations");
728 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000729 log("-- assignIndexes");
730 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000731 log("-- calculateInitFunctions");
732 calculateInitFunctions();
Sam Cleggc0a4f452019-05-21 17:16:33 +0000733 log("-- calculateTypes");
734 calculateTypes();
735 log("-- layoutMemory");
736 layoutMemory();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000737 if (!Config->Relocatable) {
Sam Clegg09137be2019-04-04 18:40:51 +0000738 if (Config->Pic)
739 createApplyRelocationsFunction();
740 createCallCtorsFunction();
741 }
Sam Clegg93102972018-02-23 05:08:53 +0000742 log("-- calculateExports");
743 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +0000744 log("-- calculateCustomSections");
745 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000746 log("-- populateSymtab");
747 populateSymtab();
748 log("-- addSections");
749 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000750
751 if (errorHandler().Verbose) {
Sam Clegg8fcf0122019-05-21 09:13:09 +0000752 log("Defined Functions: " + Twine(Out.FunctionSec->InputFunctions.size()));
753 log("Defined Globals : " + Twine(Out.GlobalSec->InputGlobals.size()));
754 log("Defined Events : " + Twine(Out.EventSec->InputEvents.size()));
Sam Cleggb9889bb2019-05-23 09:41:03 +0000755 log("Function Imports : " + Twine(Out.ImportSec->numImportedFunctions()));
756 log("Global Imports : " + Twine(Out.ImportSec->numImportedGlobals()));
757 log("Event Imports : " + Twine(Out.ImportSec->numImportedEvents()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000758 for (ObjFile *File : Symtab->ObjectFiles)
759 File->dumpInfo();
760 }
761
Sam Cleggc94d3932017-11-17 18:14:09 +0000762 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000763 log("-- finalizeSections");
764 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000765
766 log("-- openFile");
767 openFile();
768 if (errorCount())
769 return;
770
771 writeHeader();
772
773 log("-- writeSections");
774 writeSections();
775 if (errorCount())
776 return;
777
778 if (Error E = Buffer->commit())
779 fatal("failed to write the output file: " + toString(std::move(E)));
780}
781
782// Open a result file.
783void Writer::openFile() {
784 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000785
786 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
787 FileOutputBuffer::create(Config->OutputFile, FileSize,
788 FileOutputBuffer::F_executable);
789
790 if (!BufferOrErr)
791 error("failed to open " + Config->OutputFile + ": " +
792 toString(BufferOrErr.takeError()));
793 else
794 Buffer = std::move(*BufferOrErr);
795}
796
797void Writer::createHeader() {
798 raw_string_ostream OS(Header);
799 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
800 writeU32(OS, WasmVersion, "wasm version");
801 OS.flush();
802 FileSize += Header.size();
803}
804
805void lld::wasm::writeResult() { Writer().run(); }