blob: 1b7cde1e91b0a42a12e98239512f404faba8bb5d [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) {
Rui Ueyamaba16bac2018-02-28 17:32:50 +000056 unsigned H = hash_value(Sig.ReturnType);
Sam Cleggc94d3932017-11-17 18:14:09 +000057 for (int32_t Param : Sig.ParamTypes)
Rui Ueyamaba16bac2018-02-28 17:32:50 +000058 H = hash_combine(H, Param);
59 return H;
Sam Cleggc94d3932017-11-17 18:14:09 +000060 }
61 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
62 return LHS == RHS;
63 }
64};
65
Sam Clegg93102972018-02-23 05:08:53 +000066// An init entry to be written to either the synthetic init func or the
67// linking metadata.
68struct WasmInitEntry {
Sam Clegg811236c2018-01-19 03:31:07 +000069 const Symbol *Sym;
Sam Clegg93102972018-02-23 05:08:53 +000070 uint32_t Priority;
Sam Cleggd3052d52018-01-18 23:40:49 +000071};
72
Sam Cleggc94d3932017-11-17 18:14:09 +000073// The writer writes a SymbolTable result to a file.
74class Writer {
75public:
76 void run();
77
78private:
79 void openFile();
80
Sam Cleggc375e4e2018-01-10 19:18:22 +000081 uint32_t lookupType(const WasmSignature &Sig);
82 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg93102972018-02-23 05:08:53 +000083
Sam Clegg50686852018-01-12 18:35:13 +000084 void createCtorFunction();
85 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000086 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000087 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000088 void calculateExports();
Sam Clegg93102972018-02-23 05:08:53 +000089 void assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +000090 void calculateTypes();
91 void createOutputSegments();
92 void layoutMemory();
93 void createHeader();
94 void createSections();
95 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000096 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000097
98 // Builtin sections
99 void createTypeSection();
100 void createFunctionSection();
101 void createTableSection();
102 void createGlobalSection();
103 void createExportSection();
104 void createImportSection();
105 void createMemorySection();
106 void createElemSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000107 void createCodeSection();
108 void createDataSection();
109
110 // Custom sections
111 void createRelocSections();
112 void createLinkingSection();
113 void createNameSection();
114
115 void writeHeader();
116 void writeSections();
117
118 uint64_t FileSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000119 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000120
121 std::vector<const WasmSignature *> Types;
122 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg93102972018-02-23 05:08:53 +0000123 std::vector<const Symbol *> ImportedSymbols;
124 unsigned NumImportedFunctions = 0;
125 unsigned NumImportedGlobals = 0;
126 std::vector<Symbol *> ExportedSymbols;
127 std::vector<const DefinedData *> DefinedFakeGlobals;
128 std::vector<InputGlobal *> InputGlobals;
Sam Clegg9f934222018-02-21 18:29:23 +0000129 std::vector<InputFunction *> InputFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000130 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg93102972018-02-23 05:08:53 +0000131 std::vector<const Symbol *> SymtabEntries;
132 std::vector<WasmInitEntry> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000133
134 // Elements that are used to construct the final output
135 std::string Header;
136 std::vector<OutputSection *> OutputSections;
137
138 std::unique_ptr<FileOutputBuffer> Buffer;
139
140 std::vector<OutputSegment *> Segments;
141 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
142};
143
144} // anonymous namespace
145
146static void debugPrint(const char *fmt, ...) {
147 if (!errorHandler().Verbose)
148 return;
149 fprintf(stderr, "lld: ");
150 va_list ap;
151 va_start(ap, fmt);
152 vfprintf(stderr, fmt, ap);
153 va_end(ap);
154}
155
156void Writer::createImportSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000157 uint32_t NumImports = ImportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000158 if (Config->ImportMemory)
159 ++NumImports;
160
161 if (NumImports == 0)
162 return;
163
164 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
165 raw_ostream &OS = Section->getStream();
166
167 writeUleb128(OS, NumImports, "import count");
168
Sam Cleggc94d3932017-11-17 18:14:09 +0000169 if (Config->ImportMemory) {
170 WasmImport Import;
171 Import.Module = "env";
172 Import.Field = "memory";
173 Import.Kind = WASM_EXTERNAL_MEMORY;
174 Import.Memory.Flags = 0;
175 Import.Memory.Initial = NumMemoryPages;
176 writeImport(OS, Import);
177 }
178
Sam Clegg93102972018-02-23 05:08:53 +0000179 for (const Symbol *Sym : ImportedSymbols) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000180 WasmImport Import;
181 Import.Module = "env";
182 Import.Field = Sym->getName();
Sam Clegg93102972018-02-23 05:08:53 +0000183 if (auto *FunctionSym = dyn_cast<FunctionSymbol>(Sym)) {
184 Import.Kind = WASM_EXTERNAL_FUNCTION;
185 Import.SigIndex = lookupType(*FunctionSym->getFunctionType());
186 } else {
187 auto *GlobalSym = cast<GlobalSymbol>(Sym);
188 Import.Kind = WASM_EXTERNAL_GLOBAL;
189 Import.Global = *GlobalSym->getGlobalType();
190 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000191 writeImport(OS, Import);
192 }
193}
194
195void Writer::createTypeSection() {
196 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
197 raw_ostream &OS = Section->getStream();
198 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000199 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000200 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000201}
202
203void Writer::createFunctionSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000204 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000205 return;
206
207 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
208 raw_ostream &OS = Section->getStream();
209
Sam Clegg9f934222018-02-21 18:29:23 +0000210 writeUleb128(OS, InputFunctions.size(), "function count");
211 for (const InputFunction *Func : InputFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000212 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000213}
214
215void Writer::createMemorySection() {
216 if (Config->ImportMemory)
217 return;
218
219 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
220 raw_ostream &OS = Section->getStream();
221
222 writeUleb128(OS, 1, "memory count");
223 writeUleb128(OS, 0, "memory limits flags");
224 writeUleb128(OS, NumMemoryPages, "initial pages");
225}
226
227void Writer::createGlobalSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000228 unsigned NumGlobals = InputGlobals.size() + DefinedFakeGlobals.size();
229 if (NumGlobals == 0)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000230 return;
231
Sam Cleggc94d3932017-11-17 18:14:09 +0000232 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
233 raw_ostream &OS = Section->getStream();
234
Sam Clegg93102972018-02-23 05:08:53 +0000235 writeUleb128(OS, NumGlobals, "global count");
236 for (const InputGlobal *G : InputGlobals)
237 writeGlobal(OS, G->Global);
238 for (const DefinedData *Sym : DefinedFakeGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000239 WasmGlobal Global;
Sam Clegg93102972018-02-23 05:08:53 +0000240 Global.Type = {WASM_TYPE_I32, false};
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000241 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
242 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000243 writeGlobal(OS, Global);
244 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000245}
246
247void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000248 // Always output a table section, even if there are no indirect calls.
249 // There are two reasons for this:
250 // 1. For executables it is useful to have an empty table slot at 0
251 // which can be filled with a null function call handler.
252 // 2. If we don't do this, any program that contains a call_indirect but
253 // no address-taken function will fail at validation time since it is
254 // a validation error to include a call_indirect instruction if there
255 // is not table.
Sam Clegg48bbd632018-01-24 21:37:30 +0000256 uint32_t TableSize = kInitialTableOffset + IndirectFunctions.size();
Sam Cleggfc1a9122017-12-11 22:00:56 +0000257
Sam Cleggc94d3932017-11-17 18:14:09 +0000258 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
259 raw_ostream &OS = Section->getStream();
260
261 writeUleb128(OS, 1, "table count");
Sam Clegg8518e7d2018-03-01 18:06:39 +0000262 writeU8(OS, WASM_TYPE_ANYFUNC, "table type");
Sam Cleggc94d3932017-11-17 18:14:09 +0000263 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000264 writeUleb128(OS, TableSize, "table initial size");
265 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000266}
267
268void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000269 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Cleggc94d3932017-11-17 18:14:09 +0000270
Sam Cleggd3052d52018-01-18 23:40:49 +0000271 uint32_t NumExports = (ExportMemory ? 1 : 0) + ExportedSymbols.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000272 if (!NumExports)
273 return;
274
275 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
276 raw_ostream &OS = Section->getStream();
277
278 writeUleb128(OS, NumExports, "export count");
279
Rui Ueyama7d696882018-02-28 00:18:34 +0000280 if (ExportMemory)
281 writeExport(OS, {"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggc94d3932017-11-17 18:14:09 +0000282
Sam Clegg93102972018-02-23 05:08:53 +0000283 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
Rui Ueyama7d696882018-02-28 00:18:34 +0000284
Sam Clegg93102972018-02-23 05:08:53 +0000285 for (const Symbol *Sym : ExportedSymbols) {
Rui Ueyama7d696882018-02-28 00:18:34 +0000286 StringRef Name = Sym->getName();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000287 WasmExport Export;
Rui Ueyama7d696882018-02-28 00:18:34 +0000288 DEBUG(dbgs() << "Export: " << Name << "\n");
289
290 if (isa<DefinedFunction>(Sym))
291 Export = {Name, WASM_EXTERNAL_FUNCTION, Sym->getOutputIndex()};
292 else if (isa<DefinedGlobal>(Sym))
293 Export = {Name, WASM_EXTERNAL_GLOBAL, Sym->getOutputIndex()};
294 else if (isa<DefinedData>(Sym))
295 Export = {Name, WASM_EXTERNAL_GLOBAL, FakeGlobalIndex++};
296 else
Sam Clegg93102972018-02-23 05:08:53 +0000297 llvm_unreachable("unexpected symbol type");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000298 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000299 }
300}
301
Sam Cleggc94d3932017-11-17 18:14:09 +0000302void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000303 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000304 return;
305
306 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
307 raw_ostream &OS = Section->getStream();
308
309 writeUleb128(OS, 1, "segment count");
310 writeUleb128(OS, 0, "table index");
311 WasmInitExpr InitExpr;
312 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000313 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000314 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000315 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000316
Sam Clegg48bbd632018-01-24 21:37:30 +0000317 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000318 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000319 assert(Sym->getTableIndex() == TableIndex);
320 writeUleb128(OS, Sym->getOutputIndex(), "function index");
321 ++TableIndex;
322 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000323}
324
325void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000326 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000327 return;
328
329 log("createCodeSection");
330
Sam Clegg9f934222018-02-21 18:29:23 +0000331 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000332 OutputSections.push_back(Section);
333}
334
335void Writer::createDataSection() {
336 if (!Segments.size())
337 return;
338
339 log("createDataSection");
340 auto Section = make<DataSection>(Segments);
341 OutputSections.push_back(Section);
342}
343
Sam Cleggd451da12017-12-19 19:56:27 +0000344// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000345// These are only created when relocatable output is requested.
346void Writer::createRelocSections() {
347 log("createRelocSections");
348 // Don't use iterator here since we are adding to OutputSection
349 size_t OrigSize = OutputSections.size();
350 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000351 OutputSection *OSec = OutputSections[i];
352 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000353 if (!Count)
354 continue;
355
Rui Ueyama37254062018-02-28 00:01:31 +0000356 StringRef Name;
357 if (OSec->Type == WASM_SEC_DATA)
358 Name = "reloc.DATA";
359 else if (OSec->Type == WASM_SEC_CODE)
360 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000361 else
Sam Cleggd451da12017-12-19 19:56:27 +0000362 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000363
Rui Ueyama37254062018-02-28 00:01:31 +0000364 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000365 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000366 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000367 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000368 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 }
370}
371
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000372static uint32_t getWasmFlags(const Symbol *Sym) {
373 uint32_t Flags = 0;
374 if (Sym->isLocal())
375 Flags |= WASM_SYMBOL_BINDING_LOCAL;
376 if (Sym->isWeak())
377 Flags |= WASM_SYMBOL_BINDING_WEAK;
378 if (Sym->isHidden())
379 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
380 if (Sym->isUndefined())
381 Flags |= WASM_SYMBOL_UNDEFINED;
382 return Flags;
383}
384
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000385// Some synthetic sections (e.g. "name" and "linking") have subsections.
386// Just like the synthetic sections themselves these need to be created before
387// they can be written out (since they are preceded by their length). This
388// class is used to create subsections and then write them into the stream
389// of the parent section.
390class SubSection {
391public:
392 explicit SubSection(uint32_t Type) : Type(Type) {}
393
394 void writeTo(raw_ostream &To) {
395 OS.flush();
Rui Ueyama67769102018-02-28 03:38:14 +0000396 writeUleb128(To, Type, "subsection type");
397 writeUleb128(To, Body.size(), "subsection size");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000398 To.write(Body.data(), Body.size());
399 }
400
401private:
402 uint32_t Type;
403 std::string Body;
404
405public:
406 raw_string_ostream OS{Body};
407};
408
Sam Clegg49ed9262017-12-01 00:53:21 +0000409// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000410// This is only created when relocatable output is requested.
411void Writer::createLinkingSection() {
412 SyntheticSection *Section =
413 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
414 raw_ostream &OS = Section->getStream();
415
Sam Clegg0d0dd392017-12-19 17:09:45 +0000416 if (!Config->Relocatable)
417 return;
418
Sam Clegg93102972018-02-23 05:08:53 +0000419 if (!SymtabEntries.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000420 SubSection Sub(WASM_SYMBOL_TABLE);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000421 writeUleb128(Sub.OS, SymtabEntries.size(), "num symbols");
422
Sam Clegg93102972018-02-23 05:08:53 +0000423 for (const Symbol *Sym : SymtabEntries) {
424 assert(Sym->isDefined() || Sym->isUndefined());
425 WasmSymbolType Kind = Sym->getWasmType();
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000426 uint32_t Flags = getWasmFlags(Sym);
427
Sam Clegg8518e7d2018-03-01 18:06:39 +0000428 writeU8(Sub.OS, Kind, "sym kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000429 writeUleb128(Sub.OS, Flags, "sym flags");
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000430
Sam Clegg93102972018-02-23 05:08:53 +0000431 switch (Kind) {
432 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
433 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000434 writeUleb128(Sub.OS, Sym->getOutputIndex(), "index");
Sam Clegg93102972018-02-23 05:08:53 +0000435 if (Sym->isDefined())
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000436 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000437 break;
438 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000439 writeStr(Sub.OS, Sym->getName(), "sym name");
Sam Clegg93102972018-02-23 05:08:53 +0000440 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000441 writeUleb128(Sub.OS, DataSym->getOutputSegmentIndex(), "index");
442 writeUleb128(Sub.OS, DataSym->getOutputSegmentOffset(),
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000443 "data offset");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000444 writeUleb128(Sub.OS, DataSym->getSize(), "data size");
Sam Clegg93102972018-02-23 05:08:53 +0000445 }
446 break;
447 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000448 }
Rui Ueyama8bfa2a62018-02-28 00:28:07 +0000449
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000450 Sub.writeTo(OS);
Sam Cleggd3052d52018-01-18 23:40:49 +0000451 }
452
Sam Clegg0d0dd392017-12-19 17:09:45 +0000453 if (Segments.size()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000454 SubSection Sub(WASM_SEGMENT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000455 writeUleb128(Sub.OS, Segments.size(), "num data segments");
Sam Cleggc94d3932017-11-17 18:14:09 +0000456 for (const OutputSegment *S : Segments) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000457 writeStr(Sub.OS, S->Name, "segment name");
458 writeUleb128(Sub.OS, S->Alignment, "alignment");
459 writeUleb128(Sub.OS, 0, "flags");
Sam Cleggc94d3932017-11-17 18:14:09 +0000460 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000461 Sub.writeTo(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000462 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000463
Sam Clegg0d0dd392017-12-19 17:09:45 +0000464 if (!InitFunctions.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000465 SubSection Sub(WASM_INIT_FUNCS);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000466 writeUleb128(Sub.OS, InitFunctions.size(), "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000467 for (const WasmInitEntry &F : InitFunctions) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000468 writeUleb128(Sub.OS, F.Priority, "priority");
469 writeUleb128(Sub.OS, F.Sym->getOutputSymbolIndex(), "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000470 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000471 Sub.writeTo(OS);
Sam Clegg0d0dd392017-12-19 17:09:45 +0000472 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000473
474 struct ComdatEntry { unsigned Kind; uint32_t Index; };
475 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
476
Sam Clegg9f934222018-02-21 18:29:23 +0000477 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000478 StringRef Comdat = F->getComdat();
479 if (!Comdat.empty())
480 Comdats[Comdat].emplace_back(
481 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
482 }
483 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000484 const auto &InputSegments = Segments[I]->InputSegments;
485 if (InputSegments.empty())
486 continue;
487 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000488#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000489 for (const InputSegment *IS : InputSegments)
490 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000491#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000492 if (!Comdat.empty())
493 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
494 }
495
496 if (!Comdats.empty()) {
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000497 SubSection Sub(WASM_COMDAT_INFO);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000498 writeUleb128(Sub.OS, Comdats.size(), "num comdats");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000499 for (const auto &C : Comdats) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000500 writeStr(Sub.OS, C.first, "comdat name");
501 writeUleb128(Sub.OS, 0, "comdat flags"); // flags for future use
502 writeUleb128(Sub.OS, C.second.size(), "num entries");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000503 for (const ComdatEntry &Entry : C.second) {
Sam Clegg8518e7d2018-03-01 18:06:39 +0000504 writeU8(Sub.OS, Entry.Kind, "entry kind");
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000505 writeUleb128(Sub.OS, Entry.Index, "entry index");
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000506 }
507 }
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000508 Sub.writeTo(OS);
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000509 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000510}
511
512// Create the custom "name" section containing debug symbol names.
513void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000514 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000515 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000516 if (!F->getName().empty())
517 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000518
Sam Clegg1963d712018-01-17 20:19:04 +0000519 if (NumNames == 0)
520 return;
Sam Clegg50686852018-01-12 18:35:13 +0000521
Sam Cleggc94d3932017-11-17 18:14:09 +0000522 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
523
Rui Ueyama19eedbf2018-02-28 00:39:30 +0000524 SubSection Sub(WASM_NAMES_FUNCTION);
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000525 writeUleb128(Sub.OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000526
Sam Clegg93102972018-02-23 05:08:53 +0000527 // Names must appear in function index order. As it happens ImportedSymbols
528 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000529 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000530 for (const Symbol *S : ImportedSymbols) {
531 if (!isa<FunctionSymbol>(S))
532 continue;
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000533 writeUleb128(Sub.OS, S->getOutputIndex(), "import index");
534 writeStr(Sub.OS, S->getName(), "symbol name");
Sam Cleggc94d3932017-11-17 18:14:09 +0000535 }
Sam Clegg9f934222018-02-21 18:29:23 +0000536 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000537 if (!F->getName().empty()) {
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000538 writeUleb128(Sub.OS, F->getOutputIndex(), "func index");
539 writeStr(Sub.OS, F->getName(), "symbol name");
Sam Clegg1963d712018-01-17 20:19:04 +0000540 }
541 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000542
Rui Ueyama4a1b2bb2018-02-28 00:52:42 +0000543 Sub.writeTo(Section->getStream());
Sam Cleggc94d3932017-11-17 18:14:09 +0000544}
545
546void Writer::writeHeader() {
547 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
548}
549
550void Writer::writeSections() {
551 uint8_t *Buf = Buffer->getBufferStart();
552 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
553}
554
555// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000556// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000557// The memory layout is as follows, from low to high.
558// - initialized data (starting at Config->GlobalBase)
559// - BSS data (not currently implemented in llvm)
560// - explicit stack (Config->ZStackSize)
561// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000562void Writer::layoutMemory() {
563 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000564 MemoryPtr = Config->GlobalBase;
565 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000566
567 createOutputSegments();
568
Sam Cleggf0d433d2018-02-02 22:59:56 +0000569 // Arbitrarily set __dso_handle handle to point to the start of the data
570 // segments.
571 if (WasmSym::DsoHandle)
572 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
573
Sam Cleggc94d3932017-11-17 18:14:09 +0000574 for (OutputSegment *Seg : Segments) {
575 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
576 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000577 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000578 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
579 MemoryPtr += Seg->Size;
580 }
581
Sam Cleggf0d433d2018-02-02 22:59:56 +0000582 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000583 if (WasmSym::DataEnd)
584 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000585
Sam Clegg99eb42c2018-02-27 23:58:03 +0000586 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000587
Sam Cleggf0d433d2018-02-02 22:59:56 +0000588 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000589 if (!Config->Relocatable) {
590 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
591 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
592 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
593 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
594 debugPrint("mem: stack base = %d\n", MemoryPtr);
595 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000596 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000597 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000598
Sam Clegg51bcdc22018-01-17 01:34:31 +0000599 // Set `__heap_base` to directly follow the end of the stack. We don't
600 // allocate any heap memory up front, but instead really on the malloc/brk
601 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000602 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000603 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000604 }
605
606 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
607 NumMemoryPages = MemSize / WasmPageSize;
608 debugPrint("mem: total pages = %d\n", NumMemoryPages);
609}
610
611SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000612 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000613 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000614 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 OutputSections.push_back(Sec);
616 return Sec;
617}
618
619void Writer::createSections() {
620 // Known sections
621 createTypeSection();
622 createImportSection();
623 createFunctionSection();
624 createTableSection();
625 createMemorySection();
626 createGlobalSection();
627 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000628 createElemSection();
629 createCodeSection();
630 createDataSection();
631
632 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000633 if (Config->Relocatable) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000634 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000635 createLinkingSection();
636 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000637 if (!Config->StripDebug && !Config->StripAll)
638 createNameSection();
639
640 for (OutputSection *S : OutputSections) {
641 S->setOffset(FileSize);
642 S->finalizeContents();
643 FileSize += S->getSize();
644 }
645}
646
Sam Cleggc94d3932017-11-17 18:14:09 +0000647void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000648 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000649 if (!Sym->isUndefined())
650 continue;
651 if (isa<DataSymbol>(Sym))
652 continue;
653 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000654 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000655
Sam Clegg93102972018-02-23 05:08:53 +0000656 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
657 Sym->setOutputIndex(ImportedSymbols.size());
658 ImportedSymbols.emplace_back(Sym);
659 if (isa<FunctionSymbol>(Sym))
660 ++NumImportedFunctions;
661 else
662 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000663 }
664}
665
Sam Cleggd3052d52018-01-18 23:40:49 +0000666void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000667 if (Config->Relocatable)
668 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000669
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000670 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000671 if (!Sym->isDefined())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000672 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000673 if (Sym->isHidden() || Sym->isLocal())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000674 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000675 if (!Sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000676 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000677
678 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
679
680 if (auto *D = dyn_cast<DefinedData>(Sym)) {
681 // TODO Remove this check here; for non-relocatable output we actually
682 // used only to create fake-global exports for the synthetic symbols. Fix
683 // this in a future commit
684 if (Sym != WasmSym::DataEnd && Sym != WasmSym::HeapBase)
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000685 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000686 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd3052d52018-01-18 23:40:49 +0000687 }
Sam Clegg93102972018-02-23 05:08:53 +0000688 ExportedSymbols.emplace_back(Sym);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000689 }
Sam Clegg93102972018-02-23 05:08:53 +0000690}
691
692void Writer::assignSymtab() {
693 if (!Config->Relocatable)
694 return;
695
696 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000697 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000698 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000699 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000700 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000701 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000702 if (!Sym->isLive())
703 return;
704 Sym->setOutputSymbolIndex(SymbolIndex++);
705 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000706 }
707 }
708
Sam Clegg93102972018-02-23 05:08:53 +0000709 // For the moment, relocatable output doesn't contain any synthetic functions,
710 // so no need to look through the Symtab for symbols not referenced by
711 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000712}
713
Sam Cleggc375e4e2018-01-10 19:18:22 +0000714uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000715 auto It = TypeIndices.find(Sig);
716 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000717 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000718 return 0;
719 }
720 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000721}
722
723uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000724 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000725 if (Pair.second) {
726 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000727 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000728 }
Sam Cleggb8621592017-11-30 01:40:08 +0000729 return Pair.first->second;
730}
731
Sam Cleggc94d3932017-11-17 18:14:09 +0000732void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000733 // The output type section is the union of the following sets:
734 // 1. Any signature used in the TYPE relocation
735 // 2. The signatures of all imported functions
736 // 3. The signatures of all defined functions
737
Sam Cleggc94d3932017-11-17 18:14:09 +0000738 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000739 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
740 for (uint32_t I = 0; I < Types.size(); I++)
741 if (File->TypeIsUsed[I])
742 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000743 }
Sam Clegg50686852018-01-12 18:35:13 +0000744
Sam Clegg93102972018-02-23 05:08:53 +0000745 for (const Symbol *Sym : ImportedSymbols)
746 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
747 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000748
Sam Clegg9f934222018-02-21 18:29:23 +0000749 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000750 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000751}
752
Sam Clegg8d146bb2018-01-09 23:56:44 +0000753void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000754 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Clegg87e61922018-01-08 23:39:11 +0000755 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000756 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
757 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000758 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000759 continue;
Sam Clegg9f934222018-02-21 18:29:23 +0000760 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000761 Func->setOutputIndex(FunctionIndex++);
762 }
763 }
764
Sam Clegg93102972018-02-23 05:08:53 +0000765 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000766 auto HandleRelocs = [&](InputChunk *Chunk) {
767 if (!Chunk->Live)
768 return;
769 ObjFile *File = Chunk->File;
770 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000771 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000772 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
773 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
774 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
775 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
776 continue;
777 Sym->setTableIndex(TableIndex++);
778 IndirectFunctions.emplace_back(Sym);
779 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
Sam Clegg93102972018-02-23 05:08:53 +0000780 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000781 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
782 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000783 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
784 // Mark target global as live
785 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
786 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
787 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
788 G->Global->Live = true;
789 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000790 }
791 }
792 };
793
Sam Clegg8d146bb2018-01-09 23:56:44 +0000794 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000795 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000796 for (InputChunk *Chunk : File->Functions)
797 HandleRelocs(Chunk);
798 for (InputChunk *Chunk : File->Segments)
799 HandleRelocs(Chunk);
800 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000801
Sam Clegg93102972018-02-23 05:08:53 +0000802 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
803 auto AddDefinedGlobal = [&](InputGlobal *Global) {
804 if (Global->Live) {
805 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
806 Global->setOutputIndex(GlobalIndex++);
807 InputGlobals.push_back(Global);
808 }
809 };
810
811 if (WasmSym::StackPointer)
812 AddDefinedGlobal(WasmSym::StackPointer->Global);
813
814 for (ObjFile *File : Symtab->ObjectFiles) {
815 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
816 for (InputGlobal *Global : File->Globals)
817 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000818 }
819}
820
821static StringRef getOutputDataSegmentName(StringRef Name) {
822 if (Config->Relocatable)
823 return Name;
Rui Ueyama4764b572018-02-28 00:57:28 +0000824 if (Name.startswith(".text."))
825 return ".text";
826 if (Name.startswith(".data."))
827 return ".data";
828 if (Name.startswith(".bss."))
829 return ".bss";
Sam Cleggc94d3932017-11-17 18:14:09 +0000830 return Name;
831}
832
833void Writer::createOutputSegments() {
834 for (ObjFile *File : Symtab->ObjectFiles) {
835 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000836 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000837 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000838 StringRef Name = getOutputDataSegmentName(Segment->getName());
839 OutputSegment *&S = SegmentMap[Name];
840 if (S == nullptr) {
841 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000842 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000843 Segments.push_back(S);
844 }
845 S->addInputSegment(Segment);
846 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000847 }
848 }
849}
850
Sam Clegg50686852018-01-12 18:35:13 +0000851static const int OPCODE_CALL = 0x10;
852static const int OPCODE_END = 0xb;
853
854// Create synthetic "__wasm_call_ctors" function based on ctor functions
855// in input object.
856void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000857 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000858 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000859
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000860 // First write the body's contents to a string.
861 std::string BodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000862 {
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000863 raw_string_ostream OS(BodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000864 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000865 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000866 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000867 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000868 }
869 writeU8(OS, OPCODE_END, "END");
870 }
871
872 // Once we know the size of the body we can create the final function body
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000873 std::string FunctionBody;
874 {
875 raw_string_ostream OS(FunctionBody);
876 writeUleb128(OS, BodyContent.size(), "function size");
877 OS << BodyContent;
878 }
Rui Ueyama29abfe42018-02-28 17:43:15 +0000879
880 const WasmSignature *Sig = WasmSym::CallCtors->getFunctionType();
881 SyntheticFunction *F = make<SyntheticFunction>(
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000882 *Sig, std::move(FunctionBody), WasmSym::CallCtors->getName());
Rui Ueyama29abfe42018-02-28 17:43:15 +0000883
Sam Clegg011dce22018-02-21 18:37:44 +0000884 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000885 F->Live = true;
886 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000887 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000888}
889
890// Populate InitFunctions vector with init functions from all input objects.
891// This is then used either when creating the output linking section or to
892// synthesize the "__wasm_call_ctors" function.
893void Writer::calculateInitFunctions() {
894 for (ObjFile *File : Symtab->ObjectFiles) {
895 const WasmLinkingData &L = File->getWasmObj()->linkingData();
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000896 for (const WasmInitFunc &F : L.InitFunctions) {
897 FunctionSymbol *Sym = File->getFunctionSymbol(F.Symbol);
898 if (*Sym->getFunctionType() != WasmSignature{{}, WASM_TYPE_NORESULT})
899 error("invalid signature for init func: " + toString(*Sym));
900 InitFunctions.emplace_back(WasmInitEntry{Sym, F.Priority});
901 }
Sam Clegg50686852018-01-12 18:35:13 +0000902 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000903
Sam Clegg50686852018-01-12 18:35:13 +0000904 // Sort in order of priority (lowest first) so that they are called
905 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000906 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000907 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000908 return L.Priority < R.Priority;
909 });
Sam Clegg50686852018-01-12 18:35:13 +0000910}
911
Sam Cleggc94d3932017-11-17 18:14:09 +0000912void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000913 if (Config->Relocatable)
914 Config->GlobalBase = 0;
915
Sam Cleggc94d3932017-11-17 18:14:09 +0000916 log("-- calculateImports");
917 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000918 log("-- assignIndexes");
919 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000920 log("-- calculateInitFunctions");
921 calculateInitFunctions();
922 if (!Config->Relocatable)
923 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000924 log("-- calculateTypes");
925 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000926 log("-- layoutMemory");
927 layoutMemory();
928 log("-- calculateExports");
929 calculateExports();
930 log("-- assignSymtab");
931 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000932
933 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000934 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000935 log("Defined Globals : " + Twine(InputGlobals.size()));
936 log("Function Imports : " + Twine(NumImportedFunctions));
937 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000938 for (ObjFile *File : Symtab->ObjectFiles)
939 File->dumpInfo();
940 }
941
Sam Cleggc94d3932017-11-17 18:14:09 +0000942 createHeader();
943 log("-- createSections");
944 createSections();
945
946 log("-- openFile");
947 openFile();
948 if (errorCount())
949 return;
950
951 writeHeader();
952
953 log("-- writeSections");
954 writeSections();
955 if (errorCount())
956 return;
957
958 if (Error E = Buffer->commit())
959 fatal("failed to write the output file: " + toString(std::move(E)));
960}
961
962// Open a result file.
963void Writer::openFile() {
964 log("writing: " + Config->OutputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000965
966 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
967 FileOutputBuffer::create(Config->OutputFile, FileSize,
968 FileOutputBuffer::F_executable);
969
970 if (!BufferOrErr)
971 error("failed to open " + Config->OutputFile + ": " +
972 toString(BufferOrErr.takeError()));
973 else
974 Buffer = std::move(*BufferOrErr);
975}
976
977void Writer::createHeader() {
978 raw_string_ostream OS(Header);
979 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
980 writeU32(OS, WasmVersion, "wasm version");
981 OS.flush();
982 FileSize += Header.size();
983}
984
985void lld::wasm::writeResult() { Writer().run(); }