blob: 2f3c455851fd435f536975b895c130bcde46ed1a [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
282 if (ExportMemory) {
283 WasmExport MemoryExport;
284 MemoryExport.Name = "memory";
285 MemoryExport.Kind = WASM_EXTERNAL_MEMORY;
286 MemoryExport.Index = 0;
287 writeExport(OS, MemoryExport);
288 }
289
Sam Clegg93102972018-02-23 05:08:53 +0000290 unsigned FakeGlobalIndex = NumImportedGlobals + InputGlobals.size();
291 for (const Symbol *Sym : ExportedSymbols) {
292 DEBUG(dbgs() << "Export: " << Sym->getName() << "\n");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000293 WasmExport Export;
Sam Clegg93102972018-02-23 05:08:53 +0000294 Export.Name = Sym->getName();
295 if (isa<FunctionSymbol>(Sym)) {
296 Export.Index = Sym->getOutputIndex();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000297 Export.Kind = WASM_EXTERNAL_FUNCTION;
Sam Clegg93102972018-02-23 05:08:53 +0000298 } else if (isa<GlobalSymbol>(Sym)) {
299 Export.Index = Sym->getOutputIndex();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000300 Export.Kind = WASM_EXTERNAL_GLOBAL;
Sam Clegg93102972018-02-23 05:08:53 +0000301 } else if (isa<DataSymbol>(Sym)) {
302 Export.Index = FakeGlobalIndex++;
303 Export.Kind = WASM_EXTERNAL_GLOBAL;
304 } else {
305 llvm_unreachable("unexpected symbol type");
306 }
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000307 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000308 }
309}
310
Sam Cleggc94d3932017-11-17 18:14:09 +0000311void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000312 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000313 return;
314
315 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
316 raw_ostream &OS = Section->getStream();
317
318 writeUleb128(OS, 1, "segment count");
319 writeUleb128(OS, 0, "table index");
320 WasmInitExpr InitExpr;
321 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
Sam Clegg48bbd632018-01-24 21:37:30 +0000322 InitExpr.Value.Int32 = kInitialTableOffset;
Sam Cleggc94d3932017-11-17 18:14:09 +0000323 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000324 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000325
Sam Clegg48bbd632018-01-24 21:37:30 +0000326 uint32_t TableIndex = kInitialTableOffset;
Sam Cleggdfb0b2c2018-02-14 18:27:59 +0000327 for (const FunctionSymbol *Sym : IndirectFunctions) {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000328 assert(Sym->getTableIndex() == TableIndex);
329 writeUleb128(OS, Sym->getOutputIndex(), "function index");
330 ++TableIndex;
331 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000332}
333
334void Writer::createCodeSection() {
Sam Clegg9f934222018-02-21 18:29:23 +0000335 if (InputFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000336 return;
337
338 log("createCodeSection");
339
Sam Clegg9f934222018-02-21 18:29:23 +0000340 auto Section = make<CodeSection>(InputFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000341 OutputSections.push_back(Section);
342}
343
344void Writer::createDataSection() {
345 if (!Segments.size())
346 return;
347
348 log("createDataSection");
349 auto Section = make<DataSection>(Segments);
350 OutputSections.push_back(Section);
351}
352
Sam Cleggd451da12017-12-19 19:56:27 +0000353// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000354// These are only created when relocatable output is requested.
355void Writer::createRelocSections() {
356 log("createRelocSections");
357 // Don't use iterator here since we are adding to OutputSection
358 size_t OrigSize = OutputSections.size();
359 for (size_t i = 0; i < OrigSize; i++) {
Rui Ueyama37254062018-02-28 00:01:31 +0000360 OutputSection *OSec = OutputSections[i];
361 uint32_t Count = OSec->numRelocations();
Sam Cleggc94d3932017-11-17 18:14:09 +0000362 if (!Count)
363 continue;
364
Rui Ueyama37254062018-02-28 00:01:31 +0000365 StringRef Name;
366 if (OSec->Type == WASM_SEC_DATA)
367 Name = "reloc.DATA";
368 else if (OSec->Type == WASM_SEC_CODE)
369 Name = "reloc.CODE";
Sam Cleggc94d3932017-11-17 18:14:09 +0000370 else
Sam Cleggd451da12017-12-19 19:56:27 +0000371 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000372
Rui Ueyama37254062018-02-28 00:01:31 +0000373 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, Name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000374 raw_ostream &OS = Section->getStream();
Rui Ueyama37254062018-02-28 00:01:31 +0000375 writeUleb128(OS, OSec->Type, "reloc section");
Sam Cleggc94d3932017-11-17 18:14:09 +0000376 writeUleb128(OS, Count, "reloc count");
Rui Ueyama37254062018-02-28 00:01:31 +0000377 OSec->writeRelocations(OS);
Sam Cleggc94d3932017-11-17 18:14:09 +0000378 }
379}
380
Sam Clegg49ed9262017-12-01 00:53:21 +0000381// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000382// This is only created when relocatable output is requested.
383void Writer::createLinkingSection() {
384 SyntheticSection *Section =
385 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
386 raw_ostream &OS = Section->getStream();
387
Sam Clegg0d0dd392017-12-19 17:09:45 +0000388 if (!Config->Relocatable)
389 return;
390
Sam Clegg93102972018-02-23 05:08:53 +0000391 if (!SymtabEntries.empty()) {
392 SubSection SubSection(WASM_SYMBOL_TABLE);
393 writeUleb128(SubSection.getStream(), SymtabEntries.size(), "num symbols");
394 for (const Symbol *Sym : SymtabEntries) {
395 assert(Sym->isDefined() || Sym->isUndefined());
396 WasmSymbolType Kind = Sym->getWasmType();
397 uint32_t Flags = Sym->isLocal() ? WASM_SYMBOL_BINDING_LOCAL : 0;
398 if (Sym->isWeak())
399 Flags |= WASM_SYMBOL_BINDING_WEAK;
400 if (Sym->isHidden())
401 Flags |= WASM_SYMBOL_VISIBILITY_HIDDEN;
402 if (Sym->isUndefined())
403 Flags |= WASM_SYMBOL_UNDEFINED;
404 writeUleb128(SubSection.getStream(), Kind, "sym kind");
405 writeUleb128(SubSection.getStream(), Flags, "sym flags");
406 switch (Kind) {
407 case llvm::wasm::WASM_SYMBOL_TYPE_FUNCTION:
408 case llvm::wasm::WASM_SYMBOL_TYPE_GLOBAL:
409 writeUleb128(SubSection.getStream(), Sym->getOutputIndex(), "index");
410 if (Sym->isDefined())
411 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
412 break;
413 case llvm::wasm::WASM_SYMBOL_TYPE_DATA:
414 writeStr(SubSection.getStream(), Sym->getName(), "sym name");
415 if (auto *DataSym = dyn_cast<DefinedData>(Sym)) {
416 writeUleb128(SubSection.getStream(), DataSym->getOutputSegmentIndex(),
417 "index");
418 writeUleb128(SubSection.getStream(),
419 DataSym->getOutputSegmentOffset(), "data offset");
420 writeUleb128(SubSection.getStream(), DataSym->getSize(), "data size");
421 }
422 break;
423 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000424 }
425 SubSection.finalizeContents();
426 SubSection.writeToStream(OS);
427 }
428
Sam Clegg0d0dd392017-12-19 17:09:45 +0000429 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000430 SubSection SubSection(WASM_SEGMENT_INFO);
431 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
432 for (const OutputSegment *S : Segments) {
433 writeStr(SubSection.getStream(), S->Name, "segment name");
434 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
435 writeUleb128(SubSection.getStream(), 0, "flags");
436 }
437 SubSection.finalizeContents();
438 SubSection.writeToStream(OS);
439 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000440
Sam Clegg0d0dd392017-12-19 17:09:45 +0000441 if (!InitFunctions.empty()) {
442 SubSection SubSection(WASM_INIT_FUNCS);
443 writeUleb128(SubSection.getStream(), InitFunctions.size(),
Sam Clegg54c38912018-01-17 18:50:30 +0000444 "num init functions");
Sam Clegg93102972018-02-23 05:08:53 +0000445 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg0d0dd392017-12-19 17:09:45 +0000446 writeUleb128(SubSection.getStream(), F.Priority, "priority");
Sam Clegg93102972018-02-23 05:08:53 +0000447 writeUleb128(SubSection.getStream(), F.Sym->getOutputSymbolIndex(),
448 "function index");
Sam Clegg0d0dd392017-12-19 17:09:45 +0000449 }
450 SubSection.finalizeContents();
451 SubSection.writeToStream(OS);
452 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000453
454 struct ComdatEntry { unsigned Kind; uint32_t Index; };
455 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
456
Sam Clegg9f934222018-02-21 18:29:23 +0000457 for (const InputFunction *F : InputFunctions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000458 StringRef Comdat = F->getComdat();
459 if (!Comdat.empty())
460 Comdats[Comdat].emplace_back(
461 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
462 }
463 for (uint32_t I = 0; I < Segments.size(); ++I) {
Sam Cleggf98bccf2018-01-13 15:57:48 +0000464 const auto &InputSegments = Segments[I]->InputSegments;
465 if (InputSegments.empty())
466 continue;
467 StringRef Comdat = InputSegments[0]->getComdat();
Sam Clegga697df522018-01-13 15:59:53 +0000468#ifndef NDEBUG
Sam Cleggf98bccf2018-01-13 15:57:48 +0000469 for (const InputSegment *IS : InputSegments)
470 assert(IS->getComdat() == Comdat);
Sam Clegga697df522018-01-13 15:59:53 +0000471#endif
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000472 if (!Comdat.empty())
473 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
474 }
475
476 if (!Comdats.empty()) {
477 SubSection SubSection(WASM_COMDAT_INFO);
478 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
479 for (const auto &C : Comdats) {
480 writeStr(SubSection.getStream(), C.first, "comdat name");
481 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
482 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
483 for (const ComdatEntry &Entry : C.second) {
484 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
485 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
486 }
487 }
488 SubSection.finalizeContents();
489 SubSection.writeToStream(OS);
490 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000491}
492
493// Create the custom "name" section containing debug symbol names.
494void Writer::createNameSection() {
Sam Clegg93102972018-02-23 05:08:53 +0000495 unsigned NumNames = NumImportedFunctions;
Sam Clegg9f934222018-02-21 18:29:23 +0000496 for (const InputFunction *F : InputFunctions)
Sam Clegg1963d712018-01-17 20:19:04 +0000497 if (!F->getName().empty())
498 ++NumNames;
Sam Cleggc94d3932017-11-17 18:14:09 +0000499
Sam Clegg1963d712018-01-17 20:19:04 +0000500 if (NumNames == 0)
501 return;
Sam Clegg50686852018-01-12 18:35:13 +0000502
Sam Cleggc94d3932017-11-17 18:14:09 +0000503 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
504
Sam Cleggc94d3932017-11-17 18:14:09 +0000505 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
506 raw_ostream &OS = FunctionSubsection.getStream();
Sam Clegg1963d712018-01-17 20:19:04 +0000507 writeUleb128(OS, NumNames, "name count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000508
Sam Clegg93102972018-02-23 05:08:53 +0000509 // Names must appear in function index order. As it happens ImportedSymbols
510 // and InputFunctions are numbered in order with imported functions coming
Sam Clegg1963d712018-01-17 20:19:04 +0000511 // first.
Sam Clegg93102972018-02-23 05:08:53 +0000512 for (const Symbol *S : ImportedSymbols) {
513 if (!isa<FunctionSymbol>(S))
514 continue;
Sam Clegg1963d712018-01-17 20:19:04 +0000515 writeUleb128(OS, S->getOutputIndex(), "import index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000516 writeStr(OS, S->getName(), "symbol name");
517 }
Sam Clegg9f934222018-02-21 18:29:23 +0000518 for (const InputFunction *F : InputFunctions) {
Sam Clegg1963d712018-01-17 20:19:04 +0000519 if (!F->getName().empty()) {
520 writeUleb128(OS, F->getOutputIndex(), "func index");
521 writeStr(OS, F->getName(), "symbol name");
522 }
523 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000524
525 FunctionSubsection.finalizeContents();
526 FunctionSubsection.writeToStream(Section->getStream());
527}
528
529void Writer::writeHeader() {
530 memcpy(Buffer->getBufferStart(), Header.data(), Header.size());
531}
532
533void Writer::writeSections() {
534 uint8_t *Buf = Buffer->getBufferStart();
535 parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); });
536}
537
538// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000539// to each of the input data sections as well as the explicit stack region.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000540// The memory layout is as follows, from low to high.
541// - initialized data (starting at Config->GlobalBase)
542// - BSS data (not currently implemented in llvm)
543// - explicit stack (Config->ZStackSize)
544// - heap start / unallocated
Sam Cleggc94d3932017-11-17 18:14:09 +0000545void Writer::layoutMemory() {
546 uint32_t MemoryPtr = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000547 MemoryPtr = Config->GlobalBase;
548 debugPrint("mem: global base = %d\n", Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000549
550 createOutputSegments();
551
Sam Cleggf0d433d2018-02-02 22:59:56 +0000552 // Arbitrarily set __dso_handle handle to point to the start of the data
553 // segments.
554 if (WasmSym::DsoHandle)
555 WasmSym::DsoHandle->setVirtualAddress(MemoryPtr);
556
Sam Cleggc94d3932017-11-17 18:14:09 +0000557 for (OutputSegment *Seg : Segments) {
558 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
559 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000560 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000561 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
562 MemoryPtr += Seg->Size;
563 }
564
Sam Cleggf0d433d2018-02-02 22:59:56 +0000565 // TODO: Add .bss space here.
Sam Clegg37a4a8a2018-02-07 03:04:53 +0000566 if (WasmSym::DataEnd)
567 WasmSym::DataEnd->setVirtualAddress(MemoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000568
Sam Clegg99eb42c2018-02-27 23:58:03 +0000569 debugPrint("mem: static data = %d\n", MemoryPtr - Config->GlobalBase);
Sam Cleggc94d3932017-11-17 18:14:09 +0000570
Sam Cleggf0d433d2018-02-02 22:59:56 +0000571 // Stack comes after static data and bss
Sam Cleggc94d3932017-11-17 18:14:09 +0000572 if (!Config->Relocatable) {
573 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
574 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
575 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
576 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
577 debugPrint("mem: stack base = %d\n", MemoryPtr);
578 MemoryPtr += Config->ZStackSize;
Sam Clegg93102972018-02-23 05:08:53 +0000579 WasmSym::StackPointer->Global->Global.InitExpr.Value.Int32 = MemoryPtr;
Sam Cleggc94d3932017-11-17 18:14:09 +0000580 debugPrint("mem: stack top = %d\n", MemoryPtr);
Sam Clegg93102972018-02-23 05:08:53 +0000581
Sam Clegg51bcdc22018-01-17 01:34:31 +0000582 // Set `__heap_base` to directly follow the end of the stack. We don't
583 // allocate any heap memory up front, but instead really on the malloc/brk
584 // implementation growing the memory at runtime.
Sam Cleggf0d433d2018-02-02 22:59:56 +0000585 WasmSym::HeapBase->setVirtualAddress(MemoryPtr);
Sam Clegg51bcdc22018-01-17 01:34:31 +0000586 debugPrint("mem: heap base = %d\n", MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000587 }
588
589 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
590 NumMemoryPages = MemSize / WasmPageSize;
591 debugPrint("mem: total pages = %d\n", NumMemoryPages);
592}
593
594SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000595 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000596 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000597 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000598 OutputSections.push_back(Sec);
599 return Sec;
600}
601
602void Writer::createSections() {
603 // Known sections
604 createTypeSection();
605 createImportSection();
606 createFunctionSection();
607 createTableSection();
608 createMemorySection();
609 createGlobalSection();
610 createExportSection();
Sam Cleggc94d3932017-11-17 18:14:09 +0000611 createElemSection();
612 createCodeSection();
613 createDataSection();
614
615 // Custom sections
Sam Clegg99eb42c2018-02-27 23:58:03 +0000616 if (Config->Relocatable) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000617 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000618 createLinkingSection();
619 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000620 if (!Config->StripDebug && !Config->StripAll)
621 createNameSection();
622
623 for (OutputSection *S : OutputSections) {
624 S->setOffset(FileSize);
625 S->finalizeContents();
626 FileSize += S->getSize();
627 }
628}
629
Sam Cleggc94d3932017-11-17 18:14:09 +0000630void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000631 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000632 if (!Sym->isUndefined())
633 continue;
634 if (isa<DataSymbol>(Sym))
635 continue;
636 if (Sym->isWeak() && !Config->Relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000637 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000638
Sam Clegg93102972018-02-23 05:08:53 +0000639 DEBUG(dbgs() << "import: " << Sym->getName() << "\n");
640 Sym->setOutputIndex(ImportedSymbols.size());
641 ImportedSymbols.emplace_back(Sym);
642 if (isa<FunctionSymbol>(Sym))
643 ++NumImportedFunctions;
644 else
645 ++NumImportedGlobals;
Sam Cleggc94d3932017-11-17 18:14:09 +0000646 }
647}
648
Sam Cleggd3052d52018-01-18 23:40:49 +0000649void Writer::calculateExports() {
Sam Clegg93102972018-02-23 05:08:53 +0000650 if (Config->Relocatable)
651 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000652
Sam Clegg93102972018-02-23 05:08:53 +0000653 auto ExportSym = [&](Symbol *Sym) {
654 if (!Sym->isDefined())
655 return;
656 if (Sym->isHidden() || Sym->isLocal())
657 return;
658 if (!Sym->isLive())
659 return;
660
661 DEBUG(dbgs() << "exporting sym: " << Sym->getName() << "\n");
662
663 if (auto *D = dyn_cast<DefinedData>(Sym)) {
664 // TODO Remove this check here; for non-relocatable output we actually
665 // used only to create fake-global exports for the synthetic symbols. Fix
666 // this in a future commit
667 if (Sym != WasmSym::DataEnd && Sym != WasmSym::HeapBase)
668 return;
669 DefinedFakeGlobals.emplace_back(D);
Sam Cleggd3052d52018-01-18 23:40:49 +0000670 }
Sam Clegg93102972018-02-23 05:08:53 +0000671 ExportedSymbols.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000672 };
673
Sam Clegg93102972018-02-23 05:08:53 +0000674 // TODO The two loops below should be replaced with this single loop, with
675 // ExportSym inlined:
676 // for (Symbol *Sym : Symtab->getSymbols())
677 // ExportSym(Sym);
678 // Making that change would reorder the output though, so it should be done as
679 // a separate commit.
Sam Cleggd3052d52018-01-18 23:40:49 +0000680
Sam Clegg93102972018-02-23 05:08:53 +0000681 for (ObjFile *File : Symtab->ObjectFiles)
682 for (Symbol *Sym : File->getSymbols())
683 if (File == Sym->getFile())
684 ExportSym(Sym);
685
686 for (Symbol *Sym : Symtab->getSymbols())
687 if (Sym->getFile() == nullptr)
688 ExportSym(Sym);
689}
690
691void Writer::assignSymtab() {
692 if (!Config->Relocatable)
693 return;
694
695 unsigned SymbolIndex = SymtabEntries.size();
Sam Cleggd3052d52018-01-18 23:40:49 +0000696 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg93102972018-02-23 05:08:53 +0000697 DEBUG(dbgs() << "Symtab entries: " << File->getName() << "\n");
Sam Cleggd3052d52018-01-18 23:40:49 +0000698 for (Symbol *Sym : File->getSymbols()) {
Sam Clegg93102972018-02-23 05:08:53 +0000699 if (Sym->getFile() != File)
Sam Cleggd3052d52018-01-18 23:40:49 +0000700 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000701 if (!Sym->isLive())
702 return;
703 Sym->setOutputSymbolIndex(SymbolIndex++);
704 SymtabEntries.emplace_back(Sym);
Sam Cleggd3052d52018-01-18 23:40:49 +0000705 }
706 }
707
Sam Clegg93102972018-02-23 05:08:53 +0000708 // For the moment, relocatable output doesn't contain any synthetic functions,
709 // so no need to look through the Symtab for symbols not referenced by
710 // Symtab->ObjectFiles.
Sam Cleggd3052d52018-01-18 23:40:49 +0000711}
712
Sam Cleggc375e4e2018-01-10 19:18:22 +0000713uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000714 auto It = TypeIndices.find(Sig);
715 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000716 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000717 return 0;
718 }
719 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000720}
721
722uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000723 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000724 if (Pair.second) {
725 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000726 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000727 }
Sam Cleggb8621592017-11-30 01:40:08 +0000728 return Pair.first->second;
729}
730
Sam Cleggc94d3932017-11-17 18:14:09 +0000731void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000732 // The output type section is the union of the following sets:
733 // 1. Any signature used in the TYPE relocation
734 // 2. The signatures of all imported functions
735 // 3. The signatures of all defined functions
736
Sam Cleggc94d3932017-11-17 18:14:09 +0000737 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000738 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
739 for (uint32_t I = 0; I < Types.size(); I++)
740 if (File->TypeIsUsed[I])
741 File->TypeMap[I] = registerType(Types[I]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000742 }
Sam Clegg50686852018-01-12 18:35:13 +0000743
Sam Clegg93102972018-02-23 05:08:53 +0000744 for (const Symbol *Sym : ImportedSymbols)
745 if (auto *F = dyn_cast<FunctionSymbol>(Sym))
746 registerType(*F->getFunctionType());
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000747
Sam Clegg9f934222018-02-21 18:29:23 +0000748 for (const InputFunction *F : InputFunctions)
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000749 registerType(F->Signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000750}
751
Sam Clegg8d146bb2018-01-09 23:56:44 +0000752void Writer::assignIndexes() {
Sam Clegg93102972018-02-23 05:08:53 +0000753 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
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 Clegg9f934222018-02-21 18:29:23 +0000759 InputFunctions.emplace_back(Func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000760 Func->setOutputIndex(FunctionIndex++);
761 }
762 }
763
Sam Clegg93102972018-02-23 05:08:53 +0000764 uint32_t TableIndex = kInitialTableOffset;
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000765 auto HandleRelocs = [&](InputChunk *Chunk) {
766 if (!Chunk->Live)
767 return;
768 ObjFile *File = Chunk->File;
769 ArrayRef<WasmSignature> Types = File->getWasmObj()->types();
Sam Clegg93102972018-02-23 05:08:53 +0000770 for (const WasmRelocation &Reloc : Chunk->getRelocations()) {
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000771 if (Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_I32 ||
772 Reloc.Type == R_WEBASSEMBLY_TABLE_INDEX_SLEB) {
773 FunctionSymbol *Sym = File->getFunctionSymbol(Reloc.Index);
774 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) {
Sam Clegg93102972018-02-23 05:08:53 +0000779 // Mark target type as live
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000780 File->TypeMap[Reloc.Index] = registerType(Types[Reloc.Index]);
781 File->TypeIsUsed[Reloc.Index] = true;
Sam Clegg93102972018-02-23 05:08:53 +0000782 } else if (Reloc.Type == R_WEBASSEMBLY_GLOBAL_INDEX_LEB) {
783 // Mark target global as live
784 GlobalSymbol *Sym = File->getGlobalSymbol(Reloc.Index);
785 if (auto *G = dyn_cast<DefinedGlobal>(Sym)) {
786 DEBUG(dbgs() << "marking global live: " << Sym->getName() << "\n");
787 G->Global->Live = true;
788 }
Sam Clegg6c4dbfee2018-02-23 04:59:57 +0000789 }
790 }
791 };
792
Sam Clegg8d146bb2018-01-09 23:56:44 +0000793 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000794 DEBUG(dbgs() << "Handle relocs: " << File->getName() << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000795 for (InputChunk *Chunk : File->Functions)
796 HandleRelocs(Chunk);
797 for (InputChunk *Chunk : File->Segments)
798 HandleRelocs(Chunk);
799 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000800
Sam Clegg93102972018-02-23 05:08:53 +0000801 uint32_t GlobalIndex = NumImportedGlobals + InputGlobals.size();
802 auto AddDefinedGlobal = [&](InputGlobal *Global) {
803 if (Global->Live) {
804 DEBUG(dbgs() << "AddDefinedGlobal: " << GlobalIndex << "\n");
805 Global->setOutputIndex(GlobalIndex++);
806 InputGlobals.push_back(Global);
807 }
808 };
809
810 if (WasmSym::StackPointer)
811 AddDefinedGlobal(WasmSym::StackPointer->Global);
812
813 for (ObjFile *File : Symtab->ObjectFiles) {
814 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
815 for (InputGlobal *Global : File->Globals)
816 AddDefinedGlobal(Global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000817 }
818}
819
820static StringRef getOutputDataSegmentName(StringRef Name) {
821 if (Config->Relocatable)
822 return Name;
823
824 for (StringRef V :
825 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
826 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
827 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
828 StringRef Prefix = V.drop_back();
829 if (Name.startswith(V) || Name == Prefix)
830 return Prefix;
831 }
832
833 return Name;
834}
835
836void Writer::createOutputSegments() {
837 for (ObjFile *File : Symtab->ObjectFiles) {
838 for (InputSegment *Segment : File->Segments) {
Sam Clegg447ae402018-02-13 20:29:38 +0000839 if (!Segment->Live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000840 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000841 StringRef Name = getOutputDataSegmentName(Segment->getName());
842 OutputSegment *&S = SegmentMap[Name];
843 if (S == nullptr) {
844 DEBUG(dbgs() << "new segment: " << Name << "\n");
Sam Clegg93102972018-02-23 05:08:53 +0000845 S = make<OutputSegment>(Name, Segments.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000846 Segments.push_back(S);
847 }
848 S->addInputSegment(Segment);
849 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000850 }
851 }
852}
853
Sam Clegg50686852018-01-12 18:35:13 +0000854static const int OPCODE_CALL = 0x10;
855static const int OPCODE_END = 0xb;
856
857// Create synthetic "__wasm_call_ctors" function based on ctor functions
858// in input object.
859void Writer::createCtorFunction() {
Sam Clegg93102972018-02-23 05:08:53 +0000860 uint32_t FunctionIndex = NumImportedFunctions + InputFunctions.size();
Sam Cleggf0d433d2018-02-02 22:59:56 +0000861 WasmSym::CallCtors->setOutputIndex(FunctionIndex);
Sam Clegg50686852018-01-12 18:35:13 +0000862
863 // First write the body bytes to a string.
864 std::string FunctionBody;
Sam Clegg93102972018-02-23 05:08:53 +0000865 const WasmSignature *Signature = WasmSym::CallCtors->getFunctionType();
Sam Clegg50686852018-01-12 18:35:13 +0000866 {
867 raw_string_ostream OS(FunctionBody);
868 writeUleb128(OS, 0, "num locals");
Sam Clegg93102972018-02-23 05:08:53 +0000869 for (const WasmInitEntry &F : InitFunctions) {
Sam Clegg50686852018-01-12 18:35:13 +0000870 writeU8(OS, OPCODE_CALL, "CALL");
Sam Clegg93102972018-02-23 05:08:53 +0000871 writeUleb128(OS, F.Sym->getOutputIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000872 }
873 writeU8(OS, OPCODE_END, "END");
874 }
875
876 // Once we know the size of the body we can create the final function body
877 raw_string_ostream OS(CtorFunctionBody);
878 writeUleb128(OS, FunctionBody.size(), "function size");
879 OS.flush();
880 CtorFunctionBody += FunctionBody;
Sam Clegg4a379c32018-01-13 00:22:00 +0000881 ArrayRef<uint8_t> BodyArray(
882 reinterpret_cast<const uint8_t *>(CtorFunctionBody.data()),
883 CtorFunctionBody.size());
Sam Clegg93102972018-02-23 05:08:53 +0000884 SyntheticFunction *F = make<SyntheticFunction>(*Signature, BodyArray,
Sam Clegg011dce22018-02-21 18:37:44 +0000885 WasmSym::CallCtors->getName());
886 F->setOutputIndex(FunctionIndex);
Sam Clegg93102972018-02-23 05:08:53 +0000887 F->Live = true;
888 WasmSym::CallCtors->Function = F;
Sam Clegg011dce22018-02-21 18:37:44 +0000889 InputFunctions.emplace_back(F);
Sam Clegg50686852018-01-12 18:35:13 +0000890}
891
892// Populate InitFunctions vector with init functions from all input objects.
893// This is then used either when creating the output linking section or to
894// synthesize the "__wasm_call_ctors" function.
895void Writer::calculateInitFunctions() {
896 for (ObjFile *File : Symtab->ObjectFiles) {
897 const WasmLinkingData &L = File->getWasmObj()->linkingData();
898 InitFunctions.reserve(InitFunctions.size() + L.InitFunctions.size());
899 for (const WasmInitFunc &F : L.InitFunctions)
Sam Clegg93102972018-02-23 05:08:53 +0000900 InitFunctions.emplace_back(
901 WasmInitEntry{File->getFunctionSymbol(F.Symbol), F.Priority});
Sam Clegg50686852018-01-12 18:35:13 +0000902 }
903 // Sort in order of priority (lowest first) so that they are called
904 // in the correct order.
Sam Clegg29b8feb2018-02-21 00:34:34 +0000905 std::stable_sort(InitFunctions.begin(), InitFunctions.end(),
Sam Clegg93102972018-02-23 05:08:53 +0000906 [](const WasmInitEntry &L, const WasmInitEntry &R) {
Sam Clegg29b8feb2018-02-21 00:34:34 +0000907 return L.Priority < R.Priority;
908 });
Sam Clegg50686852018-01-12 18:35:13 +0000909}
910
Sam Cleggc94d3932017-11-17 18:14:09 +0000911void Writer::run() {
Sam Clegg99eb42c2018-02-27 23:58:03 +0000912 if (Config->Relocatable)
913 Config->GlobalBase = 0;
914
Sam Cleggc94d3932017-11-17 18:14:09 +0000915 log("-- calculateImports");
916 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000917 log("-- assignIndexes");
918 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000919 log("-- calculateInitFunctions");
920 calculateInitFunctions();
921 if (!Config->Relocatable)
922 createCtorFunction();
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000923 log("-- calculateTypes");
924 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000925 log("-- layoutMemory");
926 layoutMemory();
927 log("-- calculateExports");
928 calculateExports();
929 log("-- assignSymtab");
930 assignSymtab();
Sam Cleggc94d3932017-11-17 18:14:09 +0000931
932 if (errorHandler().Verbose) {
Sam Clegg9f934222018-02-21 18:29:23 +0000933 log("Defined Functions: " + Twine(InputFunctions.size()));
Sam Clegg93102972018-02-23 05:08:53 +0000934 log("Defined Globals : " + Twine(InputGlobals.size()));
935 log("Function Imports : " + Twine(NumImportedFunctions));
936 log("Global Imports : " + Twine(NumImportedGlobals));
Sam Cleggc94d3932017-11-17 18:14:09 +0000937 for (ObjFile *File : Symtab->ObjectFiles)
938 File->dumpInfo();
939 }
940
Sam Cleggc94d3932017-11-17 18:14:09 +0000941 createHeader();
942 log("-- createSections");
943 createSections();
944
945 log("-- openFile");
946 openFile();
947 if (errorCount())
948 return;
949
950 writeHeader();
951
952 log("-- writeSections");
953 writeSections();
954 if (errorCount())
955 return;
956
957 if (Error E = Buffer->commit())
958 fatal("failed to write the output file: " + toString(std::move(E)));
959}
960
961// Open a result file.
962void Writer::openFile() {
963 log("writing: " + Config->OutputFile);
964 ::remove(Config->OutputFile.str().c_str());
965
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(); }