blob: b4e034a6b1683923a90cd44edb54d5ca5ae88ec2 [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"
11
Sam Clegg50686852018-01-12 18:35:13 +000012#include "llvm/ADT/DenseSet.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000013#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000014#include "InputChunks.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000015#include "OutputSections.h"
16#include "OutputSegment.h"
17#include "SymbolTable.h"
18#include "WriterUtils.h"
19#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000020#include "lld/Common/Memory.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000021#include "lld/Common/Threads.h"
22#include "llvm/Support/FileOutputBuffer.h"
23#include "llvm/Support/Format.h"
24#include "llvm/Support/FormatVariadic.h"
25#include "llvm/Support/LEB128.h"
26
27#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000028#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000029
30#define DEBUG_TYPE "lld"
31
32using namespace llvm;
33using namespace llvm::wasm;
34using namespace lld;
35using namespace lld::wasm;
36
37static constexpr int kStackAlignment = 16;
Sam Clegg48bbd632018-01-24 21:37:30 +000038static constexpr int kInitialTableOffset = 1;
Sam Cleggc94d3932017-11-17 18:14:09 +000039
40namespace {
41
Sam Cleggc94d3932017-11-17 18:14:09 +000042// Traits for using WasmSignature in a DenseMap.
43struct WasmSignatureDenseMapInfo {
44 static WasmSignature getEmptyKey() {
45 WasmSignature Sig;
46 Sig.ReturnType = 1;
47 return Sig;
48 }
49 static WasmSignature getTombstoneKey() {
50 WasmSignature Sig;
51 Sig.ReturnType = 2;
52 return Sig;
53 }
54 static unsigned getHashValue(const WasmSignature &Sig) {
55 uintptr_t Value = 0;
56 Value += DenseMapInfo<int32_t>::getHashValue(Sig.ReturnType);
57 for (int32_t Param : Sig.ParamTypes)
58 Value += DenseMapInfo<int32_t>::getHashValue(Param);
59 return Value;
60 }
61 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
62 return LHS == RHS;
63 }
64};
65
Sam Cleggd3052d52018-01-18 23:40:49 +000066// A Wasm export to be written into the export section.
67struct WasmExportEntry {
Sam Clegg811236c2018-01-19 03:31:07 +000068 const Symbol *Sym;
Sam Cleggd3052d52018-01-18 23:40:49 +000069 StringRef FieldName; // may not match the Symbol name
70};
71
Sam Cleggc94d3932017-11-17 18:14:09 +000072// The writer writes a SymbolTable result to a file.
73class Writer {
74public:
75 void run();
76
77private:
78 void openFile();
79
Sam Cleggc375e4e2018-01-10 19:18:22 +000080 uint32_t lookupType(const WasmSignature &Sig);
81 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg50686852018-01-12 18:35:13 +000082 void createCtorFunction();
83 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000084 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000085 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000086 void calculateExports();
Sam Cleggc94d3932017-11-17 18:14:09 +000087 void calculateTypes();
88 void createOutputSegments();
89 void layoutMemory();
90 void createHeader();
91 void createSections();
92 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000093 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000094
95 // Builtin sections
96 void createTypeSection();
97 void createFunctionSection();
98 void createTableSection();
99 void createGlobalSection();
100 void createExportSection();
101 void createImportSection();
102 void createMemorySection();
103 void createElemSection();
104 void createStartSection();
105 void createCodeSection();
106 void createDataSection();
107
108 // Custom sections
109 void createRelocSections();
110 void createLinkingSection();
111 void createNameSection();
112
113 void writeHeader();
114 void writeSections();
115
116 uint64_t FileSize = 0;
117 uint32_t DataSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000118 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000119
120 std::vector<const WasmSignature *> Types;
121 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000122 std::vector<const FunctionSymbol *> ImportedFunctions;
123 std::vector<const GlobalSymbol *> ImportedGlobals;
Sam Cleggd3052d52018-01-18 23:40:49 +0000124 std::vector<WasmExportEntry> ExportedSymbols;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000125 std::vector<const DefinedGlobal *> DefinedGlobals;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000126 std::vector<InputFunction *> DefinedFunctions;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000127 std::vector<const FunctionSymbol *> IndirectFunctions;
Sam Clegg50686852018-01-12 18:35:13 +0000128 std::vector<WasmInitFunc> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000129
130 // Elements that are used to construct the final output
131 std::string Header;
132 std::vector<OutputSection *> OutputSections;
133
134 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000135 std::unique_ptr<SyntheticFunction> CtorFunction;
136 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000137
138 std::vector<OutputSegment *> Segments;
139 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
140};
141
142} // anonymous namespace
143
144static void debugPrint(const char *fmt, ...) {
145 if (!errorHandler().Verbose)
146 return;
147 fprintf(stderr, "lld: ");
148 va_list ap;
149 va_start(ap, fmt);
150 vfprintf(stderr, fmt, ap);
151 va_end(ap);
152}
153
154void Writer::createImportSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000155 uint32_t NumImports = ImportedFunctions.size() + ImportedGlobals.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000156 if (Config->ImportMemory)
157 ++NumImports;
158
159 if (NumImports == 0)
160 return;
161
162 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
163 raw_ostream &OS = Section->getStream();
164
165 writeUleb128(OS, NumImports, "import count");
166
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000167 for (const FunctionSymbol *Sym : ImportedFunctions) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000168 WasmImport Import;
169 Import.Module = "env";
170 Import.Field = Sym->getName();
171 Import.Kind = WASM_EXTERNAL_FUNCTION;
Sam Clegg3f8db982018-02-16 23:50:23 +0000172 Import.SigIndex = lookupType(*Sym->getFunctionType());
Sam Cleggc94d3932017-11-17 18:14:09 +0000173 writeImport(OS, Import);
174 }
175
176 if (Config->ImportMemory) {
177 WasmImport Import;
178 Import.Module = "env";
179 Import.Field = "memory";
180 Import.Kind = WASM_EXTERNAL_MEMORY;
181 Import.Memory.Flags = 0;
182 Import.Memory.Initial = NumMemoryPages;
183 writeImport(OS, Import);
184 }
185
Sam Clegg8d146bb2018-01-09 23:56:44 +0000186 for (const Symbol *Sym : ImportedGlobals) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000187 WasmImport Import;
188 Import.Module = "env";
189 Import.Field = Sym->getName();
190 Import.Kind = WASM_EXTERNAL_GLOBAL;
191 Import.Global.Mutable = false;
Sam Cleggd451da12017-12-19 19:56:27 +0000192 Import.Global.Type = WASM_TYPE_I32;
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 Clegg8d146bb2018-01-09 23:56:44 +0000206 if (DefinedFunctions.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 Clegg8d146bb2018-01-09 23:56:44 +0000212 writeUleb128(OS, DefinedFunctions.size(), "function count");
213 for (const InputFunction *Func : DefinedFunctions)
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 Clegg74fe0ba2017-12-07 01:51:24 +0000230 if (DefinedGlobals.empty())
231 return;
232
Sam Cleggc94d3932017-11-17 18:14:09 +0000233 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
234 raw_ostream &OS = Section->getStream();
235
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000236 writeUleb128(OS, DefinedGlobals.size(), "global count");
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000237 for (const DefinedGlobal *Sym : DefinedGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000238 WasmGlobal Global;
Sam Clegg1a9b7b92018-01-31 19:54:34 +0000239 Global.Type.Type = WASM_TYPE_I32;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000240 Global.Type.Mutable = Sym == WasmSym::StackPointer;
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");
262 writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type");
263 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
280 if (ExportMemory) {
281 WasmExport MemoryExport;
282 MemoryExport.Name = "memory";
283 MemoryExport.Kind = WASM_EXTERNAL_MEMORY;
284 MemoryExport.Index = 0;
285 writeExport(OS, MemoryExport);
286 }
287
Sam Cleggd3052d52018-01-18 23:40:49 +0000288 for (const WasmExportEntry &E : ExportedSymbols) {
Sam Clegg811236c2018-01-19 03:31:07 +0000289 DEBUG(dbgs() << "Export: " << E.Sym->getName() << "\n");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000290 WasmExport Export;
Sam Cleggd3052d52018-01-18 23:40:49 +0000291 Export.Name = E.FieldName;
Sam Clegg811236c2018-01-19 03:31:07 +0000292 Export.Index = E.Sym->getOutputIndex();
Sam Cleggcaca8d52018-02-17 00:44:21 +0000293 if (isa<FunctionSymbol>(E.Sym))
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000294 Export.Kind = WASM_EXTERNAL_FUNCTION;
295 else
296 Export.Kind = WASM_EXTERNAL_GLOBAL;
297 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000298 }
299}
300
301void Writer::createStartSection() {}
302
303void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000304 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000305 return;
306
307 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
308 raw_ostream &OS = Section->getStream();
309
310 writeUleb128(OS, 1, "segment count");
311 writeUleb128(OS, 0, "table index");
312 WasmInitExpr InitExpr;
313 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000314 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000315 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000316 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000317
Sam Clegg48bbd632018-01-24 21:37:30 +0000318 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000319 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000320 assert(Sym->getTableIndex() == TableIndex);
321 writeUleb128(OS, Sym->getOutputIndex(), "function index");
322 ++TableIndex;
323 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000324}
325
326void Writer::createCodeSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000327 if (DefinedFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000328 return;
329
330 log("createCodeSection");
331
Sam Clegg8d146bb2018-01-09 23:56:44 +0000332 auto Section = make<CodeSection>(DefinedFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000333 OutputSections.push_back(Section);
334}
335
336void Writer::createDataSection() {
337 if (!Segments.size())
338 return;
339
340 log("createDataSection");
341 auto Section = make<DataSection>(Segments);
342 OutputSections.push_back(Section);
343}
344
Sam Cleggd451da12017-12-19 19:56:27 +0000345// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000346// These are only created when relocatable output is requested.
347void Writer::createRelocSections() {
348 log("createRelocSections");
349 // Don't use iterator here since we are adding to OutputSection
350 size_t OrigSize = OutputSections.size();
351 for (size_t i = 0; i < OrigSize; i++) {
352 OutputSection *S = OutputSections[i];
353 const char *name;
354 uint32_t Count = S->numRelocations();
355 if (!Count)
356 continue;
357
358 if (S->Type == WASM_SEC_DATA)
359 name = "reloc.DATA";
360 else if (S->Type == WASM_SEC_CODE)
361 name = "reloc.CODE";
362 else
Sam Cleggd451da12017-12-19 19:56:27 +0000363 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000364
365 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, name);
366 raw_ostream &OS = Section->getStream();
367 writeUleb128(OS, S->Type, "reloc section");
368 writeUleb128(OS, Count, "reloc count");
369 S->writeRelocations(OS);
370 }
371}
372
Sam Clegg49ed9262017-12-01 00:53:21 +0000373// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000374// This is only created when relocatable output is requested.
375void Writer::createLinkingSection() {
376 SyntheticSection *Section =
377 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
378 raw_ostream &OS = Section->getStream();
379
380 SubSection DataSizeSubSection(WASM_DATA_SIZE);
381 writeUleb128(DataSizeSubSection.getStream(), DataSize, "data size");
382 DataSizeSubSection.finalizeContents();
383 DataSizeSubSection.writeToStream(OS);
384
Sam Clegg0d0dd392017-12-19 17:09:45 +0000385 if (!Config->Relocatable)
386 return;
387
Sam Cleggd3052d52018-01-18 23:40:49 +0000388 std::vector<std::pair<StringRef, uint32_t>> SymbolInfo;
Sam Clegg04b76f42018-01-19 21:49:41 +0000389 auto addSymInfo = [&](const Symbol *Sym, StringRef ExternalName) {
Sam Cleggd3052d52018-01-18 23:40:49 +0000390 uint32_t Flags =
Sam Clegg04b76f42018-01-19 21:49:41 +0000391 (Sym->isLocal() ? WASM_SYMBOL_BINDING_LOCAL :
392 Sym->isWeak() ? WASM_SYMBOL_BINDING_WEAK : 0) |
393 (Sym->isHidden() ? WASM_SYMBOL_VISIBILITY_HIDDEN : 0);
Sam Cleggd3052d52018-01-18 23:40:49 +0000394 if (Flags)
Sam Clegg04b76f42018-01-19 21:49:41 +0000395 SymbolInfo.emplace_back(ExternalName, Flags);
396 };
397 // (Imports can't have internal linkage, their names don't need to be budged.)
398 for (const Symbol *Sym : ImportedFunctions)
399 addSymInfo(Sym, Sym->getName());
400 for (const Symbol *Sym : ImportedGlobals)
401 addSymInfo(Sym, Sym->getName());
402 for (const WasmExportEntry &E : ExportedSymbols)
403 addSymInfo(E.Sym, E.FieldName);
Sam Cleggd3052d52018-01-18 23:40:49 +0000404 if (!SymbolInfo.empty()) {
405 SubSection SubSection(WASM_SYMBOL_INFO);
406 writeUleb128(SubSection.getStream(), SymbolInfo.size(), "num sym info");
407 for (auto Pair: SymbolInfo) {
408 writeStr(SubSection.getStream(), Pair.first, "sym name");
409 writeUleb128(SubSection.getStream(), Pair.second, "sym flags");
410 }
411 SubSection.finalizeContents();
412 SubSection.writeToStream(OS);
413 }
414
Sam Clegg0d0dd392017-12-19 17:09:45 +0000415 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000416 SubSection SubSection(WASM_SEGMENT_INFO);
417 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
418 for (const OutputSegment *S : Segments) {
419 writeStr(SubSection.getStream(), S->Name, "segment name");
420 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
421 writeUleb128(SubSection.getStream(), 0, "flags");
422 }
423 SubSection.finalizeContents();
424 SubSection.writeToStream(OS);
425 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000426
Sam Clegg0d0dd392017-12-19 17:09:45 +0000427 if (!InitFunctions.empty()) {
428 SubSection SubSection(WASM_INIT_FUNCS);
429 writeUleb128(SubSection.getStream(), InitFunctions.size(),
Sam Clegg54c38912018-01-17 18:50:30 +0000430 "num init functions");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000431 for (const WasmInitFunc &F : InitFunctions) {
432 writeUleb128(SubSection.getStream(), F.Priority, "priority");
433 writeUleb128(SubSection.getStream(), F.FunctionIndex, "function index");
434 }
435 SubSection.finalizeContents();
436 SubSection.writeToStream(OS);
437 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000438
439 struct ComdatEntry { unsigned Kind; uint32_t Index; };
440 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
441
442 for (const InputFunction *F : DefinedFunctions) {
443 StringRef Comdat = F->getComdat();
444 if (!Comdat.empty())
445 Comdats[Comdat].emplace_back(
446 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
447 }
448 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000449 const auto &InputSegments = Segments[I]->InputSegments;
450 if (InputSegments.empty())
451 continue;
452 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000453#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000454 for (const InputSegment *IS : InputSegments)
455 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000456#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000457 if (!Comdat.empty())
458 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
459 }
460
461 if (!Comdats.empty()) {
462 SubSection SubSection(WASM_COMDAT_INFO);
463 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
464 for (const auto &C : Comdats) {
465 writeStr(SubSection.getStream(), C.first, "comdat name");
466 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
467 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
468 for (const ComdatEntry &Entry : C.second) {
469 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
470 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
471 }
472 }
473 SubSection.finalizeContents();
474 SubSection.writeToStream(OS);
475 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000476}
477
478// Create the custom "name" section containing debug symbol names.
479void Writer::createNameSection() {
Sam Clegg1963d712018-01-17 20:19:04 +0000480 unsigned NumNames = ImportedFunctions.size();
481 for (const InputFunction *F : DefinedFunctions)
482 if (!F->getName().empty())
483 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000484
Sam Clegg1963d712018-01-17 20:19:04 +0000485 if (NumNames == 0)
486 return;
Sam Clegg50686852018-01-12 18:35:13 +0000487
Sam Cleggc94d3932017-11-17 18:14:09 +0000488 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
489
Sam Cleggc94d3932017-11-17 18:14:09 +0000490 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
491 raw_ostream &OS = FunctionSubsection.getStream();
Sam Clegg1963d712018-01-17 20:19:04 +0000492 writeUleb128(OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000493
Sam Clegg1963d712018-01-17 20:19:04 +0000494 // Names must appear in function index order. As it happens ImportedFunctions
495 // and DefinedFunctions are numbers in order with imported functions coming
496 // first.
497 for (const Symbol *S : ImportedFunctions) {
498 writeUleb128(OS, S->getOutputIndex(), "import index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000499 writeStr(OS, S->getName(), "symbol name");
500 }
Sam Clegg1963d712018-01-17 20:19:04 +0000501 for (const InputFunction *F : DefinedFunctions) {
502 if (!F->getName().empty()) {
503 writeUleb128(OS, F->getOutputIndex(), "func index");
504 writeStr(OS, F->getName(), "symbol name");
505 }
506 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000507
508 FunctionSubsection.finalizeContents();
509 FunctionSubsection.writeToStream(Section->getStream());
510}
511
512void Writer::writeHeader() {
513 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
514}
515
516void Writer::writeSections() {
517 uint8_t *Buf = Buffer->getBufferStart();
518 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
519}
520
521// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000522// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000523// The memory layout is as follows, from low to high.
524// - initialized data (starting at Config->GlobalBase)
525// - BSS data (not currently implemented in llvm)
526// - explicit stack (Config->ZStackSize)
527// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000528void Writer::layoutMemory() {
529 uint32_t MemoryPtr = 0;
530 if (!Config->Relocatable) {
531 MemoryPtr = Config->GlobalBase;
532 debugPrint("mem: global base = %d\n", Config->GlobalBase);
533 }
534
535 createOutputSegments();
536
Sam Cleggf0d433d2018-02-02 22:59:56 +0000537 // Arbitrarily set __dso_handle handle to point to the start of the data
538 // segments.
539 if (WasmSym::DsoHandle)
540 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
541
Sam Cleggc94d3932017-11-17 18:14:09 +0000542 for (OutputSegment *Seg : Segments) {
543 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
544 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000545 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000546 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
547 MemoryPtr += Seg->Size;
548 }
549
Sam Cleggf0d433d2018-02-02 22:59:56 +0000550 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000551 if (WasmSym::DataEnd)
552 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000553
Sam Cleggc94d3932017-11-17 18:14:09 +0000554 DataSize = MemoryPtr;
555 if (!Config->Relocatable)
556 DataSize -= Config->GlobalBase;
557 debugPrint("mem: static data = %d\n", DataSize);
558
Sam Cleggf0d433d2018-02-02 22:59:56 +0000559 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000560 if (!Config->Relocatable) {
561 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
562 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
563 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
564 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
565 debugPrint("mem: stack base = %d\n", MemoryPtr);
566 MemoryPtr += Config->ZStackSize;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000567 WasmSym::StackPointer->setVirtualAddress(MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000568 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000569 // Set `__heap_base` to directly follow the end of the stack. We don't
570 // allocate any heap memory up front, but instead really on the malloc/brk
571 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000572 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000573 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000574 }
575
576 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
577 NumMemoryPages = MemSize / WasmPageSize;
578 debugPrint("mem: total pages = %d\n", NumMemoryPages);
579}
580
581SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000582 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000583 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000584 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000585 OutputSections.push_back(Sec);
586 return Sec;
587}
588
589void Writer::createSections() {
590 // Known sections
591 createTypeSection();
592 createImportSection();
593 createFunctionSection();
594 createTableSection();
595 createMemorySection();
596 createGlobalSection();
597 createExportSection();
598 createStartSection();
599 createElemSection();
600 createCodeSection();
601 createDataSection();
602
603 // Custom sections
Sam Cleggff2b1222018-01-22 21:55:43 +0000604 if (Config->Relocatable)
Sam Cleggc94d3932017-11-17 18:14:09 +0000605 createRelocSections();
606 createLinkingSection();
607 if (!Config->StripDebug && !Config->StripAll)
608 createNameSection();
609
610 for (OutputSection *S : OutputSections) {
611 S->setOffset(FileSize);
612 S->finalizeContents();
613 FileSize += S->getSize();
614 }
615}
616
Sam Cleggc94d3932017-11-17 18:14:09 +0000617void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000618 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggff2b1222018-01-22 21:55:43 +0000619 if (!Sym->isUndefined() || (Sym->isWeak() && !Config->Relocatable))
Sam Clegg574d7ce2017-12-15 19:23:49 +0000620 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000621
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000622 if (auto *F = dyn_cast<FunctionSymbol>(Sym)) {
623 F->setOutputIndex(ImportedFunctions.size());
624 ImportedFunctions.push_back(F);
625 } else if (auto *G = dyn_cast<GlobalSymbol>(Sym)) {
626 G->setOutputIndex(ImportedGlobals.size());
627 ImportedGlobals.push_back(G);
Sam Cleggc94d3932017-11-17 18:14:09 +0000628 }
629 }
630}
631
Sam Cleggd3052d52018-01-18 23:40:49 +0000632void Writer::calculateExports() {
Sam Cleggff2b1222018-01-22 21:55:43 +0000633 bool ExportHidden = Config->Relocatable;
Sam Cleggd3052d52018-01-18 23:40:49 +0000634 StringSet<> UsedNames;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000635
Sam Cleggd3052d52018-01-18 23:40:49 +0000636 auto BudgeLocalName = [&](const Symbol *Sym) {
637 StringRef SymName = Sym->getName();
638 // We can't budge non-local names.
639 if (!Sym->isLocal())
640 return SymName;
641 // We must budge local names that have a collision with a symbol that we
642 // haven't yet processed.
643 if (!Symtab->find(SymName) && UsedNames.insert(SymName).second)
644 return SymName;
645 for (unsigned I = 1; ; ++I) {
646 std::string NameBuf = (SymName + "." + Twine(I)).str();
647 if (!UsedNames.count(NameBuf)) {
648 StringRef Name = Saver.save(NameBuf);
649 UsedNames.insert(Name); // Insert must use safe StringRef from save()
650 return Name;
651 }
652 }
653 };
654
Sam Cleggf0d433d2018-02-02 22:59:56 +0000655 if (WasmSym::CallCtors && (!WasmSym::CallCtors->isHidden() || ExportHidden))
Sam Cleggd3052d52018-01-18 23:40:49 +0000656 ExportedSymbols.emplace_back(
Sam Cleggf0d433d2018-02-02 22:59:56 +0000657 WasmExportEntry{WasmSym::CallCtors, WasmSym::CallCtors->getName()});
Sam Cleggd3052d52018-01-18 23:40:49 +0000658
659 for (ObjFile *File : Symtab->ObjectFiles) {
660 for (Symbol *Sym : File->getSymbols()) {
661 if (!Sym->isDefined() || File != Sym->getFile())
662 continue;
Sam Cleggcaca8d52018-02-17 00:44:21 +0000663 if (isa<GlobalSymbol>(Sym))
Sam Cleggd3052d52018-01-18 23:40:49 +0000664 continue;
Sam Clegg447ae402018-02-13 20:29:38 +0000665 if (!Sym->getChunk()->Live)
Sam Cleggd3052d52018-01-18 23:40:49 +0000666 continue;
667
668 if ((Sym->isHidden() || Sym->isLocal()) && !ExportHidden)
669 continue;
Sam Cleggd3052d52018-01-18 23:40:49 +0000670 ExportedSymbols.emplace_back(WasmExportEntry{Sym, BudgeLocalName(Sym)});
671 }
672 }
673
674 for (const Symbol *Sym : DefinedGlobals) {
Sam Clegg14ae6e72018-01-18 23:57:55 +0000675 // Can't export the SP right now because its mutable, and mutuable globals
Sam Cleggff2b1222018-01-22 21:55:43 +0000676 // are yet supported in the official binary format.
Sam Clegg14ae6e72018-01-18 23:57:55 +0000677 // TODO(sbc): Remove this if/when the "mutable global" proposal is accepted.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000678 if (Sym == WasmSym::StackPointer)
Sam Cleggd3052d52018-01-18 23:40:49 +0000679 continue;
680 ExportedSymbols.emplace_back(WasmExportEntry{Sym, BudgeLocalName(Sym)});
681 }
682}
683
Sam Cleggc375e4e2018-01-10 19:18:22 +0000684uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000685 auto It = TypeIndices.find(Sig);
686 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000687 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000688 return 0;
689 }
690 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000691}
692
693uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000694 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000695 if (Pair.second) {
696 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000697 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000698 }
Sam Cleggb8621592017-11-30 01:40:08 +0000699 return Pair.first->second;
700}
701
Sam Cleggc94d3932017-11-17 18:14:09 +0000702void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000703 // The output type section is the union of the following sets:
704 // 1. Any signature used in the TYPE relocation
705 // 2. The signatures of all imported functions
706 // 3. The signatures of all defined functions
707
Sam Cleggc94d3932017-11-17 18:14:09 +0000708 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000709 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
710 for (uint32_t I = 0; I < Types.size(); I++)
711 if (File->TypeIsUsed[I])
712 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000713 }
Sam Clegg50686852018-01-12 18:35:13 +0000714
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000715 for (const FunctionSymbol *Sym : ImportedFunctions)
Sam Clegg3f8db982018-02-16 23:50:23 +0000716 registerType(*Sym->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000717
718 for (const InputFunction *F : DefinedFunctions)
719 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000720}
721
Sam Clegg8d146bb2018-01-09 23:56:44 +0000722void Writer::assignIndexes() {
Sam Clegg50686852018-01-12 18:35:13 +0000723 uint32_t GlobalIndex = ImportedGlobals.size() + DefinedGlobals.size();
724 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000725
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000726 auto AddDefinedGlobal = [&](DefinedGlobal *Sym) {
Sam Cleggf0d433d2018-02-02 22:59:56 +0000727 if (Sym) {
728 DefinedGlobals.emplace_back(Sym);
729 Sym->setOutputIndex(GlobalIndex++);
730 }
731 };
732 AddDefinedGlobal(WasmSym::StackPointer);
733 AddDefinedGlobal(WasmSym::HeapBase);
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000734 AddDefinedGlobal(WasmSym::DataEnd);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000735
Sam Cleggff2b1222018-01-22 21:55:43 +0000736 if (Config->Relocatable)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000737 DefinedGlobals.reserve(Symtab->getSymbols().size());
738
Sam Clegg48bbd632018-01-24 21:37:30 +0000739 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggfc1a9122017-12-11 22:00:56 +0000740
Sam Cleggf0d433d2018-02-02 22:59:56 +0000741 if (Config->Relocatable) {
742 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000743 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
744 for (Symbol *Sym : File->getSymbols()) {
745 // Create wasm globals for data symbols defined in this file
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000746 if (File != Sym->getFile())
Sam Clegg8d146bb2018-01-09 23:56:44 +0000747 continue;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000748 if (auto *G = dyn_cast<DefinedGlobal>(Sym))
749 AddDefinedGlobal(G);
Sam Cleggc94d3932017-11-17 18:14:09 +0000750 }
751 }
Sam Clegg87e61922018-01-08 23:39:11 +0000752 }
Sam Cleggfc1a9122017-12-11 22:00:56 +0000753
Sam Clegg87e61922018-01-08 23:39:11 +0000754 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000755 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
756 for (InputFunction *Func : File->Functions) {
Sam Clegg447ae402018-02-13 20:29:38 +0000757 if (!Func->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000758 continue;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000759 DefinedFunctions.emplace_back(Func);
760 Func->setOutputIndex(FunctionIndex++);
761 }
762 }
763
764 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000765 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
766 auto HandleRelocs = [&](InputChunk *Chunk) {
Sam Clegg447ae402018-02-13 20:29:38 +0000767 if (!Chunk->Live)
Sam Cleggab604a92018-01-23 01:25:56 +0000768 return;
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000769 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Cleggab604a92018-01-23 01:25:56 +0000770 for (const WasmRelocation& Reloc : Chunk->getRelocations()) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000771 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
772 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000773 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000774 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
775 continue;
776 Sym->setTableIndex(TableIndex++);
777 IndirectFunctions.emplace_back(Sym);
778 } else if (Reloc.Type == R_WEBASSEMBLY_TYPE_INDEX_LEB) {
779 Chunk->File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
780 Chunk->File->TypeIsUsed[Reloc.Index] = true;
781 }
Sam Cleggab604a92018-01-23 01:25:56 +0000782 }
783 };
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000784
Sam Cleggab604a92018-01-23 01:25:56 +0000785 for (InputFunction* Function : File->Functions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000786 HandleRelocs(Function);
Sam Cleggab604a92018-01-23 01:25:56 +0000787 for (InputSegment* Segment : File->Segments)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000788 HandleRelocs(Segment);
Sam Cleggc94d3932017-11-17 18:14:09 +0000789 }
790}
791
792static StringRef getOutputDataSegmentName(StringRef Name) {
793 if (Config->Relocatable)
794 return Name;
795
796 for (StringRef V :
797 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
798 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
799 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
800 StringRef Prefix = V.drop_back();
801 if (Name.startswith(V) || Name == Prefix)
802 return Prefix;
803 }
804
805 return Name;
806}
807
808void Writer::createOutputSegments() {
809 for (ObjFile *File : Symtab->ObjectFiles) {
810 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000811 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000812 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000813 StringRef Name = getOutputDataSegmentName(Segment->getName());
814 OutputSegment *&S = SegmentMap[Name];
815 if (S == nullptr) {
816 DEBUG(dbgs() << "new segment: " << Name << "\n");
817 S = make<OutputSegment>(Name);
818 Segments.push_back(S);
819 }
820 S->addInputSegment(Segment);
821 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000822 }
823 }
824}
825
Sam Clegg50686852018-01-12 18:35:13 +0000826static const int OPCODE_CALL = 0x10;
827static const int OPCODE_END = 0xb;
828
829// Create synthetic "__wasm_call_ctors" function based on ctor functions
830// in input object.
831void Writer::createCtorFunction() {
832 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000833 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000834
835 // First write the body bytes to a string.
836 std::string FunctionBody;
837 static WasmSignature Signature = {{}, WASM_TYPE_NORESULT};
838 {
839 raw_string_ostream OS(FunctionBody);
840 writeUleb128(OS, 0, "num locals");
841 for (const WasmInitFunc &F : InitFunctions) {
842 writeU8(OS, OPCODE_CALL, "CALL");
843 writeUleb128(OS, F.FunctionIndex, "function index");
844 }
845 writeU8(OS, OPCODE_END, "END");
846 }
847
848 // Once we know the size of the body we can create the final function body
849 raw_string_ostream OS(CtorFunctionBody);
850 writeUleb128(OS, FunctionBody.size(), "function size");
851 OS.flush();
852 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000853 ArrayRef<uint8_t> BodyArray(
854 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
855 CtorFunctionBody.size());
Sam Clegg1963d712018-01-17 20:19:04 +0000856 CtorFunction = llvm::make_unique<SyntheticFunction>(
Sam Cleggf0d433d2018-02-02 22:59:56 +0000857 Signature, BodyArray, WasmSym::CallCtors->getName());
Sam Clegg1963d712018-01-17 20:19:04 +0000858 CtorFunction->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000859 DefinedFunctions.emplace_back(CtorFunction.get());
860}
861
862// Populate InitFunctions vector with init functions from all input objects.
863// This is then used either when creating the output linking section or to
864// synthesize the "__wasm_call_ctors" function.
865void Writer::calculateInitFunctions() {
866 for (ObjFile *File : Symtab->ObjectFiles) {
867 const WasmLinkingData &L = File->getWasmObj()->linkingData();
868 InitFunctions.reserve(InitFunctions.size() + L.InitFunctions.size());
869 for (const WasmInitFunc &F : L.InitFunctions)
870 InitFunctions.emplace_back(WasmInitFunc{
871 F.Priority, File->relocateFunctionIndex(F.FunctionIndex)});
872 }
873 // Sort in order of priority (lowest first) so that they are called
874 // in the correct order.
875 std::sort(InitFunctions.begin(), InitFunctions.end(),
876 [](const WasmInitFunc &L, const WasmInitFunc &R) {
877 return L.Priority < R.Priority;
878 });
879}
880
Sam Cleggc94d3932017-11-17 18:14:09 +0000881void Writer::run() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000882 log("-- calculateImports");
883 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000884 log("-- assignIndexes");
885 assignIndexes();
Sam Cleggd3052d52018-01-18 23:40:49 +0000886 log("-- calculateExports");
887 calculateExports();
Sam Clegg50686852018-01-12 18:35:13 +0000888 log("-- calculateInitFunctions");
889 calculateInitFunctions();
890 if (!Config->Relocatable)
891 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000892 log("-- calculateTypes");
893 calculateTypes();
Sam Cleggc94d3932017-11-17 18:14:09 +0000894
895 if (errorHandler().Verbose) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000896 log("Defined Functions: " + Twine(DefinedFunctions.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000897 log("Defined Globals : " + Twine(DefinedGlobals.size()));
Sam Clegg8d146bb2018-01-09 23:56:44 +0000898 log("Function Imports : " + Twine(ImportedFunctions.size()));
899 log("Global Imports : " + Twine(ImportedGlobals.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000900 log("Total Imports : " +
Sam Clegg8d146bb2018-01-09 23:56:44 +0000901 Twine(ImportedFunctions.size() + ImportedGlobals.size()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000902 for (ObjFile *File : Symtab->ObjectFiles)
903 File->dumpInfo();
904 }
905
Sam Cleggc94d3932017-11-17 18:14:09 +0000906 log("-- layoutMemory");
907 layoutMemory();
908
909 createHeader();
910 log("-- createSections");
911 createSections();
912
913 log("-- openFile");
914 openFile();
915 if (errorCount())
916 return;
917
918 writeHeader();
919
920 log("-- writeSections");
921 writeSections();
922 if (errorCount())
923 return;
924
925 if (Error E = Buffer->commit())
926 fatal("failed to write the output file: " + toString(std::move(E)));
927}
928
929// Open a result file.
930void Writer::openFile() {
931 log("writing: " + Config->OutputFile);
932 ::remove(Config->OutputFile.str().c_str());
933
934 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
935 FileOutputBuffer::create(Config->OutputFile, FileSize,
936 FileOutputBuffer::F_executable);
937
938 if (!BufferOrErr)
939 error("failed to open " + Config->OutputFile + ": " +
940 toString(BufferOrErr.takeError()));
941 else
942 Buffer = std::move(*BufferOrErr);
943}
944
945void Writer::createHeader() {
946 raw_string_ostream OS(Header);
947 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
948 writeU32(OS, WasmVersion, "wasm version");
949 OS.flush();
950 FileSize += Header.size();
951}
952
953void lld::wasm::writeResult() { Writer().run(); }