blob: 2dbff1bc88053dcb60b7d5cda1622e328a9d6a0d [file] [log] [blame]
Sam Cleggc94d3932017-11-17 18:14:09 +00001//===- Writer.cpp ---------------------------------------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Sam Cleggc94d3932017-11-17 18:14:09 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "Writer.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000010#include "Config.h"
Sam Clegg5fa274b2018-01-10 01:13:34 +000011#include "InputChunks.h"
Heejin Ahne915a712018-12-08 06:17:43 +000012#include "InputEvent.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"
Sam Clegg8fcf0122019-05-21 09:13:09 +000016#include "Relocations.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000017#include "SymbolTable.h"
Sam Clegg8fcf0122019-05-21 09:13:09 +000018#include "SyntheticSections.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000019#include "WriterUtils.h"
20#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000021#include "lld/Common/Memory.h"
Nicholas Wilson8269f372018-03-07 10:37:50 +000022#include "lld/Common/Strings.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000023#include "lld/Common/Threads.h"
Sam Clegg3141ddc2018-02-20 21:53:18 +000024#include "llvm/ADT/DenseSet.h"
Thomas Livelyf6f4f842019-03-20 20:26:45 +000025#include "llvm/ADT/SmallSet.h"
Thomas Lively2a0868f2019-01-17 02:29:41 +000026#include "llvm/ADT/SmallVector.h"
Sam Clegg80ba4382018-04-10 16:12:49 +000027#include "llvm/ADT/StringMap.h"
Sam Clegg93102972018-02-23 05:08:53 +000028#include "llvm/BinaryFormat/Wasm.h"
Nicholas Wilson3e3f5fb2018-03-14 15:58:16 +000029#include "llvm/Object/WasmTraits.h"
Sam Cleggc94d3932017-11-17 18:14:09 +000030#include "llvm/Support/FileOutputBuffer.h"
31#include "llvm/Support/Format.h"
32#include "llvm/Support/FormatVariadic.h"
33#include "llvm/Support/LEB128.h"
34
35#include <cstdarg>
Sam Clegge0f6fcd2018-01-12 22:25:17 +000036#include <map>
Sam Cleggc94d3932017-11-17 18:14:09 +000037
38#define DEBUG_TYPE "lld"
39
40using namespace llvm;
41using namespace llvm::wasm;
42using namespace lld;
43using namespace lld::wasm;
44
Rui Ueyama136d27a2019-07-11 05:40:30 +000045static constexpr int stackAlignment = 16;
Sam Cleggc94d3932017-11-17 18:14:09 +000046
47namespace {
48
Sam Cleggc94d3932017-11-17 18:14:09 +000049// The writer writes a SymbolTable result to a file.
50class Writer {
51public:
52 void run();
53
54private:
55 void openFile();
56
Thomas Lively6004d9a2019-07-03 22:04:54 +000057 void createInitMemoryFunction();
Sam Clegg09137be2019-04-04 18:40:51 +000058 void createApplyRelocationsFunction();
59 void createCallCtorsFunction();
Guanzhong Chen42bba4b2019-07-16 22:00:45 +000060 void createInitTLSFunction();
Sam Clegg09137be2019-04-04 18:40:51 +000061
Sam Clegg8d146bb2018-01-09 23:56:44 +000062 void assignIndexes();
Sam Clegg8fcf0122019-05-21 09:13:09 +000063 void populateSymtab();
64 void populateProducers();
65 void populateTargetFeatures();
66 void calculateInitFunctions();
Sam Cleggc94d3932017-11-17 18:14:09 +000067 void calculateImports();
Sam Cleggd3052d52018-01-18 23:40:49 +000068 void calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +000069 void calculateCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000070 void calculateTypes();
71 void createOutputSegments();
72 void layoutMemory();
73 void createHeader();
Sam Cleggc94d3932017-11-17 18:14:09 +000074
Rui Ueyama136d27a2019-07-11 05:40:30 +000075 void addSection(OutputSection *sec);
Sam Clegg8fcf0122019-05-21 09:13:09 +000076
77 void addSections();
Sam Clegg4bce63a2019-05-23 10:06:03 +000078
Sam Clegg80ba4382018-04-10 16:12:49 +000079 void createCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +000080 void createSyntheticSections();
81 void finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000082
83 // Custom sections
84 void createRelocSections();
Sam Cleggc94d3932017-11-17 18:14:09 +000085
86 void writeHeader();
87 void writeSections();
88
Rui Ueyama136d27a2019-07-11 05:40:30 +000089 uint64_t fileSize = 0;
90 uint32_t tableBase = 0;
Sam Cleggc94d3932017-11-17 18:14:09 +000091
Rui Ueyama136d27a2019-07-11 05:40:30 +000092 std::vector<WasmInitEntry> initFunctions;
93 llvm::StringMap<std::vector<InputSection *>> customSectionMapping;
Sam Clegg80ba4382018-04-10 16:12:49 +000094
Sam Cleggc94d3932017-11-17 18:14:09 +000095 // Elements that are used to construct the final output
Rui Ueyama136d27a2019-07-11 05:40:30 +000096 std::string header;
97 std::vector<OutputSection *> outputSections;
Sam Cleggc94d3932017-11-17 18:14:09 +000098
Rui Ueyama136d27a2019-07-11 05:40:30 +000099 std::unique_ptr<FileOutputBuffer> buffer;
Sam Cleggc94d3932017-11-17 18:14:09 +0000100
Rui Ueyama136d27a2019-07-11 05:40:30 +0000101 std::vector<OutputSegment *> segments;
102 llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap;
Sam Cleggc94d3932017-11-17 18:14:09 +0000103};
104
105} // anonymous namespace
106
Sam Cleggd177ab22018-05-04 23:14:42 +0000107void Writer::calculateCustomSections() {
108 log("calculateCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000109 bool stripDebug = config->stripDebug || config->stripAll;
110 for (ObjFile *file : symtab->objectFiles) {
111 for (InputSection *section : file->customSections) {
112 StringRef name = section->getName();
Sam Cleggd177ab22018-05-04 23:14:42 +0000113 // These custom sections are known the linker and synthesized rather than
114 // blindly copied
Rui Ueyama136d27a2019-07-11 05:40:30 +0000115 if (name == "linking" || name == "name" || name == "producers" ||
116 name == "target_features" || name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000117 continue;
118 // .. or it is a debug section
Rui Ueyama136d27a2019-07-11 05:40:30 +0000119 if (stripDebug && name.startswith(".debug_"))
Sam Cleggd177ab22018-05-04 23:14:42 +0000120 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000121 customSectionMapping[name].push_back(section);
Sam Cleggd177ab22018-05-04 23:14:42 +0000122 }
123 }
124}
125
Sam Clegg80ba4382018-04-10 16:12:49 +0000126void Writer::createCustomSections() {
127 log("createCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000128 for (auto &pair : customSectionMapping) {
129 StringRef name = pair.first();
130 LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000131
Rui Ueyama136d27a2019-07-11 05:40:30 +0000132 OutputSection *sec = make<CustomSection>(name, pair.second);
133 if (config->relocatable || config->emitRelocs) {
134 auto *sym = make<OutputSectionSymbol>(sec);
135 out.linkingSec->addToSymtab(sym);
136 sec->sectionSym = sym;
Sam Clegg8fcf0122019-05-21 09:13:09 +0000137 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000138 addSection(sec);
Sam Clegg80ba4382018-04-10 16:12:49 +0000139 }
140}
141
Sam Cleggd451da12017-12-19 19:56:27 +0000142// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000143// These are only created when relocatable output is requested.
144void Writer::createRelocSections() {
145 log("createRelocSections");
146 // Don't use iterator here since we are adding to OutputSection
Rui Ueyama136d27a2019-07-11 05:40:30 +0000147 size_t origSize = outputSections.size();
148 for (size_t i = 0; i < origSize; i++) {
149 LLVM_DEBUG(dbgs() << "check section " << i << "\n");
150 OutputSection *sec = outputSections[i];
Sam Clegg8fcf0122019-05-21 09:13:09 +0000151
152 // Count the number of needed sections.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000153 uint32_t count = sec->getNumRelocations();
154 if (!count)
Sam Cleggc94d3932017-11-17 18:14:09 +0000155 continue;
156
Rui Ueyama136d27a2019-07-11 05:40:30 +0000157 StringRef name;
158 if (sec->type == WASM_SEC_DATA)
159 name = "reloc.DATA";
160 else if (sec->type == WASM_SEC_CODE)
161 name = "reloc.CODE";
162 else if (sec->type == WASM_SEC_CUSTOM)
163 name = saver.save("reloc." + sec->name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000164 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000165 llvm_unreachable(
166 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000167
Rui Ueyama136d27a2019-07-11 05:40:30 +0000168 addSection(make<RelocSection>(name, sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000169 }
170}
171
Sam Clegg8fcf0122019-05-21 09:13:09 +0000172void Writer::populateProducers() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000173 for (ObjFile *file : symtab->objectFiles) {
174 const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo();
175 out.producersSec->addInfo(info);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000176 }
177}
178
Sam Cleggc94d3932017-11-17 18:14:09 +0000179void Writer::writeHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000180 memcpy(buffer->getBufferStart(), header.data(), header.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000181}
182
183void Writer::writeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000184 uint8_t *buf = buffer->getBufferStart();
185 parallelForEach(outputSections, [buf](OutputSection *s) {
186 assert(s->isNeeded());
187 s->writeTo(buf);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000188 });
Sam Cleggc94d3932017-11-17 18:14:09 +0000189}
190
191// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000192// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000193// The default memory layout is as follows, from low to high.
194//
Fangrui Song33fdf822019-07-16 08:08:17 +0000195// - initialized data (starting at Config->globalBase)
Sam Cleggf0d433d2018-02-02 22:59:56 +0000196// - BSS data (not currently implemented in llvm)
197// - explicit stack (Config->ZStackSize)
198// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000199//
200// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000201// This can be useful since it means that stack overflow traps immediately
202// rather than overwriting global data, but also increases code size since all
203// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000204void Writer::layoutMemory() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000205 uint32_t memoryPtr = 0;
Sam Clegga0f095e2018-05-03 17:21:53 +0000206
Rui Ueyama136d27a2019-07-11 05:40:30 +0000207 auto placeStack = [&]() {
Sam Cleggfd11ce32019-07-11 13:13:25 +0000208 if (config->relocatable || config->isPic)
Sam Clegga0f095e2018-05-03 17:21:53 +0000209 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000210 memoryPtr = alignTo(memoryPtr, stackAlignment);
211 if (config->zStackSize != alignTo(config->zStackSize, stackAlignment))
212 error("stack size must be " + Twine(stackAlignment) + "-byte aligned");
213 log("mem: stack size = " + Twine(config->zStackSize));
214 log("mem: stack base = " + Twine(memoryPtr));
215 memoryPtr += config->zStackSize;
216 auto *sp = cast<DefinedGlobal>(WasmSym::stackPointer);
217 sp->global->global.InitExpr.Value.Int32 = memoryPtr;
218 log("mem: stack top = " + Twine(memoryPtr));
Sam Clegga0f095e2018-05-03 17:21:53 +0000219 };
220
Rui Ueyama136d27a2019-07-11 05:40:30 +0000221 if (config->stackFirst) {
222 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000223 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000224 memoryPtr = config->globalBase;
225 log("mem: global base = " + Twine(config->globalBase));
Sam Clegga0f095e2018-05-03 17:21:53 +0000226 }
227
Rui Ueyama136d27a2019-07-11 05:40:30 +0000228 if (WasmSym::globalBase)
229 WasmSym::globalBase->setVirtualAddress(config->globalBase);
Guanzhong Chene15dc952019-06-26 20:12:33 +0000230
Rui Ueyama136d27a2019-07-11 05:40:30 +0000231 uint32_t dataStart = memoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000232
Sam Cleggf0d433d2018-02-02 22:59:56 +0000233 // Arbitrarily set __dso_handle handle to point to the start of the data
234 // segments.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000235 if (WasmSym::dsoHandle)
236 WasmSym::dsoHandle->setVirtualAddress(dataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000237
Rui Ueyama136d27a2019-07-11 05:40:30 +0000238 out.dylinkSec->memAlign = 0;
239 for (OutputSegment *seg : segments) {
240 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
241 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
242 seg->startVA = memoryPtr;
243 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
244 memoryPtr, seg->size, seg->alignment));
245 memoryPtr += seg->size;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000246
247 if (WasmSym::tlsSize && seg->name == ".tdata") {
248 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
249 tlsSize->global->global.InitExpr.Value.Int32 = seg->size;
Guanzhong Chen5204f762019-07-19 23:34:16 +0000250
251 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
252 tlsAlign->global->global.InitExpr.Value.Int32 = 1U << seg->alignment;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000253 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000254 }
255
Sam Cleggf0d433d2018-02-02 22:59:56 +0000256 // TODO: Add .bss space here.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000257 if (WasmSym::dataEnd)
258 WasmSym::dataEnd->setVirtualAddress(memoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000259
Rui Ueyama136d27a2019-07-11 05:40:30 +0000260 log("mem: static data = " + Twine(memoryPtr - dataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000261
Rui Ueyama136d27a2019-07-11 05:40:30 +0000262 if (config->shared) {
263 out.dylinkSec->memSize = memoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000264 return;
265 }
266
Rui Ueyama136d27a2019-07-11 05:40:30 +0000267 if (!config->stackFirst)
268 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000269
270 // Set `__heap_base` to directly follow the end of the stack or global data.
271 // The fact that this comes last means that a malloc/brk implementation
272 // can grow the heap at runtime.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000273 log("mem: heap base = " + Twine(memoryPtr));
274 if (WasmSym::heapBase)
275 WasmSym::heapBase->setVirtualAddress(memoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000276
Rui Ueyama136d27a2019-07-11 05:40:30 +0000277 if (config->initialMemory != 0) {
278 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000279 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000280 if (memoryPtr > config->initialMemory)
281 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000282 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000283 memoryPtr = config->initialMemory;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000284 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000285 out.dylinkSec->memSize = memoryPtr;
286 out.memorySec->numMemoryPages =
287 alignTo(memoryPtr, WasmPageSize) / WasmPageSize;
288 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000289
Thomas Lively06391f32019-03-29 20:43:49 +0000290 // Check max if explicitly supplied or required by shared memory
Rui Ueyama136d27a2019-07-11 05:40:30 +0000291 if (config->maxMemory != 0 || config->sharedMemory) {
292 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000293 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000294 if (memoryPtr > config->maxMemory)
295 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
296 out.memorySec->maxMemoryPages = config->maxMemory / WasmPageSize;
297 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000298 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000299}
300
Rui Ueyama136d27a2019-07-11 05:40:30 +0000301void Writer::addSection(OutputSection *sec) {
302 if (!sec->isNeeded())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000303 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000304 log("addSection: " + toString(*sec));
305 sec->sectionIndex = outputSections.size();
306 outputSections.push_back(sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000307}
308
Sam Clegg4bce63a2019-05-23 10:06:03 +0000309// If a section name is valid as a C identifier (which is rare because of
310// the leading '.'), linkers are expected to define __start_<secname> and
311// __stop_<secname> symbols. They are at beginning and end of the section,
312// respectively. This is not requested by the ELF standard, but GNU ld and
313// gold provide the feature, and used by many programs.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000314static void addStartStopSymbols(const OutputSegment *seg) {
315 StringRef name = seg->name;
316 if (!isValidCIdentifier(name))
Sam Clegg4bce63a2019-05-23 10:06:03 +0000317 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000318 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
319 uint32_t start = seg->startVA;
320 uint32_t stop = start + seg->size;
321 symtab->addOptionalDataSymbol(saver.save("__start_" + name), start);
322 symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000323}
324
Sam Clegg8fcf0122019-05-21 09:13:09 +0000325void Writer::addSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000326 addSection(out.dylinkSec);
327 addSection(out.typeSec);
328 addSection(out.importSec);
329 addSection(out.functionSec);
330 addSection(out.tableSec);
331 addSection(out.memorySec);
332 addSection(out.globalSec);
333 addSection(out.eventSec);
334 addSection(out.exportSec);
335 addSection(out.elemSec);
336 addSection(out.dataCountSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000337
Rui Ueyama136d27a2019-07-11 05:40:30 +0000338 addSection(make<CodeSection>(out.functionSec->inputFunctions));
339 addSection(make<DataSection>(segments));
Sam Clegg8fcf0122019-05-21 09:13:09 +0000340
Sam Clegg80ba4382018-04-10 16:12:49 +0000341 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000342
Rui Ueyama136d27a2019-07-11 05:40:30 +0000343 addSection(out.linkingSec);
344 if (config->emitRelocs || config->relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000345 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000346 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000347
Rui Ueyama136d27a2019-07-11 05:40:30 +0000348 addSection(out.nameSec);
349 addSection(out.producersSec);
350 addSection(out.targetFeaturesSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000351}
Sam Cleggc94d3932017-11-17 18:14:09 +0000352
Sam Clegg8fcf0122019-05-21 09:13:09 +0000353void Writer::finalizeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000354 for (OutputSection *s : outputSections) {
355 s->setOffset(fileSize);
356 s->finalizeContents();
357 fileSize += s->getSize();
Sam Cleggc94d3932017-11-17 18:14:09 +0000358 }
359}
360
Sam Clegg8fcf0122019-05-21 09:13:09 +0000361void Writer::populateTargetFeatures() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000362 StringMap<std::string> used;
363 StringMap<std::string> required;
364 StringMap<std::string> disallowed;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000365 bool tlsUsed = false;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000366
Thomas Lively82de51a2019-03-26 04:11:05 +0000367 // Only infer used features if user did not specify features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000368 bool inferFeatures = !config->features.hasValue();
Thomas Lively82de51a2019-03-26 04:11:05 +0000369
Rui Ueyama136d27a2019-07-11 05:40:30 +0000370 if (!inferFeatures) {
371 for (auto &feature : config->features.getValue())
372 out.targetFeaturesSec->features.insert(feature);
Thomas Lively82de51a2019-03-26 04:11:05 +0000373 // No need to read or check features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000374 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000375 return;
376 }
377
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000378 // Find the sets of used, required, and disallowed features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000379 for (ObjFile *file : symtab->objectFiles) {
380 StringRef fileName(file->getName());
381 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
382 switch (feature.Prefix) {
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000383 case WASM_FEATURE_PREFIX_USED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000384 used.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000385 break;
386 case WASM_FEATURE_PREFIX_REQUIRED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000387 used.insert({feature.Name, fileName});
388 required.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000389 break;
390 case WASM_FEATURE_PREFIX_DISALLOWED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000391 disallowed.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000392 break;
393 default:
394 error("Unrecognized feature policy prefix " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000395 std::to_string(feature.Prefix));
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000396 }
397 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000398
399 for (InputSegment *segment : file->segments) {
400 if (!segment->live)
401 continue;
402 StringRef name = segment->getName();
403 if (name.startswith(".tdata") || name.startswith(".tbss"))
404 tlsUsed = true;
405 }
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000406 }
407
Rui Ueyama136d27a2019-07-11 05:40:30 +0000408 if (inferFeatures)
409 out.targetFeaturesSec->features.insert(used.keys().begin(),
410 used.keys().end());
Thomas Lively82de51a2019-03-26 04:11:05 +0000411
Rui Ueyama136d27a2019-07-11 05:40:30 +0000412 if (out.targetFeaturesSec->features.count("atomics") &&
413 !config->sharedMemory) {
414 if (inferFeatures)
415 error(Twine("'atomics' feature is used by ") + used["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000416 ", so --shared-memory must be used");
417 else
418 error("'atomics' feature is used, so --shared-memory must be used");
419 }
Thomas Lively06391f32019-03-29 20:43:49 +0000420
Rui Ueyama136d27a2019-07-11 05:40:30 +0000421 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000422 return;
423
Rui Ueyama136d27a2019-07-11 05:40:30 +0000424 if (disallowed.count("atomics") && config->sharedMemory)
425 error("'atomics' feature is disallowed by " + disallowed["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000426 ", so --shared-memory must not be used");
Thomas Lively06391f32019-03-29 20:43:49 +0000427
Rui Ueyama136d27a2019-07-11 05:40:30 +0000428 if (!used.count("bulk-memory") && config->passiveSegments)
Thomas Lively6004d9a2019-07-03 22:04:54 +0000429 error("'bulk-memory' feature must be used in order to emit passive "
430 "segments");
431
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000432 if (!used.count("bulk-memory") && tlsUsed)
433 error("'bulk-memory' feature must be used in order to use thread-local "
434 "storage");
435
Thomas Lively82de51a2019-03-26 04:11:05 +0000436 // Validate that used features are allowed in output
Rui Ueyama136d27a2019-07-11 05:40:30 +0000437 if (!inferFeatures) {
438 for (auto &feature : used.keys()) {
439 if (!out.targetFeaturesSec->features.count(feature))
440 error(Twine("Target feature '") + feature + "' used by " +
441 used[feature] + " is not allowed.");
Thomas Lively82de51a2019-03-26 04:11:05 +0000442 }
443 }
444
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000445 // Validate the required and disallowed constraints for each file
Rui Ueyama136d27a2019-07-11 05:40:30 +0000446 for (ObjFile *file : symtab->objectFiles) {
447 StringRef fileName(file->getName());
448 SmallSet<std::string, 8> objectFeatures;
449 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
450 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000451 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000452 objectFeatures.insert(feature.Name);
453 if (disallowed.count(feature.Name))
454 error(Twine("Target feature '") + feature.Name + "' used in " +
455 fileName + " is disallowed by " + disallowed[feature.Name] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000456 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000457 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000458 for (auto &feature : required.keys()) {
459 if (!objectFeatures.count(feature))
460 error(Twine("Missing target feature '") + feature + "' in " + fileName +
461 ", required by " + required[feature] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000462 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000463 }
464 }
465}
466
Sam Cleggc94d3932017-11-17 18:14:09 +0000467void Writer::calculateImports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000468 for (Symbol *sym : symtab->getSymbols()) {
469 if (!sym->isUndefined())
Sam Clegg93102972018-02-23 05:08:53 +0000470 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000471 if (sym->isWeak() && !config->relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000472 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000473 if (!sym->isLive())
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000474 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000475 if (!sym->isUsedInRegularObj)
Sam Cleggc729c1b2018-05-30 18:07:52 +0000476 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000477 // We don't generate imports for data symbols. They however can be imported
478 // as GOT entries.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000479 if (isa<DataSymbol>(sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000480 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000481
Rui Ueyama136d27a2019-07-11 05:40:30 +0000482 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
483 out.importSec->addImport(sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000484 }
485}
486
Sam Cleggd3052d52018-01-18 23:40:49 +0000487void Writer::calculateExports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000488 if (config->relocatable)
Sam Clegg93102972018-02-23 05:08:53 +0000489 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000490
Rui Ueyama136d27a2019-07-11 05:40:30 +0000491 if (!config->relocatable && !config->importMemory)
492 out.exportSec->exports.push_back(
Sam Clegg8fcf0122019-05-21 09:13:09 +0000493 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000494
Rui Ueyama136d27a2019-07-11 05:40:30 +0000495 if (!config->relocatable && config->exportTable)
496 out.exportSec->exports.push_back(
497 WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000498
Rui Ueyama136d27a2019-07-11 05:40:30 +0000499 unsigned fakeGlobalIndex = out.importSec->getNumImportedGlobals() +
500 out.globalSec->inputGlobals.size();
Sam Cleggd6beb322018-05-10 18:10:34 +0000501
Rui Ueyama136d27a2019-07-11 05:40:30 +0000502 for (Symbol *sym : symtab->getSymbols()) {
503 if (!sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000504 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000505 if (!sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000506 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000507
Rui Ueyama136d27a2019-07-11 05:40:30 +0000508 StringRef name = sym->getName();
509 WasmExport export_;
510 if (auto *f = dyn_cast<DefinedFunction>(sym)) {
511 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
512 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000513 // TODO(sbc): Remove this check once to mutable global proposal is
514 // implement in all major browsers.
515 // See: https://github.com/WebAssembly/mutable-global
Rui Ueyama136d27a2019-07-11 05:40:30 +0000516 if (g->getGlobalType()->Mutable) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000517 // Only __stack_pointer and __tls_base should ever be create as mutable.
518 assert(g == WasmSym::stackPointer || g == WasmSym::tlsBase);
Sam Clegg177b4582018-06-07 01:27:07 +0000519 continue;
520 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000521 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
522 } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
523 export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000524 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000525 auto *d = cast<DefinedData>(sym);
526 out.globalSec->definedFakeGlobals.emplace_back(d);
527 export_ = {name, WASM_EXTERNAL_GLOBAL, fakeGlobalIndex++};
Sam Cleggd6beb322018-05-10 18:10:34 +0000528 }
529
Rui Ueyama136d27a2019-07-11 05:40:30 +0000530 LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
531 out.exportSec->exports.push_back(export_);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000532 }
Sam Clegg93102972018-02-23 05:08:53 +0000533}
534
Sam Clegg8fcf0122019-05-21 09:13:09 +0000535void Writer::populateSymtab() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000536 if (!config->relocatable && !config->emitRelocs)
Sam Clegg93102972018-02-23 05:08:53 +0000537 return;
538
Rui Ueyama136d27a2019-07-11 05:40:30 +0000539 for (Symbol *sym : symtab->getSymbols())
540 if (sym->isUsedInRegularObj && sym->isLive())
541 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000542
Rui Ueyama136d27a2019-07-11 05:40:30 +0000543 for (ObjFile *file : symtab->objectFiles) {
544 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
545 for (Symbol *sym : file->getSymbols())
546 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
547 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000548 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000549}
550
Sam Cleggc94d3932017-11-17 18:14:09 +0000551void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000552 // The output type section is the union of the following sets:
553 // 1. Any signature used in the TYPE relocation
554 // 2. The signatures of all imported functions
555 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000556 // 4. The signatures of all imported events
557 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000558
Rui Ueyama136d27a2019-07-11 05:40:30 +0000559 for (ObjFile *file : symtab->objectFiles) {
560 ArrayRef<WasmSignature> types = file->getWasmObj()->types();
561 for (uint32_t i = 0; i < types.size(); i++)
562 if (file->typeIsUsed[i])
563 file->typeMap[i] = out.typeSec->registerType(types[i]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000564 }
Sam Clegg50686852018-01-12 18:35:13 +0000565
Rui Ueyama136d27a2019-07-11 05:40:30 +0000566 for (const Symbol *sym : out.importSec->importedSymbols) {
567 if (auto *f = dyn_cast<FunctionSymbol>(sym))
568 out.typeSec->registerType(*f->signature);
569 else if (auto *e = dyn_cast<EventSymbol>(sym))
570 out.typeSec->registerType(*e->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000571 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000572
Rui Ueyama136d27a2019-07-11 05:40:30 +0000573 for (const InputFunction *f : out.functionSec->inputFunctions)
574 out.typeSec->registerType(f->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000575
Rui Ueyama136d27a2019-07-11 05:40:30 +0000576 for (const InputEvent *e : out.eventSec->inputEvents)
577 out.typeSec->registerType(e->signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000578}
579
Sam Clegg8fcf0122019-05-21 09:13:09 +0000580static void scanRelocations() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000581 for (ObjFile *file : symtab->objectFiles) {
582 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
583 for (InputChunk *chunk : file->functions)
584 scanRelocations(chunk);
585 for (InputChunk *chunk : file->segments)
586 scanRelocations(chunk);
587 for (auto &p : file->customSections)
588 scanRelocations(p);
Sam Clegg632c21792019-03-16 01:18:12 +0000589 }
590}
591
Sam Clegg8d146bb2018-01-09 23:56:44 +0000592void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000593 // Seal the import section, since other index spaces such as function and
594 // global are effected by the number of imports.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000595 out.importSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000596
Rui Ueyama136d27a2019-07-11 05:40:30 +0000597 for (InputFunction *func : symtab->syntheticFunctions)
598 out.functionSec->addFunction(func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000599
Rui Ueyama136d27a2019-07-11 05:40:30 +0000600 for (ObjFile *file : symtab->objectFiles) {
601 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
602 for (InputFunction *func : file->functions)
603 out.functionSec->addFunction(func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000604 }
605
Rui Ueyama136d27a2019-07-11 05:40:30 +0000606 for (InputGlobal *global : symtab->syntheticGlobals)
607 out.globalSec->addGlobal(global);
Sam Clegg93102972018-02-23 05:08:53 +0000608
Rui Ueyama136d27a2019-07-11 05:40:30 +0000609 for (ObjFile *file : symtab->objectFiles) {
610 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
611 for (InputGlobal *global : file->globals)
612 out.globalSec->addGlobal(global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000613 }
Heejin Ahne915a712018-12-08 06:17:43 +0000614
Rui Ueyama136d27a2019-07-11 05:40:30 +0000615 for (ObjFile *file : symtab->objectFiles) {
616 LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
617 for (InputEvent *event : file->events)
618 out.eventSec->addEvent(event);
Heejin Ahne915a712018-12-08 06:17:43 +0000619 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000620}
621
Rui Ueyama136d27a2019-07-11 05:40:30 +0000622static StringRef getOutputDataSegmentName(StringRef name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000623 // With PIC code we currently only support a single data segment since
624 // we only have a single __memory_base to use as our base address.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000625 if (config->isPic)
Sam Clegg51c2b992019-07-09 19:47:32 +0000626 return ".data";
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000627 // We only support one thread-local segment, so we must merge the segments
628 // despite --no-merge-data-segments.
629 // We also need to merge .tbss into .tdata so they share the same offsets.
630 if (name.startswith(".tdata") || name.startswith(".tbss"))
631 return ".tdata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000632 if (!config->mergeDataSegments)
633 return name;
634 if (name.startswith(".text."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000635 return ".text";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000636 if (name.startswith(".data."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000637 return ".data";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000638 if (name.startswith(".bss."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000639 return ".bss";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000640 if (name.startswith(".rodata."))
Sam Clegg57694c52018-08-08 18:02:55 +0000641 return ".rodata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000642 return name;
Sam Cleggc94d3932017-11-17 18:14:09 +0000643}
644
645void Writer::createOutputSegments() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000646 for (ObjFile *file : symtab->objectFiles) {
647 for (InputSegment *segment : file->segments) {
648 if (!segment->live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000649 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000650 StringRef name = getOutputDataSegmentName(segment->getName());
651 OutputSegment *&s = segmentMap[name];
652 if (s == nullptr) {
653 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
654 s = make<OutputSegment>(name, segments.size());
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000655 if (config->passiveSegments || name == ".tdata")
Rui Ueyama136d27a2019-07-11 05:40:30 +0000656 s->initFlags = WASM_SEGMENT_IS_PASSIVE;
657 segments.push_back(s);
Sam Cleggc94d3932017-11-17 18:14:09 +0000658 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000659 s->addInputSegment(segment);
660 LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000661 }
662 }
663}
664
Rui Ueyama136d27a2019-07-11 05:40:30 +0000665static void createFunction(DefinedFunction *func, StringRef bodyContent) {
666 std::string functionBody;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000667 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000668 raw_string_ostream os(functionBody);
669 writeUleb128(os, bodyContent.size(), "function size");
670 os << bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000671 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000672 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
673 cast<SyntheticFunction>(func->function)->setBody(body);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000674}
675
676void Writer::createInitMemoryFunction() {
677 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000678 std::string bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000679 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000680 raw_string_ostream os(bodyContent);
681 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000682
683 // initialize passive data segments
Rui Ueyama136d27a2019-07-11 05:40:30 +0000684 for (const OutputSegment *s : segments) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000685 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
Thomas Lively6004d9a2019-07-03 22:04:54 +0000686 // destination address
Rui Ueyama136d27a2019-07-11 05:40:30 +0000687 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
Thomas Lively26a6b952019-07-12 17:55:07 +0000688 writeSleb128(os, s->startVA, "destination address");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000689 // source segment offset
Rui Ueyama136d27a2019-07-11 05:40:30 +0000690 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
Thomas Lively26a6b952019-07-12 17:55:07 +0000691 writeSleb128(os, 0, "segment offset");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000692 // memory region size
Rui Ueyama136d27a2019-07-11 05:40:30 +0000693 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
Thomas Lively26a6b952019-07-12 17:55:07 +0000694 writeSleb128(os, s->size, "memory region size");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000695 // memory.init instruction
Rui Ueyama136d27a2019-07-11 05:40:30 +0000696 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
697 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
698 writeUleb128(os, s->index, "segment index immediate");
699 writeU8(os, 0, "memory index immediate");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000700 // data.drop instruction
Rui Ueyama136d27a2019-07-11 05:40:30 +0000701 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
702 writeUleb128(os, WASM_OPCODE_DATA_DROP, "DATA.DROP");
703 writeUleb128(os, s->index, "segment index immediate");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000704 }
705 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000706 writeU8(os, WASM_OPCODE_END, "END");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000707 }
708
Rui Ueyama136d27a2019-07-11 05:40:30 +0000709 createFunction(WasmSym::initMemory, bodyContent);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000710}
711
Sam Clegg09137be2019-04-04 18:40:51 +0000712// For -shared (PIC) output, we create create a synthetic function which will
713// apply any relocations to the data segments on startup. This function is
Thomas Lively6004d9a2019-07-03 22:04:54 +0000714// called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
715// before any of the constructors run.
Sam Clegg09137be2019-04-04 18:40:51 +0000716void Writer::createApplyRelocationsFunction() {
717 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
718 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000719 std::string bodyContent;
Sam Clegg09137be2019-04-04 18:40:51 +0000720 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000721 raw_string_ostream os(bodyContent);
722 writeUleb128(os, 0, "num locals");
723 for (const OutputSegment *seg : segments)
724 for (const InputSegment *inSeg : seg->inputSegments)
725 inSeg->generateRelocationCode(os);
726 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg09137be2019-04-04 18:40:51 +0000727 }
728
Rui Ueyama136d27a2019-07-11 05:40:30 +0000729 createFunction(WasmSym::applyRelocs, bodyContent);
Sam Clegg09137be2019-04-04 18:40:51 +0000730}
Sam Clegg50686852018-01-12 18:35:13 +0000731
732// Create synthetic "__wasm_call_ctors" function based on ctor functions
733// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000734void Writer::createCallCtorsFunction() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000735 if (!WasmSym::callCtors->isLive())
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000736 return;
737
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000738 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000739 std::string bodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000740 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000741 raw_string_ostream os(bodyContent);
742 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000743
Rui Ueyama136d27a2019-07-11 05:40:30 +0000744 if (config->passiveSegments) {
745 writeU8(os, WASM_OPCODE_CALL, "CALL");
746 writeUleb128(os, WasmSym::initMemory->getFunctionIndex(),
Thomas Lively6004d9a2019-07-03 22:04:54 +0000747 "function index");
748 }
749
Rui Ueyama136d27a2019-07-11 05:40:30 +0000750 if (config->isPic) {
751 writeU8(os, WASM_OPCODE_CALL, "CALL");
752 writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
Sam Clegg09137be2019-04-04 18:40:51 +0000753 "function index");
754 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000755
756 // Call constructors
Rui Ueyama136d27a2019-07-11 05:40:30 +0000757 for (const WasmInitEntry &f : initFunctions) {
758 writeU8(os, WASM_OPCODE_CALL, "CALL");
759 writeUleb128(os, f.sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000760 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000761 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000762 }
763
Rui Ueyama136d27a2019-07-11 05:40:30 +0000764 createFunction(WasmSym::callCtors, bodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000765}
766
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000767void Writer::createInitTLSFunction() {
768 if (!WasmSym::initTLS->isLive())
769 return;
770
771 std::string bodyContent;
772 {
773 raw_string_ostream os(bodyContent);
774
775 OutputSegment *tlsSeg = nullptr;
776 for (auto *seg : segments) {
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000777 if (seg->name == ".tdata") {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000778 tlsSeg = seg;
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000779 break;
780 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000781 }
782
783 writeUleb128(os, 0, "num locals");
784 if (tlsSeg) {
785 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
786 writeUleb128(os, 0, "local index");
787
788 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
789 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
790
791 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
792 writeUleb128(os, 0, "local index");
793
794 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
795 writeSleb128(os, 0, "segment offset");
796
797 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
798 writeSleb128(os, tlsSeg->size, "memory region size");
799
800 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
801 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
802 writeUleb128(os, tlsSeg->index, "segment index immediate");
803 writeU8(os, 0, "memory index immediate");
804 }
805 writeU8(os, WASM_OPCODE_END, "end function");
806 }
807
808 createFunction(WasmSym::initTLS, bodyContent);
809}
810
Sam Clegg50686852018-01-12 18:35:13 +0000811// Populate InitFunctions vector with init functions from all input objects.
812// This is then used either when creating the output linking section or to
813// synthesize the "__wasm_call_ctors" function.
814void Writer::calculateInitFunctions() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000815 if (!config->relocatable && !WasmSym::callCtors->isLive())
Sam Clegg61f13b32019-03-02 04:55:02 +0000816 return;
817
Rui Ueyama136d27a2019-07-11 05:40:30 +0000818 for (ObjFile *file : symtab->objectFiles) {
819 const WasmLinkingData &l = file->getWasmObj()->linkingData();
820 for (const WasmInitFunc &f : l.InitFunctions) {
821 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
Sam Cleggfd54fa52019-06-07 06:00:46 +0000822 // comdat exclusions can cause init functions be discarded.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000823 if (sym->isDiscarded())
Sam Cleggfd54fa52019-06-07 06:00:46 +0000824 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000825 assert(sym->isLive());
826 if (*sym->signature != WasmSignature{{}, {}})
827 error("invalid signature for init func: " + toString(*sym));
Sam Cleggaccad762019-07-17 18:43:36 +0000828 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000829 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000830 }
Sam Clegg50686852018-01-12 18:35:13 +0000831 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000832
Sam Clegg50686852018-01-12 18:35:13 +0000833 // Sort in order of priority (lowest first) so that they are called
834 // in the correct order.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000835 llvm::stable_sort(initFunctions,
836 [](const WasmInitEntry &l, const WasmInitEntry &r) {
837 return l.priority < r.priority;
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000838 });
Sam Clegg50686852018-01-12 18:35:13 +0000839}
840
Sam Clegg8fcf0122019-05-21 09:13:09 +0000841void Writer::createSyntheticSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000842 out.dylinkSec = make<DylinkSection>();
843 out.typeSec = make<TypeSection>();
844 out.importSec = make<ImportSection>();
845 out.functionSec = make<FunctionSection>();
846 out.tableSec = make<TableSection>();
847 out.memorySec = make<MemorySection>();
848 out.globalSec = make<GlobalSection>();
849 out.eventSec = make<EventSection>();
850 out.exportSec = make<ExportSection>();
851 out.elemSec = make<ElemSection>(tableBase);
852 out.dataCountSec = make<DataCountSection>(segments.size());
853 out.linkingSec = make<LinkingSection>(initFunctions, segments);
854 out.nameSec = make<NameSection>();
855 out.producersSec = make<ProducersSection>();
856 out.targetFeaturesSec = make<TargetFeaturesSection>();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000857}
858
Sam Cleggc94d3932017-11-17 18:14:09 +0000859void Writer::run() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000860 if (config->relocatable || config->isPic)
861 config->globalBase = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000862
Sam Cleggbfb75342018-11-15 00:37:21 +0000863 // For PIC code the table base is assigned dynamically by the loader.
864 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000865 if (!config->isPic)
866 tableBase = 1;
Sam Cleggbfb75342018-11-15 00:37:21 +0000867
Sam Clegg8fcf0122019-05-21 09:13:09 +0000868 log("-- createOutputSegments");
869 createOutputSegments();
870 log("-- createSyntheticSections");
871 createSyntheticSections();
872 log("-- populateProducers");
873 populateProducers();
874 log("-- populateTargetFeatures");
875 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +0000876 log("-- calculateImports");
877 calculateImports();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000878 log("-- layoutMemory");
879 layoutMemory();
880
Rui Ueyama136d27a2019-07-11 05:40:30 +0000881 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000882 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
883 // This has to be done after memory layout is performed.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000884 for (const OutputSegment *seg : segments)
885 addStartStopSymbols(seg);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000886 }
887
Sam Cleggb9889bb2019-05-23 09:41:03 +0000888 log("-- scanRelocations");
889 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000890 log("-- assignIndexes");
891 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000892 log("-- calculateInitFunctions");
893 calculateInitFunctions();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000894
Rui Ueyama136d27a2019-07-11 05:40:30 +0000895 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000896 // Create linker synthesized functions
Rui Ueyama136d27a2019-07-11 05:40:30 +0000897 if (config->passiveSegments)
Thomas Lively6004d9a2019-07-03 22:04:54 +0000898 createInitMemoryFunction();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000899 if (config->isPic)
Sam Clegg09137be2019-04-04 18:40:51 +0000900 createApplyRelocationsFunction();
901 createCallCtorsFunction();
902 }
Sam Clegg4bce63a2019-05-23 10:06:03 +0000903
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000904 if (config->sharedMemory && !config->shared)
905 createInitTLSFunction();
906
907 if (errorCount())
908 return;
909
Sam Clegg4bce63a2019-05-23 10:06:03 +0000910 log("-- calculateTypes");
911 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000912 log("-- calculateExports");
913 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +0000914 log("-- calculateCustomSections");
915 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000916 log("-- populateSymtab");
917 populateSymtab();
918 log("-- addSections");
919 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000920
Rui Ueyama136d27a2019-07-11 05:40:30 +0000921 if (errorHandler().verbose) {
922 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
923 log("Defined Globals : " + Twine(out.globalSec->inputGlobals.size()));
924 log("Defined Events : " + Twine(out.eventSec->inputEvents.size()));
Rui Ueyama7e296ad2019-07-10 09:10:01 +0000925 log("Function Imports : " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000926 Twine(out.importSec->getNumImportedFunctions()));
927 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals()));
928 log("Event Imports : " + Twine(out.importSec->getNumImportedEvents()));
929 for (ObjFile *file : symtab->objectFiles)
930 file->dumpInfo();
Sam Cleggc94d3932017-11-17 18:14:09 +0000931 }
932
Sam Cleggc94d3932017-11-17 18:14:09 +0000933 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000934 log("-- finalizeSections");
935 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000936
937 log("-- openFile");
938 openFile();
939 if (errorCount())
940 return;
941
942 writeHeader();
943
944 log("-- writeSections");
945 writeSections();
946 if (errorCount())
947 return;
948
Rui Ueyama136d27a2019-07-11 05:40:30 +0000949 if (Error e = buffer->commit())
950 fatal("failed to write the output file: " + toString(std::move(e)));
Sam Cleggc94d3932017-11-17 18:14:09 +0000951}
952
953// Open a result file.
954void Writer::openFile() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000955 log("writing: " + config->outputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000956
Rui Ueyama136d27a2019-07-11 05:40:30 +0000957 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
958 FileOutputBuffer::create(config->outputFile, fileSize,
Sam Cleggc94d3932017-11-17 18:14:09 +0000959 FileOutputBuffer::F_executable);
960
Rui Ueyama136d27a2019-07-11 05:40:30 +0000961 if (!bufferOrErr)
962 error("failed to open " + config->outputFile + ": " +
963 toString(bufferOrErr.takeError()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000964 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000965 buffer = std::move(*bufferOrErr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000966}
967
968void Writer::createHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000969 raw_string_ostream os(header);
970 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
971 writeU32(os, WasmVersion, "wasm version");
972 os.flush();
973 fileSize += header.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000974}
975
976void lld::wasm::writeResult() { Writer().run(); }