blob: 5a347e458d8bf5104d116da59f1690a42236aa64 [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
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000374static uint32_t getWasmFlags(const Symbol *Sym) {
375 uint32_t Flags = 0;
376 if (Sym->isLocal())
377 Flags |= WASM_SYMBOL_BINDING_LOCAL;
378 if (Sym->isWeak())
379 Flags |= WASM_SYMBOL_BINDING_WEAK;
380 if (Sym->isHidden())
381 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
382 if (Sym->isUndefined())
383 Flags |= WASM_SYMBOL_UNDEFINED;
384 return Flags;
385}
386
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000387// Some synthetic sections (e.g. "name" and "linking") have subsections.
388// Just like the synthetic sections themselves these need to be created before
389// they can be written out (since they are preceded by their length). This
390// class is used to create subsections and then write them into the stream
391// of the parent section.
392class SubSection {
393public:
394 explicit SubSection(uint32_t Type) : Type(Type) {}
395
396 void writeTo(raw_ostream &To) {
397 OS.flush();
398 lld::wasm::writeUleb128(To, Type, "subsection type");
399 lld::wasm::writeUleb128(To, Body.size(), "subsection size");
400 To.write(Body.data(), Body.size());
401 }
402
403private:
404 uint32_t Type;
405 std::string Body;
406
407public:
408 raw_string_ostream OS{Body};
409};
410
Sam Clegg49ed9262017-12-01 00:53:21 +0000411// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000412// This is only created when relocatable output is requested.
413void Writer::createLinkingSection() {
414 SyntheticSection *Section =
415 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
416 raw_ostream &OS = Section->getStream();
417
Sam Clegg0d0dd392017-12-19 17:09:45 +0000418 if (!Config->Relocatable)
419 return;
420
Sam Clegg93102972018-02-23 05:08:53 +0000421 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000422 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000423 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
424
Sam Clegg93102972018-02-23 05:08:53 +0000425 for (const Symbol *Sym : SymtabEntries) {
426 assert(Sym->isDefined() || Sym->isUndefined());
427 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000428 uint32_t Flags = getWasmFlags(Sym);
429
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000430 writeUleb128(Sub.OS, Kind, "sym kind");
431 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000432
Sam Clegg93102972018-02-23 05:08:53 +0000433 switch (Kind) {
434 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
435 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000436 writeUleb128(Sub.OS, Sym->getOutputIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000437 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000438 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000439 break;
440 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000441 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000442 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000443 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
444 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000445 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000446 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000447 }
448 break;
449 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000450 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000451
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000452 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000453 }
454
Sam Clegg0d0dd392017-12-19 17:09:45 +0000455 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000456 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000458 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000459 writeStr(Sub.OS, S->Name, "segment name");
460 writeUleb128(Sub.OS, S->Alignment, "alignment");
461 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000462 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000463 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000464 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000465
Sam Clegg0d0dd392017-12-19 17:09:45 +0000466 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000467 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000468 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000469 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000470 writeUleb128(Sub.OS, F.Priority, "priority");
471 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000472 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000473 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000474 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000475
476 struct ComdatEntry { unsigned Kind; uint32_t Index; };
477 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
478
Sam Clegg9f934222018-02-21 18:29:23 +0000479 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000480 StringRef Comdat = F->getComdat();
481 if (!Comdat.empty())
482 Comdats[Comdat].emplace_back(
483 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
484 }
485 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000486 const auto &InputSegments = Segments[I]->InputSegments;
487 if (InputSegments.empty())
488 continue;
489 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000490#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000491 for (const InputSegment *IS : InputSegments)
492 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000493#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000494 if (!Comdat.empty())
495 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
496 }
497
498 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000499 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000501 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000502 writeStr(Sub.OS, C.first, "comdat name");
503 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
504 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000505 for (const ComdatEntry &Entry : C.second) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000506 writeUleb128(Sub.OS, Entry.Kind, "entry kind");
507 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000508 }
509 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000510 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000511 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000512}
513
514// Create the custom "name" section containing debug symbol names.
515void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000516 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000517 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000518 if (!F->getName().empty())
519 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000520
Sam Clegg1963d712018-01-17 20:19:04 +0000521 if (NumNames == 0)
522 return;
Sam Clegg50686852018-01-12 18:35:13 +0000523
Sam Cleggc94d3932017-11-17 18:14:09 +0000524 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
525
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000526 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000527 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000528
Sam Clegg93102972018-02-23 05:08:53 +0000529 // Names must appear in function index order. As it happens ImportedSymbols
530 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000531 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000532 for (const Symbol *S : ImportedSymbols) {
533 if (!isa<FunctionSymbol>(S))
534 continue;
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000535 writeUleb128(Sub.OS, S->getOutputIndex(), "import index");
536 writeStr(Sub.OS, S->getName(), "symbol name");
Sam Cleggc94d3932017-11-17 18:14:09 +0000537 }
Sam Clegg9f934222018-02-21 18:29:23 +0000538 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000539 if (!F->getName().empty()) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000540 writeUleb128(Sub.OS, F->getOutputIndex(), "func index");
541 writeStr(Sub.OS, F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000542 }
543 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000544
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000545 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000546}
547
548void Writer::writeHeader() {
549 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
550}
551
552void Writer::writeSections() {
553 uint8_t *Buf = Buffer->getBufferStart();
554 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
555}
556
557// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000558// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000559// The memory layout is as follows, from low to high.
560// - initialized data (starting at Config->GlobalBase)
561// - BSS data (not currently implemented in llvm)
562// - explicit stack (Config->ZStackSize)
563// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000564void Writer::layoutMemory() {
565 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000566 MemoryPtr = Config->GlobalBase;
567 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000568
569 createOutputSegments();
570
Sam Cleggf0d433d2018-02-02 22:59:56 +0000571 // Arbitrarily set __dso_handle handle to point to the start of the data
572 // segments.
573 if (WasmSym::DsoHandle)
574 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
575
Sam Cleggc94d3932017-11-17 18:14:09 +0000576 for (OutputSegment *Seg : Segments) {
577 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
578 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000579 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000580 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
581 MemoryPtr += Seg->Size;
582 }
583
Sam Cleggf0d433d2018-02-02 22:59:56 +0000584 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000585 if (WasmSym::DataEnd)
586 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000587
Sam Clegg99eb42c2018-02-27 23:58:03 +0000588 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000589
Sam Cleggf0d433d2018-02-02 22:59:56 +0000590 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000591 if (!Config->Relocatable) {
592 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
593 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
594 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
595 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
596 debugPrint("mem: stack base = %d\n", MemoryPtr);
597 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000598 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000599 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000600
Sam Clegg51bcdc22018-01-17 01:34:31 +0000601 // Set `__heap_base` to directly follow the end of the stack. We don't
602 // allocate any heap memory up front, but instead really on the malloc/brk
603 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000604 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000605 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000606 }
607
608 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
609 NumMemoryPages = MemSize / WasmPageSize;
610 debugPrint("mem: total pages = %d\n", NumMemoryPages);
611}
612
613SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000614 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000616 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000617 OutputSections.push_back(Sec);
618 return Sec;
619}
620
621void Writer::createSections() {
622 // Known sections
623 createTypeSection();
624 createImportSection();
625 createFunctionSection();
626 createTableSection();
627 createMemorySection();
628 createGlobalSection();
629 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000630 createElemSection();
631 createCodeSection();
632 createDataSection();
633
634 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000635 if (Config->Relocatable) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000636 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000637 createLinkingSection();
638 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000639 if (!Config->StripDebug && !Config->StripAll)
640 createNameSection();
641
642 for (OutputSection *S : OutputSections) {
643 S->setOffset(FileSize);
644 S->finalizeContents();
645 FileSize += S->getSize();
646 }
647}
648
Sam Cleggc94d3932017-11-17 18:14:09 +0000649void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000650 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000651 if (!Sym->isUndefined())
652 continue;
653 if (isa<DataSymbol>(Sym))
654 continue;
655 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000656 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000657
Sam Clegg93102972018-02-23 05:08:53 +0000658 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
659 Sym->setOutputIndex(ImportedSymbols.size());
660 ImportedSymbols.emplace_back(Sym);
661 if (isa<FunctionSymbol>(Sym))
662 ++NumImportedFunctions;
663 else
664 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000665 }
666}
667
Sam Cleggd3052d52018-01-18 23:40:49 +0000668void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000669 if (Config->Relocatable)
670 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000671
Sam Clegg93102972018-02-23 05:08:53 +0000672 auto ExportSym = [&](Symbol *Sym) {
673 if (!Sym->isDefined())
674 return;
675 if (Sym->isHidden() || Sym->isLocal())
676 return;
677 if (!Sym->isLive())
678 return;
679
680 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
681
682 if (auto *D = dyn_cast<DefinedData>(Sym)) {
683 // TODO Remove this check here; for non-relocatable output we actually
684 // used only to create fake-global exports for the synthetic symbols. Fix
685 // this in a future commit
686 if (Sym != WasmSym::DataEnd && Sym != WasmSym::HeapBase)
687 return;
688 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd3052d52018-01-18 23:40:49 +0000689 }
Sam Clegg93102972018-02-23 05:08:53 +0000690 ExportedSymbols.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000691 };
692
Sam Clegg93102972018-02-23 05:08:53 +0000693 // TODO The two loops below should be replaced with this single loop, with
694 // ExportSym inlined:
695 // for (Symbol *Sym : Symtab->getSymbols())
696 // ExportSym(Sym);
697 // Making that change would reorder the output though, so it should be done as
698 // a separate commit.
Sam Cleggd3052d52018-01-18 23:40:49 +0000699
Sam Clegg93102972018-02-23 05:08:53 +0000700 for (ObjFile *File : Symtab->ObjectFiles)
701 for (Symbol *Sym : File->getSymbols())
702 if (File == Sym->getFile())
703 ExportSym(Sym);
704
705 for (Symbol *Sym : Symtab->getSymbols())
706 if (Sym->getFile() == nullptr)
707 ExportSym(Sym);
708}
709
710void Writer::assignSymtab() {
711 if (!Config->Relocatable)
712 return;
713
714 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000715 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000716 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000717 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000718 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000719 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000720 if (!Sym->isLive())
721 return;
722 Sym->setOutputSymbolIndex(SymbolIndex++);
723 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000724 }
725 }
726
Sam Clegg93102972018-02-23 05:08:53 +0000727 // For the moment, relocatable output doesn't contain any synthetic functions,
728 // so no need to look through the Symtab for symbols not referenced by
729 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000730}
731
Sam Cleggc375e4e2018-01-10 19:18:22 +0000732uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000733 auto It = TypeIndices.find(Sig);
734 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000735 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000736 return 0;
737 }
738 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000739}
740
741uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000742 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000743 if (Pair.second) {
744 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000745 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000746 }
Sam Cleggb8621592017-11-30 01:40:08 +0000747 return Pair.first->second;
748}
749
Sam Cleggc94d3932017-11-17 18:14:09 +0000750void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000751 // The output type section is the union of the following sets:
752 // 1. Any signature used in the TYPE relocation
753 // 2. The signatures of all imported functions
754 // 3. The signatures of all defined functions
755
Sam Cleggc94d3932017-11-17 18:14:09 +0000756 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000757 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
758 for (uint32_t I = 0; I < Types.size(); I++)
759 if (File->TypeIsUsed[I])
760 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000761 }
Sam Clegg50686852018-01-12 18:35:13 +0000762
Sam Clegg93102972018-02-23 05:08:53 +0000763 for (const Symbol *Sym : ImportedSymbols)
764 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
765 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000766
Sam Clegg9f934222018-02-21 18:29:23 +0000767 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000768 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000769}
770
Sam Clegg8d146bb2018-01-09 23:56:44 +0000771void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000772 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000773 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000774 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
775 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000776 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000777 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000778 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000779 Func->setOutputIndex(FunctionIndex++);
780 }
781 }
782
Sam Clegg93102972018-02-23 05:08:53 +0000783 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000784 auto HandleRelocs = [&](InputChunk *Chunk) {
785 if (!Chunk->Live)
786 return;
787 ObjFile *File = Chunk->File;
788 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000789 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000790 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
791 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
792 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
793 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
794 continue;
795 Sym->setTableIndex(TableIndex++);
796 IndirectFunctions.emplace_back(Sym);
797 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000798 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000799 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
800 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000801 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
802 // Mark target global as live
803 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
804 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
805 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
806 G->Global->Live = true;
807 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000808 }
809 }
810 };
811
Sam Clegg8d146bb2018-01-09 23:56:44 +0000812 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000813 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000814 for (InputChunk *Chunk : File->Functions)
815 HandleRelocs(Chunk);
816 for (InputChunk *Chunk : File->Segments)
817 HandleRelocs(Chunk);
818 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000819
Sam Clegg93102972018-02-23 05:08:53 +0000820 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
821 auto AddDefinedGlobal = [&](InputGlobal *Global) {
822 if (Global->Live) {
823 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
824 Global->setOutputIndex(GlobalIndex++);
825 InputGlobals.push_back(Global);
826 }
827 };
828
829 if (WasmSym::StackPointer)
830 AddDefinedGlobal(WasmSym::StackPointer->Global);
831
832 for (ObjFile *File : Symtab->ObjectFiles) {
833 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
834 for (InputGlobal *Global : File->Globals)
835 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000836 }
837}
838
839static StringRef getOutputDataSegmentName(StringRef Name) {
840 if (Config->Relocatable)
841 return Name;
842
843 for (StringRef V :
844 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
845 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
846 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
847 StringRef Prefix = V.drop_back();
848 if (Name.startswith(V) || Name == Prefix)
849 return Prefix;
850 }
851
852 return Name;
853}
854
855void Writer::createOutputSegments() {
856 for (ObjFile *File : Symtab->ObjectFiles) {
857 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000858 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000859 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000860 StringRef Name = getOutputDataSegmentName(Segment->getName());
861 OutputSegment *&S = SegmentMap[Name];
862 if (S == nullptr) {
863 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000864 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000865 Segments.push_back(S);
866 }
867 S->addInputSegment(Segment);
868 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000869 }
870 }
871}
872
Sam Clegg50686852018-01-12 18:35:13 +0000873static const int OPCODE_CALL = 0x10;
874static const int OPCODE_END = 0xb;
875
876// Create synthetic "__wasm_call_ctors" function based on ctor functions
877// in input object.
878void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000879 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000880 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000881
882 // First write the body bytes to a string.
883 std::string FunctionBody;
Sam Clegg93102972018-02-23 05:08:53 +0000884 const WasmSignature *Signature = WasmSym::CallCtors->getFunctionType();
Sam Clegg50686852018-01-12 18:35:13 +0000885 {
886 raw_string_ostream OS(FunctionBody);
887 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000888 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000889 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000890 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000891 }
892 writeU8(OS, OPCODE_END, "END");
893 }
894
895 // Once we know the size of the body we can create the final function body
896 raw_string_ostream OS(CtorFunctionBody);
897 writeUleb128(OS, FunctionBody.size(), "function size");
898 OS.flush();
899 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000900 ArrayRef<uint8_t> BodyArray(
901 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
902 CtorFunctionBody.size());
Sam Clegg93102972018-02-23 05:08:53 +0000903 SyntheticFunction *F = make<SyntheticFunction>(*Signature, BodyArray,
Sam Clegg011dce22018-02-21 18:37:44 +0000904 WasmSym::CallCtors->getName());
905 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000906 F->Live = true;
907 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000908 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000909}
910
911// Populate InitFunctions vector with init functions from all input objects.
912// This is then used either when creating the output linking section or to
913// synthesize the "__wasm_call_ctors" function.
914void Writer::calculateInitFunctions() {
915 for (ObjFile *File : Symtab->ObjectFiles) {
916 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Sam Clegg50686852018-01-12 18:35:13 +0000917 for (const WasmInitFunc &F : L.InitFunctions)
Sam Clegg93102972018-02-23 05:08:53 +0000918 InitFunctions.emplace_back(
919 WasmInitEntry{File->getFunctionSymbol(F.Symbol), F.Priority});
Sam Clegg50686852018-01-12 18:35:13 +0000920 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000921
Sam Clegg50686852018-01-12 18:35:13 +0000922 // Sort in order of priority (lowest first) so that they are called
923 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000924 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000925 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000926 return L.Priority < R.Priority;
927 });
Sam Clegg50686852018-01-12 18:35:13 +0000928}
929
Sam Cleggc94d3932017-11-17 18:14:09 +0000930void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000931 if (Config->Relocatable)
932 Config->GlobalBase = 0;
933
Sam Cleggc94d3932017-11-17 18:14:09 +0000934 log("-- calculateImports");
935 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000936 log("-- assignIndexes");
937 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000938 log("-- calculateInitFunctions");
939 calculateInitFunctions();
940 if (!Config->Relocatable)
941 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000942 log("-- calculateTypes");
943 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000944 log("-- layoutMemory");
945 layoutMemory();
946 log("-- calculateExports");
947 calculateExports();
948 log("-- assignSymtab");
949 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000950
951 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000952 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000953 log("Defined Globals : " + Twine(InputGlobals.size()));
954 log("Function Imports : " + Twine(NumImportedFunctions));
955 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000956 for (ObjFile *File : Symtab->ObjectFiles)
957 File->dumpInfo();
958 }
959
Sam Cleggc94d3932017-11-17 18:14:09 +0000960 createHeader();
961 log("-- createSections");
962 createSections();
963
964 log("-- openFile");
965 openFile();
966 if (errorCount())
967 return;
968
969 writeHeader();
970
971 log("-- writeSections");
972 writeSections();
973 if (errorCount())
974 return;
975
976 if (Error E = Buffer->commit())
977 fatal("failed to write the output file: " + toString(std::move(E)));
978}
979
980// Open a result file.
981void Writer::openFile() {
982 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000983
984 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
985 FileOutputBuffer::create(Config->OutputFile, FileSize,
986 FileOutputBuffer::F_executable);
987
988 if (!BufferOrErr)
989 error("failed to open " + Config->OutputFile + ": " +
990 toString(BufferOrErr.takeError()));
991 else
992 Buffer = std::move(*BufferOrErr);
993}
994
995void Writer::createHeader() {
996 raw_string_ostream OS(Header);
997 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
998 writeU32(OS, WasmVersion, "wasm version");
999 OS.flush();
1000 FileSize += Header.size();
1001}
1002
1003void lld::wasm::writeResult() { Writer().run(); }