blob: eea5439c2b9057069753ad5932ff077fa19bcbe9 [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;
38
39namespace {
40
Sam Cleggc94d3932017-11-17 18:14:09 +000041// Traits for using WasmSignature in a DenseMap.
42struct WasmSignatureDenseMapInfo {
43 static WasmSignature getEmptyKey() {
44 WasmSignature Sig;
45 Sig.ReturnType = 1;
46 return Sig;
47 }
48 static WasmSignature getTombstoneKey() {
49 WasmSignature Sig;
50 Sig.ReturnType = 2;
51 return Sig;
52 }
53 static unsigned getHashValue(const WasmSignature &Sig) {
54 uintptr_t Value = 0;
55 Value += DenseMapInfo<int32_t>::getHashValue(Sig.ReturnType);
56 for (int32_t Param : Sig.ParamTypes)
57 Value += DenseMapInfo<int32_t>::getHashValue(Param);
58 return Value;
59 }
60 static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
61 return LHS == RHS;
62 }
63};
64
65// The writer writes a SymbolTable result to a file.
66class Writer {
67public:
68 void run();
69
70private:
71 void openFile();
72
Sam Cleggc375e4e2018-01-10 19:18:22 +000073 uint32_t lookupType(const WasmSignature &Sig);
74 uint32_t registerType(const WasmSignature &Sig);
Sam Clegg50686852018-01-12 18:35:13 +000075 void createCtorFunction();
76 void calculateInitFunctions();
Sam Clegg8d146bb2018-01-09 23:56:44 +000077 void assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +000078 void calculateImports();
79 void calculateOffsets();
80 void calculateTypes();
81 void createOutputSegments();
82 void layoutMemory();
83 void createHeader();
84 void createSections();
85 SyntheticSection *createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +000086 StringRef Name = "");
Sam Cleggc94d3932017-11-17 18:14:09 +000087
88 // Builtin sections
89 void createTypeSection();
90 void createFunctionSection();
91 void createTableSection();
92 void createGlobalSection();
93 void createExportSection();
94 void createImportSection();
95 void createMemorySection();
96 void createElemSection();
97 void createStartSection();
98 void createCodeSection();
99 void createDataSection();
100
101 // Custom sections
102 void createRelocSections();
103 void createLinkingSection();
104 void createNameSection();
105
106 void writeHeader();
107 void writeSections();
108
109 uint64_t FileSize = 0;
110 uint32_t DataSize = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000111 uint32_t NumMemoryPages = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000112 uint32_t InitialTableOffset = 0;
113
114 std::vector<const WasmSignature *> Types;
115 DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000116 std::vector<const Symbol *> ImportedFunctions;
117 std::vector<const Symbol *> ImportedGlobals;
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000118 std::vector<const Symbol *> DefinedGlobals;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000119 std::vector<InputFunction *> DefinedFunctions;
Sam Cleggfc1a9122017-12-11 22:00:56 +0000120 std::vector<const Symbol *> IndirectFunctions;
Sam Clegg50686852018-01-12 18:35:13 +0000121 std::vector<WasmInitFunc> InitFunctions;
Sam Cleggc94d3932017-11-17 18:14:09 +0000122
123 // Elements that are used to construct the final output
124 std::string Header;
125 std::vector<OutputSection *> OutputSections;
126
127 std::unique_ptr<FileOutputBuffer> Buffer;
Sam Clegg50686852018-01-12 18:35:13 +0000128 std::unique_ptr<SyntheticFunction> CtorFunction;
129 std::string CtorFunctionBody;
Sam Cleggc94d3932017-11-17 18:14:09 +0000130
131 std::vector<OutputSegment *> Segments;
132 llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap;
133};
134
135} // anonymous namespace
136
137static void debugPrint(const char *fmt, ...) {
138 if (!errorHandler().Verbose)
139 return;
140 fprintf(stderr, "lld: ");
141 va_list ap;
142 va_start(ap, fmt);
143 vfprintf(stderr, fmt, ap);
144 va_end(ap);
145}
146
147void Writer::createImportSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000148 uint32_t NumImports = ImportedFunctions.size() + ImportedGlobals.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000149 if (Config->ImportMemory)
150 ++NumImports;
151
152 if (NumImports == 0)
153 return;
154
155 SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT);
156 raw_ostream &OS = Section->getStream();
157
158 writeUleb128(OS, NumImports, "import count");
159
Sam Clegg8d146bb2018-01-09 23:56:44 +0000160 for (const Symbol *Sym : ImportedFunctions) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000161 WasmImport Import;
162 Import.Module = "env";
163 Import.Field = Sym->getName();
164 Import.Kind = WASM_EXTERNAL_FUNCTION;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000165 Import.SigIndex = lookupType(Sym->getFunctionType());
Sam Cleggc94d3932017-11-17 18:14:09 +0000166 writeImport(OS, Import);
167 }
168
169 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 Clegg8d146bb2018-01-09 23:56:44 +0000179 for (const Symbol *Sym : ImportedGlobals) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000180 WasmImport Import;
181 Import.Module = "env";
182 Import.Field = Sym->getName();
183 Import.Kind = WASM_EXTERNAL_GLOBAL;
184 Import.Global.Mutable = false;
Sam Cleggd451da12017-12-19 19:56:27 +0000185 Import.Global.Type = WASM_TYPE_I32;
Sam Cleggc94d3932017-11-17 18:14:09 +0000186 writeImport(OS, Import);
187 }
188}
189
190void Writer::createTypeSection() {
191 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE);
192 raw_ostream &OS = Section->getStream();
193 writeUleb128(OS, Types.size(), "type count");
Sam Cleggd451da12017-12-19 19:56:27 +0000194 for (const WasmSignature *Sig : Types)
Sam Cleggc94d3932017-11-17 18:14:09 +0000195 writeSig(OS, *Sig);
Sam Cleggc94d3932017-11-17 18:14:09 +0000196}
197
198void Writer::createFunctionSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000199 if (DefinedFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000200 return;
201
202 SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION);
203 raw_ostream &OS = Section->getStream();
204
Sam Clegg8d146bb2018-01-09 23:56:44 +0000205 writeUleb128(OS, DefinedFunctions.size(), "function count");
206 for (const InputFunction *Func : DefinedFunctions)
Sam Cleggc375e4e2018-01-10 19:18:22 +0000207 writeUleb128(OS, lookupType(Func->Signature), "sig index");
Sam Cleggc94d3932017-11-17 18:14:09 +0000208}
209
210void Writer::createMemorySection() {
211 if (Config->ImportMemory)
212 return;
213
214 SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY);
215 raw_ostream &OS = Section->getStream();
216
217 writeUleb128(OS, 1, "memory count");
218 writeUleb128(OS, 0, "memory limits flags");
219 writeUleb128(OS, NumMemoryPages, "initial pages");
220}
221
222void Writer::createGlobalSection() {
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000223 if (DefinedGlobals.empty())
224 return;
225
Sam Cleggc94d3932017-11-17 18:14:09 +0000226 SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL);
227 raw_ostream &OS = Section->getStream();
228
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000229 writeUleb128(OS, DefinedGlobals.size(), "global count");
230 for (const Symbol *Sym : DefinedGlobals) {
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000231 WasmGlobal Global;
232 Global.Type = WASM_TYPE_I32;
233 Global.Mutable = Sym == Config->StackPointerSymbol;
234 Global.InitExpr.Opcode = WASM_OPCODE_I32_CONST;
235 Global.InitExpr.Value.Int32 = Sym->getVirtualAddress();
Sam Cleggc94d3932017-11-17 18:14:09 +0000236 writeGlobal(OS, Global);
237 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000238}
239
240void Writer::createTableSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000241 // Always output a table section, even if there are no indirect calls.
242 // There are two reasons for this:
243 // 1. For executables it is useful to have an empty table slot at 0
244 // which can be filled with a null function call handler.
245 // 2. If we don't do this, any program that contains a call_indirect but
246 // no address-taken function will fail at validation time since it is
247 // a validation error to include a call_indirect instruction if there
248 // is not table.
249 uint32_t TableSize = InitialTableOffset + IndirectFunctions.size();
250
Sam Cleggc94d3932017-11-17 18:14:09 +0000251 SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE);
252 raw_ostream &OS = Section->getStream();
253
254 writeUleb128(OS, 1, "table count");
255 writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type");
256 writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000257 writeUleb128(OS, TableSize, "table initial size");
258 writeUleb128(OS, TableSize, "table max size");
Sam Cleggc94d3932017-11-17 18:14:09 +0000259}
260
261void Writer::createExportSection() {
Sam Cleggc94d3932017-11-17 18:14:09 +0000262 bool ExportMemory = !Config->Relocatable && !Config->ImportMemory;
Sam Clegg4b27c052017-12-03 02:38:04 +0000263 Symbol *EntrySym = Symtab->find(Config->Entry);
264 bool ExportEntry = !Config->Relocatable && EntrySym && EntrySym->isDefined();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000265 bool ExportHidden = Config->EmitRelocs;
Sam Cleggc94d3932017-11-17 18:14:09 +0000266
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000267 uint32_t NumExports = ExportMemory ? 1 : 0;
Sam Cleggc94d3932017-11-17 18:14:09 +0000268
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000269 std::vector<const Symbol *> SymbolExports;
Sam Clegg4b27c052017-12-03 02:38:04 +0000270 if (ExportEntry)
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000271 SymbolExports.emplace_back(EntrySym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000272
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000273 for (const Symbol *Sym : Symtab->getSymbols()) {
274 if (Sym->isUndefined() || Sym->isGlobal())
275 continue;
276 if (Sym->isHidden() && !ExportHidden)
277 continue;
278 if (ExportEntry && Sym == EntrySym)
279 continue;
280 SymbolExports.emplace_back(Sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000281 }
282
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000283 for (const Symbol *Sym : DefinedGlobals) {
284 // Can't export the SP right now because it mutable and mutable globals
285 // connot be exported.
286 if (Sym == Config->StackPointerSymbol)
287 continue;
288 SymbolExports.emplace_back(Sym);
289 }
290
291 NumExports += SymbolExports.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000292 if (!NumExports)
293 return;
294
295 SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT);
296 raw_ostream &OS = Section->getStream();
297
298 writeUleb128(OS, NumExports, "export count");
299
300 if (ExportMemory) {
301 WasmExport MemoryExport;
302 MemoryExport.Name = "memory";
303 MemoryExport.Kind = WASM_EXTERNAL_MEMORY;
304 MemoryExport.Index = 0;
305 writeExport(OS, MemoryExport);
306 }
307
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000308 for (const Symbol *Sym : SymbolExports) {
Sam Clegg7ed293e2018-01-12 00:34:04 +0000309 DEBUG(dbgs() << "Export: " << Sym->getName() << "\n");
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000310 WasmExport Export;
311 Export.Name = Sym->getName();
312 Export.Index = Sym->getOutputIndex();
313 if (Sym->isFunction())
314 Export.Kind = WASM_EXTERNAL_FUNCTION;
315 else
316 Export.Kind = WASM_EXTERNAL_GLOBAL;
317 writeExport(OS, Export);
Sam Cleggc94d3932017-11-17 18:14:09 +0000318 }
319}
320
321void Writer::createStartSection() {}
322
323void Writer::createElemSection() {
Sam Cleggfc1a9122017-12-11 22:00:56 +0000324 if (IndirectFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000325 return;
326
327 SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM);
328 raw_ostream &OS = Section->getStream();
329
330 writeUleb128(OS, 1, "segment count");
331 writeUleb128(OS, 0, "table index");
332 WasmInitExpr InitExpr;
333 InitExpr.Opcode = WASM_OPCODE_I32_CONST;
334 InitExpr.Value.Int32 = InitialTableOffset;
335 writeInitExpr(OS, InitExpr);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000336 writeUleb128(OS, IndirectFunctions.size(), "elem count");
Sam Cleggc94d3932017-11-17 18:14:09 +0000337
Sam Cleggfc1a9122017-12-11 22:00:56 +0000338 uint32_t TableIndex = InitialTableOffset;
339 for (const Symbol *Sym : IndirectFunctions) {
340 assert(Sym->getTableIndex() == TableIndex);
341 writeUleb128(OS, Sym->getOutputIndex(), "function index");
342 ++TableIndex;
343 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000344}
345
346void Writer::createCodeSection() {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000347 if (DefinedFunctions.empty())
Sam Cleggc94d3932017-11-17 18:14:09 +0000348 return;
349
350 log("createCodeSection");
351
Sam Clegg8d146bb2018-01-09 23:56:44 +0000352 auto Section = make<CodeSection>(DefinedFunctions);
Sam Cleggc94d3932017-11-17 18:14:09 +0000353 OutputSections.push_back(Section);
354}
355
356void Writer::createDataSection() {
357 if (!Segments.size())
358 return;
359
360 log("createDataSection");
361 auto Section = make<DataSection>(Segments);
362 OutputSections.push_back(Section);
363}
364
Sam Cleggd451da12017-12-19 19:56:27 +0000365// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000366// These are only created when relocatable output is requested.
367void Writer::createRelocSections() {
368 log("createRelocSections");
369 // Don't use iterator here since we are adding to OutputSection
370 size_t OrigSize = OutputSections.size();
371 for (size_t i = 0; i < OrigSize; i++) {
372 OutputSection *S = OutputSections[i];
373 const char *name;
374 uint32_t Count = S->numRelocations();
375 if (!Count)
376 continue;
377
378 if (S->Type == WASM_SEC_DATA)
379 name = "reloc.DATA";
380 else if (S->Type == WASM_SEC_CODE)
381 name = "reloc.CODE";
382 else
Sam Cleggd451da12017-12-19 19:56:27 +0000383 llvm_unreachable("relocations only supported for code and data");
Sam Cleggc94d3932017-11-17 18:14:09 +0000384
385 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, name);
386 raw_ostream &OS = Section->getStream();
387 writeUleb128(OS, S->Type, "reloc section");
388 writeUleb128(OS, Count, "reloc count");
389 S->writeRelocations(OS);
390 }
391}
392
Sam Clegg49ed9262017-12-01 00:53:21 +0000393// Create the custom "linking" section containing linker metadata.
Sam Cleggc94d3932017-11-17 18:14:09 +0000394// This is only created when relocatable output is requested.
395void Writer::createLinkingSection() {
396 SyntheticSection *Section =
397 createSyntheticSection(WASM_SEC_CUSTOM, "linking");
398 raw_ostream &OS = Section->getStream();
399
400 SubSection DataSizeSubSection(WASM_DATA_SIZE);
401 writeUleb128(DataSizeSubSection.getStream(), DataSize, "data size");
402 DataSizeSubSection.finalizeContents();
403 DataSizeSubSection.writeToStream(OS);
404
Sam Clegg0d0dd392017-12-19 17:09:45 +0000405 if (!Config->Relocatable)
406 return;
407
408 if (Segments.size()) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000409 SubSection SubSection(WASM_SEGMENT_INFO);
410 writeUleb128(SubSection.getStream(), Segments.size(), "num data segments");
411 for (const OutputSegment *S : Segments) {
412 writeStr(SubSection.getStream(), S->Name, "segment name");
413 writeUleb128(SubSection.getStream(), S->Alignment, "alignment");
414 writeUleb128(SubSection.getStream(), 0, "flags");
415 }
416 SubSection.finalizeContents();
417 SubSection.writeToStream(OS);
418 }
Sam Clegg0d0dd392017-12-19 17:09:45 +0000419
Sam Clegg0d0dd392017-12-19 17:09:45 +0000420 if (!InitFunctions.empty()) {
421 SubSection SubSection(WASM_INIT_FUNCS);
422 writeUleb128(SubSection.getStream(), InitFunctions.size(),
423 "num init functionsw");
424 for (const WasmInitFunc &F : InitFunctions) {
425 writeUleb128(SubSection.getStream(), F.Priority, "priority");
426 writeUleb128(SubSection.getStream(), F.FunctionIndex, "function index");
427 }
428 SubSection.finalizeContents();
429 SubSection.writeToStream(OS);
430 }
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000431
432 struct ComdatEntry { unsigned Kind; uint32_t Index; };
433 std::map<StringRef,std::vector<ComdatEntry>> Comdats;
434
435 for (const InputFunction *F : DefinedFunctions) {
436 StringRef Comdat = F->getComdat();
437 if (!Comdat.empty())
438 Comdats[Comdat].emplace_back(
439 ComdatEntry{WASM_COMDAT_FUNCTION, F->getOutputIndex()});
440 }
441 for (uint32_t I = 0; I < Segments.size(); ++I) {
442 const auto &InputSegments = Segments[I]->InputSegments;
443 if (InputSegments.empty())
444 continue;
445 StringRef Comdat = InputSegments[0]->getComdat();
446 for (const InputSegment *IS : InputSegments)
447 assert(IS->getComdat() == Comdat);
448 if (!Comdat.empty())
449 Comdats[Comdat].emplace_back(ComdatEntry{WASM_COMDAT_DATA, I});
450 }
451
452 if (!Comdats.empty()) {
453 SubSection SubSection(WASM_COMDAT_INFO);
454 writeUleb128(SubSection.getStream(), Comdats.size(), "num comdats");
455 for (const auto &C : Comdats) {
456 writeStr(SubSection.getStream(), C.first, "comdat name");
457 writeUleb128(SubSection.getStream(), 0, "comdat flags"); // flags for future use
458 writeUleb128(SubSection.getStream(), C.second.size(), "num entries");
459 for (const ComdatEntry &Entry : C.second) {
460 writeUleb128(SubSection.getStream(), Entry.Kind, "entry kind");
461 writeUleb128(SubSection.getStream(), Entry.Index, "entry index");
462 }
463 }
464 SubSection.finalizeContents();
465 SubSection.writeToStream(OS);
466 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000467}
468
469// Create the custom "name" section containing debug symbol names.
470void Writer::createNameSection() {
471 // Create an array of all function sorted by function index space
472 std::vector<const Symbol *> Names;
473
Sam Clegg50686852018-01-12 18:35:13 +0000474 auto AddToNames = [&](Symbol* S) {
475 if (!S->isFunction() || S->WrittenToNameSec)
476 return;
477 // We also need to guard against two different symbols (two different
478 // names) for the same wasm function. While this is possible (aliases)
479 // it is not legal in the "name" section.
480 InputFunction *Function = S->getFunction();
481 if (Function) {
482 if (Function->WrittenToNameSec)
483 return;
484 Function->WrittenToNameSec = true;
485 }
486 S->WrittenToNameSec = true;
487 Names.emplace_back(S);
488 };
489
Sam Cleggc94d3932017-11-17 18:14:09 +0000490 for (ObjFile *File : Symtab->ObjectFiles) {
491 Names.reserve(Names.size() + File->getSymbols().size());
Sam Clegg50686852018-01-12 18:35:13 +0000492 DEBUG(dbgs() << "adding names from: " << File->getName() << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000493 for (Symbol *S : File->getSymbols()) {
Sam Clegg50686852018-01-12 18:35:13 +0000494 if (S->isWeak())
Sam Cleggc94d3932017-11-17 18:14:09 +0000495 continue;
Sam Clegg50686852018-01-12 18:35:13 +0000496 AddToNames(S);
Sam Cleggc94d3932017-11-17 18:14:09 +0000497 }
498 }
499
Sam Clegg50686852018-01-12 18:35:13 +0000500 DEBUG(dbgs() << "adding symtab names\n");
501 for (Symbol *S : Symtab->getSymbols()) {
502 DEBUG(dbgs() << "sym: " << S->getName() << "\n");
503 if (S->getFile())
504 continue;
505 AddToNames(S);
506 }
507
Sam Cleggc94d3932017-11-17 18:14:09 +0000508 SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name");
509
510 std::sort(Names.begin(), Names.end(), [](const Symbol *A, const Symbol *B) {
511 return A->getOutputIndex() < B->getOutputIndex();
512 });
513
514 SubSection FunctionSubsection(WASM_NAMES_FUNCTION);
515 raw_ostream &OS = FunctionSubsection.getStream();
516 writeUleb128(OS, Names.size(), "name count");
517
518 // We have to iterate through the inputs twice so that all the imports
519 // appear first before any of the local function names.
520 for (const Symbol *S : Names) {
521 writeUleb128(OS, S->getOutputIndex(), "func index");
522 writeStr(OS, S->getName(), "symbol name");
523 }
524
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 Cleggc94d3932017-11-17 18:14:09 +0000540void Writer::layoutMemory() {
541 uint32_t MemoryPtr = 0;
542 if (!Config->Relocatable) {
543 MemoryPtr = Config->GlobalBase;
544 debugPrint("mem: global base = %d\n", Config->GlobalBase);
545 }
546
547 createOutputSegments();
548
549 // Static data comes first
550 for (OutputSegment *Seg : Segments) {
551 MemoryPtr = alignTo(MemoryPtr, Seg->Alignment);
552 Seg->StartVA = MemoryPtr;
Sam Clegg7ed293e2018-01-12 00:34:04 +0000553 debugPrint("mem: %-15s offset=%-8d size=%-8d align=%d\n",
Sam Cleggc94d3932017-11-17 18:14:09 +0000554 Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment);
555 MemoryPtr += Seg->Size;
556 }
557
558 DataSize = MemoryPtr;
559 if (!Config->Relocatable)
560 DataSize -= Config->GlobalBase;
561 debugPrint("mem: static data = %d\n", DataSize);
562
563 // Stack comes after static data
564 if (!Config->Relocatable) {
565 MemoryPtr = alignTo(MemoryPtr, kStackAlignment);
566 if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment))
567 error("stack size must be " + Twine(kStackAlignment) + "-byte aligned");
568 debugPrint("mem: stack size = %d\n", Config->ZStackSize);
569 debugPrint("mem: stack base = %d\n", MemoryPtr);
570 MemoryPtr += Config->ZStackSize;
Sam Clegg4eedcfc2017-12-05 19:05:45 +0000571 Config->StackPointerSymbol->setVirtualAddress(MemoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000572 debugPrint("mem: stack top = %d\n", MemoryPtr);
573 }
574
575 uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize);
576 NumMemoryPages = MemSize / WasmPageSize;
577 debugPrint("mem: total pages = %d\n", NumMemoryPages);
578}
579
580SyntheticSection *Writer::createSyntheticSection(uint32_t Type,
Sam Cleggc375e4e2018-01-10 19:18:22 +0000581 StringRef Name) {
Sam Cleggc94d3932017-11-17 18:14:09 +0000582 auto Sec = make<SyntheticSection>(Type, Name);
Sam Cleggab2ac292017-12-20 05:14:48 +0000583 log("createSection: " + toString(*Sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000584 OutputSections.push_back(Sec);
585 return Sec;
586}
587
588void Writer::createSections() {
589 // Known sections
590 createTypeSection();
591 createImportSection();
592 createFunctionSection();
593 createTableSection();
594 createMemorySection();
595 createGlobalSection();
596 createExportSection();
597 createStartSection();
598 createElemSection();
599 createCodeSection();
600 createDataSection();
601
602 // Custom sections
Sam Clegg22cfe522017-12-05 16:53:25 +0000603 if (Config->EmitRelocs)
Sam Cleggc94d3932017-11-17 18:14:09 +0000604 createRelocSections();
605 createLinkingSection();
606 if (!Config->StripDebug && !Config->StripAll)
607 createNameSection();
608
609 for (OutputSection *S : OutputSections) {
610 S->setOffset(FileSize);
611 S->finalizeContents();
612 FileSize += S->getSize();
613 }
614}
615
Sam Cleggc94d3932017-11-17 18:14:09 +0000616void Writer::calculateImports() {
Sam Clegg574d7ce2017-12-15 19:23:49 +0000617 for (Symbol *Sym : Symtab->getSymbols()) {
Sam Cleggc0181152017-12-15 22:17:15 +0000618 if (!Sym->isUndefined() || Sym->isWeak())
Sam Clegg574d7ce2017-12-15 19:23:49 +0000619 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000620
Sam Clegg574d7ce2017-12-15 19:23:49 +0000621 if (Sym->isFunction()) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000622 Sym->setOutputIndex(ImportedFunctions.size());
623 ImportedFunctions.push_back(Sym);
Sam Clegg574d7ce2017-12-15 19:23:49 +0000624 } else {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000625 Sym->setOutputIndex(ImportedGlobals.size());
626 ImportedGlobals.push_back(Sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000627 }
628 }
629}
630
Sam Cleggc375e4e2018-01-10 19:18:22 +0000631uint32_t Writer::lookupType(const WasmSignature &Sig) {
Sam Clegg8d027d62018-01-10 20:12:26 +0000632 auto It = TypeIndices.find(Sig);
633 if (It == TypeIndices.end()) {
Sam Cleggc375e4e2018-01-10 19:18:22 +0000634 error("type not found: " + toString(Sig));
Sam Clegg8d027d62018-01-10 20:12:26 +0000635 return 0;
636 }
637 return It->second;
Sam Cleggc375e4e2018-01-10 19:18:22 +0000638}
639
640uint32_t Writer::registerType(const WasmSignature &Sig) {
Sam Cleggb8621592017-11-30 01:40:08 +0000641 auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size()));
Sam Cleggc375e4e2018-01-10 19:18:22 +0000642 if (Pair.second) {
643 DEBUG(dbgs() << "type " << toString(Sig) << "\n");
Sam Cleggb8621592017-11-30 01:40:08 +0000644 Types.push_back(&Sig);
Sam Cleggc375e4e2018-01-10 19:18:22 +0000645 }
Sam Cleggb8621592017-11-30 01:40:08 +0000646 return Pair.first->second;
647}
648
Sam Cleggc94d3932017-11-17 18:14:09 +0000649void Writer::calculateTypes() {
650 for (ObjFile *File : Symtab->ObjectFiles) {
651 File->TypeMap.reserve(File->getWasmObj()->types().size());
Sam Cleggb8621592017-11-30 01:40:08 +0000652 for (const WasmSignature &Sig : File->getWasmObj()->types())
Sam Cleggc375e4e2018-01-10 19:18:22 +0000653 File->TypeMap.push_back(registerType(Sig));
Sam Cleggc94d3932017-11-17 18:14:09 +0000654 }
Sam Clegg50686852018-01-12 18:35:13 +0000655
656 for (Symbol *Sym : Symtab->getSymbols())
657 if (Sym->isFunction())
658 registerType(Sym->getFunctionType());
Sam Cleggc94d3932017-11-17 18:14:09 +0000659}
660
Sam Clegg8d146bb2018-01-09 23:56:44 +0000661void Writer::assignIndexes() {
Sam Clegg50686852018-01-12 18:35:13 +0000662 uint32_t GlobalIndex = ImportedGlobals.size() + DefinedGlobals.size();
663 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000664
665 if (Config->StackPointerSymbol) {
666 DefinedGlobals.emplace_back(Config->StackPointerSymbol);
667 Config->StackPointerSymbol->setOutputIndex(GlobalIndex++);
668 }
669
670 if (Config->EmitRelocs)
671 DefinedGlobals.reserve(Symtab->getSymbols().size());
672
Sam Cleggfc1a9122017-12-11 22:00:56 +0000673 uint32_t TableIndex = InitialTableOffset;
674
Sam Cleggc94d3932017-11-17 18:14:09 +0000675 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000676 if (Config->EmitRelocs) {
677 DEBUG(dbgs() << "Globals: " << File->getName() << "\n");
678 for (Symbol *Sym : File->getSymbols()) {
679 // Create wasm globals for data symbols defined in this file
680 if (!Sym->isDefined() || File != Sym->getFile())
681 continue;
682 if (Sym->isFunction())
683 continue;
Sam Cleggfc1a9122017-12-11 22:00:56 +0000684
Sam Clegg74fe0ba2017-12-07 01:51:24 +0000685 DefinedGlobals.emplace_back(Sym);
686 Sym->setOutputIndex(GlobalIndex++);
Sam Cleggc94d3932017-11-17 18:14:09 +0000687 }
688 }
Sam Clegg87e61922018-01-08 23:39:11 +0000689 }
Sam Cleggfc1a9122017-12-11 22:00:56 +0000690
Sam Clegg87e61922018-01-08 23:39:11 +0000691 for (ObjFile *File : Symtab->ObjectFiles) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000692 DEBUG(dbgs() << "Functions: " << File->getName() << "\n");
693 for (InputFunction *Func : File->Functions) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000694 if (Func->Discarded)
695 continue;
Sam Clegg8d146bb2018-01-09 23:56:44 +0000696 DefinedFunctions.emplace_back(Func);
697 Func->setOutputIndex(FunctionIndex++);
698 }
699 }
700
701 for (ObjFile *File : Symtab->ObjectFiles) {
702 DEBUG(dbgs() << "Table Indexes: " << File->getName() << "\n");
Sam Cleggfc1a9122017-12-11 22:00:56 +0000703 for (Symbol *Sym : File->getTableSymbols()) {
Sam Clegg87e61922018-01-08 23:39:11 +0000704 if (Sym->hasTableIndex() || !Sym->hasOutputIndex())
705 continue;
706 Sym->setTableIndex(TableIndex++);
707 IndirectFunctions.emplace_back(Sym);
Sam Cleggfc1a9122017-12-11 22:00:56 +0000708 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000709 }
710}
711
712static StringRef getOutputDataSegmentName(StringRef Name) {
713 if (Config->Relocatable)
714 return Name;
715
716 for (StringRef V :
717 {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.",
718 ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.",
719 ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) {
720 StringRef Prefix = V.drop_back();
721 if (Name.startswith(V) || Name == Prefix)
722 return Prefix;
723 }
724
725 return Name;
726}
727
728void Writer::createOutputSegments() {
729 for (ObjFile *File : Symtab->ObjectFiles) {
730 for (InputSegment *Segment : File->Segments) {
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000731 if (Segment->Discarded)
732 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000733 StringRef Name = getOutputDataSegmentName(Segment->getName());
734 OutputSegment *&S = SegmentMap[Name];
735 if (S == nullptr) {
736 DEBUG(dbgs() << "new segment: " << Name << "\n");
737 S = make<OutputSegment>(Name);
738 Segments.push_back(S);
739 }
740 S->addInputSegment(Segment);
741 DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000742 }
743 }
744}
745
Sam Clegg50686852018-01-12 18:35:13 +0000746static const int OPCODE_CALL = 0x10;
747static const int OPCODE_END = 0xb;
748
749// Create synthetic "__wasm_call_ctors" function based on ctor functions
750// in input object.
751void Writer::createCtorFunction() {
752 uint32_t FunctionIndex = ImportedFunctions.size() + DefinedFunctions.size();
753 Config->CtorSymbol->setOutputIndex(FunctionIndex);
754
755 // First write the body bytes to a string.
756 std::string FunctionBody;
757 static WasmSignature Signature = {{}, WASM_TYPE_NORESULT};
758 {
759 raw_string_ostream OS(FunctionBody);
760 writeUleb128(OS, 0, "num locals");
761 for (const WasmInitFunc &F : InitFunctions) {
762 writeU8(OS, OPCODE_CALL, "CALL");
763 writeUleb128(OS, F.FunctionIndex, "function index");
764 }
765 writeU8(OS, OPCODE_END, "END");
766 }
767
768 // Once we know the size of the body we can create the final function body
769 raw_string_ostream OS(CtorFunctionBody);
770 writeUleb128(OS, FunctionBody.size(), "function size");
771 OS.flush();
772 CtorFunctionBody += FunctionBody;
773 CtorFunction =
774 llvm::make_unique<SyntheticFunction>(Signature, CtorFunctionBody);
775 DefinedFunctions.emplace_back(CtorFunction.get());
776}
777
778// Populate InitFunctions vector with init functions from all input objects.
779// This is then used either when creating the output linking section or to
780// synthesize the "__wasm_call_ctors" function.
781void Writer::calculateInitFunctions() {
782 for (ObjFile *File : Symtab->ObjectFiles) {
783 const WasmLinkingData &L = File->getWasmObj()->linkingData();
784 InitFunctions.reserve(InitFunctions.size() + L.InitFunctions.size());
785 for (const WasmInitFunc &F : L.InitFunctions)
786 InitFunctions.emplace_back(WasmInitFunc{
787 F.Priority, File->relocateFunctionIndex(F.FunctionIndex)});
788 }
789 // Sort in order of priority (lowest first) so that they are called
790 // in the correct order.
791 std::sort(InitFunctions.begin(), InitFunctions.end(),
792 [](const WasmInitFunc &L, const WasmInitFunc &R) {
793 return L.Priority < R.Priority;
794 });
795}
796
Sam Cleggc94d3932017-11-17 18:14:09 +0000797void Writer::run() {
798 if (!Config->Relocatable)
799 InitialTableOffset = 1;
800
801 log("-- calculateTypes");
802 calculateTypes();
803 log("-- calculateImports");
804 calculateImports();
Sam Clegg8d146bb2018-01-09 23:56:44 +0000805 log("-- assignIndexes");
806 assignIndexes();
Sam Clegg50686852018-01-12 18:35:13 +0000807 log("-- calculateInitFunctions");
808 calculateInitFunctions();
809 if (!Config->Relocatable)
810 createCtorFunction();
Sam Cleggc94d3932017-11-17 18:14:09 +0000811
812 if (errorHandler().Verbose) {
Sam Clegg8d146bb2018-01-09 23:56:44 +0000813 log("Defined Functions: " + Twine(DefinedFunctions.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000814 log("Defined Globals : " + Twine(DefinedGlobals.size()));
Sam Clegg8d146bb2018-01-09 23:56:44 +0000815 log("Function Imports : " + Twine(ImportedFunctions.size()));
816 log("Global Imports : " + Twine(ImportedGlobals.size()));
Sam Cleggfc1a9122017-12-11 22:00:56 +0000817 log("Total Imports : " +
Sam Clegg8d146bb2018-01-09 23:56:44 +0000818 Twine(ImportedFunctions.size() + ImportedGlobals.size()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000819 for (ObjFile *File : Symtab->ObjectFiles)
820 File->dumpInfo();
821 }
822
Sam Cleggc94d3932017-11-17 18:14:09 +0000823 log("-- layoutMemory");
824 layoutMemory();
825
826 createHeader();
827 log("-- createSections");
828 createSections();
829
830 log("-- openFile");
831 openFile();
832 if (errorCount())
833 return;
834
835 writeHeader();
836
837 log("-- writeSections");
838 writeSections();
839 if (errorCount())
840 return;
841
842 if (Error E = Buffer->commit())
843 fatal("failed to write the output file: " + toString(std::move(E)));
844}
845
846// Open a result file.
847void Writer::openFile() {
848 log("writing: " + Config->OutputFile);
849 ::remove(Config->OutputFile.str().c_str());
850
851 Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr =
852 FileOutputBuffer::create(Config->OutputFile, FileSize,
853 FileOutputBuffer::F_executable);
854
855 if (!BufferOrErr)
856 error("failed to open " + Config->OutputFile + ": " +
857 toString(BufferOrErr.takeError()));
858 else
859 Buffer = std::move(*BufferOrErr);
860}
861
862void Writer::createHeader() {
863 raw_string_ostream OS(Header);
864 writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic");
865 writeU32(OS, WasmVersion, "wasm version");
866 OS.flush();
867 FileSize += Header.size();
868}
869
870void lld::wasm::writeResult() { Writer().run(); }