blob: 6c4ccab31d40ea30e27aa8f83afa97d6db5b9bfd [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.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#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000011#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000012#include "InputChunks.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"
16#include "SymbolTable.h"
17#include "WriterUtils.h"
18#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000019#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000020#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000021#include "llvm/ADT/DenseSet.h"
Sam Clegg93102972018-02-23 05:08:53 +000022#include "llvm/BinaryFormat/Wasm.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000023#include "llvm/Support/FileOutputBuffer.h"
24#include "llvm/Support/Format.h"
25#include "llvm/Support/FormatVariadic.h"
26#include "llvm/Support/LEB128.h"
27
28#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000029#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000030
31#define DEBUG_TYPE "lld"
32
33using namespace llvm;
34using namespace llvm::wasm;
35using namespace lld;
36using namespace lld::wasm;
37
38static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000039static constexpr int kInitialTableOffset = 1;
Sam Cleggc94d3932017-11-17 18:14:09 +000040
41namespace {
42
Sam Cleggc94d3932017-11-17 18:14:09 +000043// Traits for using WasmSignature in a DenseMap.
44struct WasmSignatureDenseMapInfo {
45 static WasmSignature getEmptyKey() {
46 WasmSignature Sig;
47 Sig.ReturnType = 1;
48 return Sig;
49 }
50 static WasmSignature getTombstoneKey() {
51 WasmSignature Sig;
52 Sig.ReturnType = 2;
53 return Sig;
54 }
55 static unsigned getHashValue(const WasmSignature &Sig) {
56 uintptr_t Value = 0;
57 Value += DenseMapInfo<int32_t>::getHashValue(Sig.ReturnType);
58 for (int32_t Param : Sig.ParamTypes)
59 Value += DenseMapInfo<int32_t>::getHashValue(Param);
60 return Value;
61 }
62 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
63 return LHS == RHS;
64 }
65};
66
Sam Clegg93102972018-02-23 05:08:53 +000067// An init entry to be written to either the synthetic init func or the
68// linking metadata.
69struct WasmInitEntry {
Sam Clegg811236c2018-01-19 03:31:07 +000070 const Symbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000071 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000072};
73
Sam Cleggc94d3932017-11-17 18:14:09 +000074// The writer writes a SymbolTable result to a file.
75class Writer {
76public:
77 void run();
78
79private:
80 void openFile();
81
Sam Cleggc375e4e2018-01-10 19:18:22 +000082 uint32_t lookupType(const WasmSignature &Sig);
83 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000084
Sam Clegg50686852018-01-12 18:35:13 +000085 void createCtorFunction();
86 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000087 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000088 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000089 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000090 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000091 void calculateTypes();
92 void createOutputSegments();
93 void layoutMemory();
94 void createHeader();
95 void createSections();
96 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000097 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000098
99 // Builtin sections
100 void createTypeSection();
101 void createFunctionSection();
102 void createTableSection();
103 void createGlobalSection();
104 void createExportSection();
105 void createImportSection();
106 void createMemorySection();
107 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000108 void createCodeSection();
109 void createDataSection();
110
111 // Custom sections
112 void createRelocSections();
113 void createLinkingSection();
114 void createNameSection();
115
116 void writeHeader();
117 void writeSections();
118
119 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000120 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000121
122 std::vector<const WasmSignature *> Types;
123 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000124 std::vector<const Symbol *> ImportedSymbols;
125 unsigned NumImportedFunctions = 0;
126 unsigned NumImportedGlobals = 0;
127 std::vector<Symbol *> ExportedSymbols;
128 std::vector<const DefinedData *> DefinedFakeGlobals;
129 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000130 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000131 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000132 std::vector<const Symbol *> SymtabEntries;
133 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000134
135 // Elements that are used to construct the final output
136 std::string Header;
137 std::vector<OutputSection *> OutputSections;
138
139 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000140 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000141
142 std::vector<OutputSegment *> Segments;
143 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
144};
145
146} // anonymous namespace
147
148static void debugPrint(const char *fmt, ...) {
149 if (!errorHandler().Verbose)
150 return;
151 fprintf(stderr, "lld: ");
152 va_list ap;
153 va_start(ap, fmt);
154 vfprintf(stderr, fmt, ap);
155 va_end(ap);
156}
157
158void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000159 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000160 if (Config->ImportMemory)
161 ++NumImports;
162
163 if (NumImports == 0)
164 return;
165
166 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
167 raw_ostream &OS = Section->getStream();
168
169 writeUleb128(OS, NumImports, "import count");
170
Sam Cleggc94d3932017-11-17 18:14:09 +0000171 if (Config->ImportMemory) {
172 WasmImport Import;
173 Import.Module = "env";
174 Import.Field = "memory";
175 Import.Kind = WASM_EXTERNAL_MEMORY;
176 Import.Memory.Flags = 0;
177 Import.Memory.Initial = NumMemoryPages;
178 writeImport(OS, Import);
179 }
180
Sam Clegg93102972018-02-23 05:08:53 +0000181 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000182 WasmImport Import;
183 Import.Module = "env";
184 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000185 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
186 Import.Kind = WASM_EXTERNAL_FUNCTION;
187 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
188 } else {
189 auto *GlobalSym = cast<GlobalSymbol>(Sym);
190 Import.Kind = WASM_EXTERNAL_GLOBAL;
191 Import.Global = *GlobalSym->getGlobalType();
192 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000193 writeImport(OS, Import);
194 }
195}
196
197void Writer::createTypeSection() {
198 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
199 raw_ostream &OS = Section->getStream();
200 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000201 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000202 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000203}
204
205void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000206 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000207 return;
208
209 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
210 raw_ostream &OS = Section->getStream();
211
Sam Clegg9f934222018-02-21 18:29:23 +0000212 writeUleb128(OS, InputFunctions.size(), "function count");
213 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000214 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000215}
216
217void Writer::createMemorySection() {
218 if (Config->ImportMemory)
219 return;
220
221 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
222 raw_ostream &OS = Section->getStream();
223
224 writeUleb128(OS, 1, "memory count");
225 writeUleb128(OS, 0, "memory limits flags");
226 writeUleb128(OS, NumMemoryPages, "initial pages");
227}
228
229void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000230 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
231 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000232 return;
233
Sam Cleggc94d3932017-11-17 18:14:09 +0000234 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
235 raw_ostream &OS = Section->getStream();
236
Sam Clegg93102972018-02-23 05:08:53 +0000237 writeUleb128(OS, NumGlobals, "global count");
238 for (const InputGlobal *G : InputGlobals)
239 writeGlobal(OS, G->Global);
240 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000241 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000242 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000243 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
244 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000245 writeGlobal(OS, Global);
246 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000247}
248
249void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000250 // Always output a table section, even if there are no indirect calls.
251 // There are two reasons for this:
252 // 1. For executables it is useful to have an empty table slot at 0
253 // which can be filled with a null function call handler.
254 // 2. If we don't do this, any program that contains a call_indirect but
255 // no address-taken function will fail at validation time since it is
256 // a validation error to include a call_indirect instruction if there
257 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000258 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000259
Sam Cleggc94d3932017-11-17 18:14:09 +0000260 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
261 raw_ostream &OS = Section->getStream();
262
263 writeUleb128(OS, 1, "table count");
264 writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type");
265 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000266 writeUleb128(OS, TableSize, "table initial size");
267 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000268}
269
270void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000271 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000272
Sam Cleggd3052d52018-01-18 23:40:49 +0000273 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000274 if (!NumExports)
275 return;
276
277 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
278 raw_ostream &OS = Section->getStream();
279
280 writeUleb128(OS, NumExports, "export count");
281
Rui Ueyama7d696882018-02-28 00:18:34 +0000282 if (ExportMemory)
283 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000286
Sam Clegg93102972018-02-23 05:08:53 +0000287 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000289 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000290 DEBUG(dbgs() << "Export: " << Name << "\n");
291
292 if (isa<DefinedFunction>(Sym))
293 Export = {Name, WASM_EXTERNAL_FUNCTION, Sym->getOutputIndex()};
294 else if (isa<DefinedGlobal>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, Sym->getOutputIndex()};
296 else if (isa<DefinedData>(Sym))
297 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
298 else
Sam Clegg93102972018-02-23 05:08:53 +0000299 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000300 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000301 }
302}
303
Sam Cleggc94d3932017-11-17 18:14:09 +0000304void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000305 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000306 return;
307
308 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
309 raw_ostream &OS = Section->getStream();
310
311 writeUleb128(OS, 1, "segment count");
312 writeUleb128(OS, 0, "table index");
313 WasmInitExpr InitExpr;
314 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000315 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000316 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000317 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000318
Sam Clegg48bbd632018-01-24 21:37:30 +0000319 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000320 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000321 assert(Sym->getTableIndex() == TableIndex);
322 writeUleb128(OS, Sym->getOutputIndex(), "function index");
323 ++TableIndex;
324 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000325}
326
327void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000328 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000329 return;
330
331 log("createCodeSection");
332
Sam Clegg9f934222018-02-21 18:29:23 +0000333 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000334 OutputSections.push_back(Section);
335}
336
337void Writer::createDataSection() {
338 if (!Segments.size())
339 return;
340
341 log("createDataSection");
342 auto Section = make<DataSection>(Segments);
343 OutputSections.push_back(Section);
344}
345
Sam Cleggd451da12017-12-19 19:56:27 +0000346// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000347// These are only created when relocatable output is requested.
348void Writer::createRelocSections() {
349 log("createRelocSections");
350 // Don't use iterator here since we are adding to OutputSection
351 size_t OrigSize = OutputSections.size();
352 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000353 OutputSection *OSec = OutputSections[i];
354 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000355 if (!Count)
356 continue;
357
Rui Ueyama37254062018-02-28 00:01:31 +0000358 StringRef Name;
359 if (OSec->Type == WASM_SEC_DATA)
360 Name = "reloc.DATA";
361 else if (OSec->Type == WASM_SEC_CODE)
362 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000363 else
Sam Cleggd451da12017-12-19 19:56:27 +0000364 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000365
Rui Ueyama37254062018-02-28 00:01:31 +0000366 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000367 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000368 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000370 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000371 }
372}
373
Sam Clegg49ed9262017-12-01 00:53:21 +0000374// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000375// This is only created when relocatable output is requested.
376void Writer::createLinkingSection() {
377 SyntheticSection *Section =
378 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
379 raw_ostream &OS = Section->getStream();
380
Sam Clegg0d0dd392017-12-19 17:09:45 +0000381 if (!Config->Relocatable)
382 return;
383
Sam Clegg93102972018-02-23 05:08:53 +0000384 if (!SymtabEntries.empty()) {
385 SubSection SubSection(WASM_SYMBOL_TABLE);
386 writeUleb128(SubSection.getStream(), SymtabEntries.size(), "num symbols");
387 for (const Symbol *Sym : SymtabEntries) {
388 assert(Sym->isDefined() || Sym->isUndefined());
389 WasmSymbolType Kind = Sym->getWasmType();
390 uint32_t Flags = Sym->isLocal() ? WASM_SYMBOL_BINDING_LOCAL : 0;
391 if (Sym->isWeak())
392 Flags |= WASM_SYMBOL_BINDING_WEAK;
393 if (Sym->isHidden())
394 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
395 if (Sym->isUndefined())
396 Flags |= WASM_SYMBOL_UNDEFINED;
397 writeUleb128(SubSection.getStream(), Kind, "sym kind");
398 writeUleb128(SubSection.getStream(), Flags, "sym flags");
399 switch (Kind) {
400 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
401 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
402 writeUleb128(SubSection.getStream(), Sym->getOutputIndex(), "index");
403 if (Sym->isDefined())
404 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
405 break;
406 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
407 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
408 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
409 writeUleb128(SubSection.getStream(), DataSym->getOutputSegmentIndex(),
410 "index");
411 writeUleb128(SubSection.getStream(),
412 DataSym->getOutputSegmentOffset(), "data offset");
413 writeUleb128(SubSection.getStream(), DataSym->getSize(), "data size");
414 }
415 break;
416 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000417 }
418 SubSection.finalizeContents();
419 SubSection.writeToStream(OS);
420 }
421
Sam Clegg0d0dd392017-12-19 17:09:45 +0000422 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000423 SubSection SubSection(WASM_SEGMENT_INFO);
424 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
425 for (const OutputSegment *S : Segments) {
426 writeStr(SubSection.getStream(), S->Name, "segment name");
427 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
428 writeUleb128(SubSection.getStream(), 0, "flags");
429 }
430 SubSection.finalizeContents();
431 SubSection.writeToStream(OS);
432 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000433
Sam Clegg0d0dd392017-12-19 17:09:45 +0000434 if (!InitFunctions.empty()) {
435 SubSection SubSection(WASM_INIT_FUNCS);
436 writeUleb128(SubSection.getStream(), InitFunctions.size(),
Sam Clegg54c38912018-01-17 18:50:30 +0000437 "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000438 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg0d0dd392017-12-19 17:09:45 +0000439 writeUleb128(SubSection.getStream(), F.Priority, "priority");
Sam Clegg93102972018-02-23 05:08:53 +0000440 writeUleb128(SubSection.getStream(), F.Sym->getOutputSymbolIndex(),
441 "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000442 }
443 SubSection.finalizeContents();
444 SubSection.writeToStream(OS);
445 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000446
447 struct ComdatEntry { unsigned Kind; uint32_t Index; };
448 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
449
Sam Clegg9f934222018-02-21 18:29:23 +0000450 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000451 StringRef Comdat = F->getComdat();
452 if (!Comdat.empty())
453 Comdats[Comdat].emplace_back(
454 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
455 }
456 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000457 const auto &InputSegments = Segments[I]->InputSegments;
458 if (InputSegments.empty())
459 continue;
460 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000461#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000462 for (const InputSegment *IS : InputSegments)
463 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000464#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000465 if (!Comdat.empty())
466 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
467 }
468
469 if (!Comdats.empty()) {
470 SubSection SubSection(WASM_COMDAT_INFO);
471 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
472 for (const auto &C : Comdats) {
473 writeStr(SubSection.getStream(), C.first, "comdat name");
474 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
475 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
476 for (const ComdatEntry &Entry : C.second) {
477 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
478 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
479 }
480 }
481 SubSection.finalizeContents();
482 SubSection.writeToStream(OS);
483 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000484}
485
486// Create the custom "name" section containing debug symbol names.
487void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000488 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000489 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000490 if (!F->getName().empty())
491 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000492
Sam Clegg1963d712018-01-17 20:19:04 +0000493 if (NumNames == 0)
494 return;
Sam Clegg50686852018-01-12 18:35:13 +0000495
Sam Cleggc94d3932017-11-17 18:14:09 +0000496 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
497
Sam Cleggc94d3932017-11-17 18:14:09 +0000498 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
499 raw_ostream &OS = FunctionSubsection.getStream();
Sam Clegg1963d712018-01-17 20:19:04 +0000500 writeUleb128(OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000501
Sam Clegg93102972018-02-23 05:08:53 +0000502 // Names must appear in function index order. As it happens ImportedSymbols
503 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000504 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000505 for (const Symbol *S : ImportedSymbols) {
506 if (!isa<FunctionSymbol>(S))
507 continue;
Sam Clegg1963d712018-01-17 20:19:04 +0000508 writeUleb128(OS, S->getOutputIndex(), "import index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000509 writeStr(OS, S->getName(), "symbol name");
510 }
Sam Clegg9f934222018-02-21 18:29:23 +0000511 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000512 if (!F->getName().empty()) {
513 writeUleb128(OS, F->getOutputIndex(), "func index");
514 writeStr(OS, F->getName(), "symbol name");
515 }
516 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000517
518 FunctionSubsection.finalizeContents();
519 FunctionSubsection.writeToStream(Section->getStream());
520}
521
522void Writer::writeHeader() {
523 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
524}
525
526void Writer::writeSections() {
527 uint8_t *Buf = Buffer->getBufferStart();
528 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
529}
530
531// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000532// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000533// The memory layout is as follows, from low to high.
534// - initialized data (starting at Config->GlobalBase)
535// - BSS data (not currently implemented in llvm)
536// - explicit stack (Config->ZStackSize)
537// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000538void Writer::layoutMemory() {
539 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000540 MemoryPtr = Config->GlobalBase;
541 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000542
543 createOutputSegments();
544
Sam Cleggf0d433d2018-02-02 22:59:56 +0000545 // Arbitrarily set __dso_handle handle to point to the start of the data
546 // segments.
547 if (WasmSym::DsoHandle)
548 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
549
Sam Cleggc94d3932017-11-17 18:14:09 +0000550 for (OutputSegment *Seg : Segments) {
551 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
552 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000553 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000554 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
555 MemoryPtr += Seg->Size;
556 }
557
Sam Cleggf0d433d2018-02-02 22:59:56 +0000558 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000559 if (WasmSym::DataEnd)
560 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000561
Sam Clegg99eb42c2018-02-27 23:58:03 +0000562 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000563
Sam Cleggf0d433d2018-02-02 22:59:56 +0000564 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000565 if (!Config->Relocatable) {
566 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
567 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
568 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
569 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
570 debugPrint("mem: stack base = %d\n", MemoryPtr);
571 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000572 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000573 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000574
Sam Clegg51bcdc22018-01-17 01:34:31 +0000575 // Set `__heap_base` to directly follow the end of the stack. We don't
576 // allocate any heap memory up front, but instead really on the malloc/brk
577 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000578 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000579 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000580 }
581
582 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
583 NumMemoryPages = MemSize / WasmPageSize;
584 debugPrint("mem: total pages = %d\n", NumMemoryPages);
585}
586
587SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000588 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000589 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000590 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000591 OutputSections.push_back(Sec);
592 return Sec;
593}
594
595void Writer::createSections() {
596 // Known sections
597 createTypeSection();
598 createImportSection();
599 createFunctionSection();
600 createTableSection();
601 createMemorySection();
602 createGlobalSection();
603 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000604 createElemSection();
605 createCodeSection();
606 createDataSection();
607
608 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000609 if (Config->Relocatable) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000610 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000611 createLinkingSection();
612 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000613 if (!Config->StripDebug && !Config->StripAll)
614 createNameSection();
615
616 for (OutputSection *S : OutputSections) {
617 S->setOffset(FileSize);
618 S->finalizeContents();
619 FileSize += S->getSize();
620 }
621}
622
Sam Cleggc94d3932017-11-17 18:14:09 +0000623void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000624 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000625 if (!Sym->isUndefined())
626 continue;
627 if (isa<DataSymbol>(Sym))
628 continue;
629 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000630 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000631
Sam Clegg93102972018-02-23 05:08:53 +0000632 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
633 Sym->setOutputIndex(ImportedSymbols.size());
634 ImportedSymbols.emplace_back(Sym);
635 if (isa<FunctionSymbol>(Sym))
636 ++NumImportedFunctions;
637 else
638 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000639 }
640}
641
Sam Cleggd3052d52018-01-18 23:40:49 +0000642void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000643 if (Config->Relocatable)
644 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000645
Sam Clegg93102972018-02-23 05:08:53 +0000646 auto ExportSym = [&](Symbol *Sym) {
647 if (!Sym->isDefined())
648 return;
649 if (Sym->isHidden() || Sym->isLocal())
650 return;
651 if (!Sym->isLive())
652 return;
653
654 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
655
656 if (auto *D = dyn_cast<DefinedData>(Sym)) {
657 // TODO Remove this check here; for non-relocatable output we actually
658 // used only to create fake-global exports for the synthetic symbols. Fix
659 // this in a future commit
660 if (Sym != WasmSym::DataEnd && Sym != WasmSym::HeapBase)
661 return;
662 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd3052d52018-01-18 23:40:49 +0000663 }
Sam Clegg93102972018-02-23 05:08:53 +0000664 ExportedSymbols.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000665 };
666
Sam Clegg93102972018-02-23 05:08:53 +0000667 // TODO The two loops below should be replaced with this single loop, with
668 // ExportSym inlined:
669 // for (Symbol *Sym : Symtab->getSymbols())
670 // ExportSym(Sym);
671 // Making that change would reorder the output though, so it should be done as
672 // a separate commit.
Sam Cleggd3052d52018-01-18 23:40:49 +0000673
Sam Clegg93102972018-02-23 05:08:53 +0000674 for (ObjFile *File : Symtab->ObjectFiles)
675 for (Symbol *Sym : File->getSymbols())
676 if (File == Sym->getFile())
677 ExportSym(Sym);
678
679 for (Symbol *Sym : Symtab->getSymbols())
680 if (Sym->getFile() == nullptr)
681 ExportSym(Sym);
682}
683
684void Writer::assignSymtab() {
685 if (!Config->Relocatable)
686 return;
687
688 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000689 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000690 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000691 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000692 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000693 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000694 if (!Sym->isLive())
695 return;
696 Sym->setOutputSymbolIndex(SymbolIndex++);
697 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000698 }
699 }
700
Sam Clegg93102972018-02-23 05:08:53 +0000701 // For the moment, relocatable output doesn't contain any synthetic functions,
702 // so no need to look through the Symtab for symbols not referenced by
703 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000704}
705
Sam Cleggc375e4e2018-01-10 19:18:22 +0000706uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000707 auto It = TypeIndices.find(Sig);
708 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000709 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000710 return 0;
711 }
712 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000713}
714
715uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000716 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000717 if (Pair.second) {
718 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000719 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000720 }
Sam Cleggb8621592017-11-30 01:40:08 +0000721 return Pair.first->second;
722}
723
Sam Cleggc94d3932017-11-17 18:14:09 +0000724void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000725 // The output type section is the union of the following sets:
726 // 1. Any signature used in the TYPE relocation
727 // 2. The signatures of all imported functions
728 // 3. The signatures of all defined functions
729
Sam Cleggc94d3932017-11-17 18:14:09 +0000730 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000731 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
732 for (uint32_t I = 0; I < Types.size(); I++)
733 if (File->TypeIsUsed[I])
734 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000735 }
Sam Clegg50686852018-01-12 18:35:13 +0000736
Sam Clegg93102972018-02-23 05:08:53 +0000737 for (const Symbol *Sym : ImportedSymbols)
738 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
739 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000740
Sam Clegg9f934222018-02-21 18:29:23 +0000741 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000742 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000743}
744
Sam Clegg8d146bb2018-01-09 23:56:44 +0000745void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000746 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000747 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000748 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
749 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000750 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000751 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000752 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000753 Func->setOutputIndex(FunctionIndex++);
754 }
755 }
756
Sam Clegg93102972018-02-23 05:08:53 +0000757 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000758 auto HandleRelocs = [&](InputChunk *Chunk) {
759 if (!Chunk->Live)
760 return;
761 ObjFile *File = Chunk->File;
762 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000763 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000764 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
765 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
766 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
767 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
768 continue;
769 Sym->setTableIndex(TableIndex++);
770 IndirectFunctions.emplace_back(Sym);
771 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000772 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000773 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
774 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000775 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
776 // Mark target global as live
777 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
778 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
779 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
780 G->Global->Live = true;
781 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000782 }
783 }
784 };
785
Sam Clegg8d146bb2018-01-09 23:56:44 +0000786 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000787 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000788 for (InputChunk *Chunk : File->Functions)
789 HandleRelocs(Chunk);
790 for (InputChunk *Chunk : File->Segments)
791 HandleRelocs(Chunk);
792 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000793
Sam Clegg93102972018-02-23 05:08:53 +0000794 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
795 auto AddDefinedGlobal = [&](InputGlobal *Global) {
796 if (Global->Live) {
797 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
798 Global->setOutputIndex(GlobalIndex++);
799 InputGlobals.push_back(Global);
800 }
801 };
802
803 if (WasmSym::StackPointer)
804 AddDefinedGlobal(WasmSym::StackPointer->Global);
805
806 for (ObjFile *File : Symtab->ObjectFiles) {
807 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
808 for (InputGlobal *Global : File->Globals)
809 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000810 }
811}
812
813static StringRef getOutputDataSegmentName(StringRef Name) {
814 if (Config->Relocatable)
815 return Name;
816
817 for (StringRef V :
818 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
819 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
820 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
821 StringRef Prefix = V.drop_back();
822 if (Name.startswith(V) || Name == Prefix)
823 return Prefix;
824 }
825
826 return Name;
827}
828
829void Writer::createOutputSegments() {
830 for (ObjFile *File : Symtab->ObjectFiles) {
831 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000832 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000833 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000834 StringRef Name = getOutputDataSegmentName(Segment->getName());
835 OutputSegment *&S = SegmentMap[Name];
836 if (S == nullptr) {
837 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000838 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000839 Segments.push_back(S);
840 }
841 S->addInputSegment(Segment);
842 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000843 }
844 }
845}
846
Sam Clegg50686852018-01-12 18:35:13 +0000847static const int OPCODE_CALL = 0x10;
848static const int OPCODE_END = 0xb;
849
850// Create synthetic "__wasm_call_ctors" function based on ctor functions
851// in input object.
852void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000853 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000854 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000855
856 // First write the body bytes to a string.
857 std::string FunctionBody;
Sam Clegg93102972018-02-23 05:08:53 +0000858 const WasmSignature *Signature = WasmSym::CallCtors->getFunctionType();
Sam Clegg50686852018-01-12 18:35:13 +0000859 {
860 raw_string_ostream OS(FunctionBody);
861 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000862 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000863 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000864 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000865 }
866 writeU8(OS, OPCODE_END, "END");
867 }
868
869 // Once we know the size of the body we can create the final function body
870 raw_string_ostream OS(CtorFunctionBody);
871 writeUleb128(OS, FunctionBody.size(), "function size");
872 OS.flush();
873 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000874 ArrayRef<uint8_t> BodyArray(
875 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
876 CtorFunctionBody.size());
Sam Clegg93102972018-02-23 05:08:53 +0000877 SyntheticFunction *F = make<SyntheticFunction>(*Signature, BodyArray,
Sam Clegg011dce22018-02-21 18:37:44 +0000878 WasmSym::CallCtors->getName());
879 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000880 F->Live = true;
881 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000882 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000883}
884
885// Populate InitFunctions vector with init functions from all input objects.
886// This is then used either when creating the output linking section or to
887// synthesize the "__wasm_call_ctors" function.
888void Writer::calculateInitFunctions() {
889 for (ObjFile *File : Symtab->ObjectFiles) {
890 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Sam Clegg50686852018-01-12 18:35:13 +0000891 for (const WasmInitFunc &F : L.InitFunctions)
Sam Clegg93102972018-02-23 05:08:53 +0000892 InitFunctions.emplace_back(
893 WasmInitEntry{File->getFunctionSymbol(F.Symbol), F.Priority});
Sam Clegg50686852018-01-12 18:35:13 +0000894 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000895
Sam Clegg50686852018-01-12 18:35:13 +0000896 // Sort in order of priority (lowest first) so that they are called
897 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000898 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000899 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000900 return L.Priority < R.Priority;
901 });
Sam Clegg50686852018-01-12 18:35:13 +0000902}
903
Sam Cleggc94d3932017-11-17 18:14:09 +0000904void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000905 if (Config->Relocatable)
906 Config->GlobalBase = 0;
907
Sam Cleggc94d3932017-11-17 18:14:09 +0000908 log("-- calculateImports");
909 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000910 log("-- assignIndexes");
911 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000912 log("-- calculateInitFunctions");
913 calculateInitFunctions();
914 if (!Config->Relocatable)
915 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000916 log("-- calculateTypes");
917 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000918 log("-- layoutMemory");
919 layoutMemory();
920 log("-- calculateExports");
921 calculateExports();
922 log("-- assignSymtab");
923 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000924
925 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000926 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000927 log("Defined Globals : " + Twine(InputGlobals.size()));
928 log("Function Imports : " + Twine(NumImportedFunctions));
929 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000930 for (ObjFile *File : Symtab->ObjectFiles)
931 File->dumpInfo();
932 }
933
Sam Cleggc94d3932017-11-17 18:14:09 +0000934 createHeader();
935 log("-- createSections");
936 createSections();
937
938 log("-- openFile");
939 openFile();
940 if (errorCount())
941 return;
942
943 writeHeader();
944
945 log("-- writeSections");
946 writeSections();
947 if (errorCount())
948 return;
949
950 if (Error E = Buffer->commit())
951 fatal("failed to write the output file: " + toString(std::move(E)));
952}
953
954// Open a result file.
955void Writer::openFile() {
956 log("writing: " + Config->OutputFile);
957 ::remove(Config->OutputFile.str().c_str());
958
959 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
960 FileOutputBuffer::create(Config->OutputFile, FileSize,
961 FileOutputBuffer::F_executable);
962
963 if (!BufferOrErr)
964 error("failed to open " + Config->OutputFile + ": " +
965 toString(BufferOrErr.takeError()));
966 else
967 Buffer = std::move(*BufferOrErr);
968}
969
970void Writer::createHeader() {
971 raw_string_ostream OS(Header);
972 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
973 writeU32(OS, WasmVersion, "wasm version");
974 OS.flush();
975 FileSize += Header.size();
976}
977
978void lld::wasm::writeResult() { Writer().run(); }