blob: 58d585bf0cb0f59d26c0bd23f5db4018f05087ae [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;
Sam Cleggc94d3932017-11-17 18:14:09 +000090
Rui Ueyama136d27a2019-07-11 05:40:30 +000091 std::vector<WasmInitEntry> initFunctions;
92 llvm::StringMap<std::vector<InputSection *>> customSectionMapping;
Sam Clegg80ba4382018-04-10 16:12:49 +000093
Sam Cleggc94d3932017-11-17 18:14:09 +000094 // Elements that are used to construct the final output
Rui Ueyama136d27a2019-07-11 05:40:30 +000095 std::string header;
96 std::vector<OutputSection *> outputSections;
Sam Cleggc94d3932017-11-17 18:14:09 +000097
Rui Ueyama136d27a2019-07-11 05:40:30 +000098 std::unique_ptr<FileOutputBuffer> buffer;
Sam Cleggc94d3932017-11-17 18:14:09 +000099
Rui Ueyama136d27a2019-07-11 05:40:30 +0000100 std::vector<OutputSegment *> segments;
101 llvm::SmallDenseMap<StringRef, OutputSegment *> segmentMap;
Sam Cleggc94d3932017-11-17 18:14:09 +0000102};
103
104} // anonymous namespace
105
Sam Cleggd177ab22018-05-04 23:14:42 +0000106void Writer::calculateCustomSections() {
107 log("calculateCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000108 bool stripDebug = config->stripDebug || config->stripAll;
109 for (ObjFile *file : symtab->objectFiles) {
110 for (InputSection *section : file->customSections) {
111 StringRef name = section->getName();
Sam Cleggd177ab22018-05-04 23:14:42 +0000112 // These custom sections are known the linker and synthesized rather than
113 // blindly copied
Rui Ueyama136d27a2019-07-11 05:40:30 +0000114 if (name == "linking" || name == "name" || name == "producers" ||
115 name == "target_features" || name.startswith("reloc."))
Sam Cleggd177ab22018-05-04 23:14:42 +0000116 continue;
117 // .. or it is a debug section
Rui Ueyama136d27a2019-07-11 05:40:30 +0000118 if (stripDebug && name.startswith(".debug_"))
Sam Cleggd177ab22018-05-04 23:14:42 +0000119 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000120 customSectionMapping[name].push_back(section);
Sam Cleggd177ab22018-05-04 23:14:42 +0000121 }
122 }
123}
124
Sam Clegg80ba4382018-04-10 16:12:49 +0000125void Writer::createCustomSections() {
126 log("createCustomSections");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000127 for (auto &pair : customSectionMapping) {
128 StringRef name = pair.first();
129 LLVM_DEBUG(dbgs() << "createCustomSection: " << name << "\n");
Sam Clegg8fcf0122019-05-21 09:13:09 +0000130
Rui Ueyama136d27a2019-07-11 05:40:30 +0000131 OutputSection *sec = make<CustomSection>(name, pair.second);
132 if (config->relocatable || config->emitRelocs) {
133 auto *sym = make<OutputSectionSymbol>(sec);
134 out.linkingSec->addToSymtab(sym);
135 sec->sectionSym = sym;
Sam Clegg8fcf0122019-05-21 09:13:09 +0000136 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000137 addSection(sec);
Sam Clegg80ba4382018-04-10 16:12:49 +0000138 }
139}
140
Sam Cleggd451da12017-12-19 19:56:27 +0000141// Create relocations sections in the final output.
Sam Cleggc94d3932017-11-17 18:14:09 +0000142// These are only created when relocatable output is requested.
143void Writer::createRelocSections() {
144 log("createRelocSections");
145 // Don't use iterator here since we are adding to OutputSection
Rui Ueyama136d27a2019-07-11 05:40:30 +0000146 size_t origSize = outputSections.size();
147 for (size_t i = 0; i < origSize; i++) {
148 LLVM_DEBUG(dbgs() << "check section " << i << "\n");
149 OutputSection *sec = outputSections[i];
Sam Clegg8fcf0122019-05-21 09:13:09 +0000150
151 // Count the number of needed sections.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000152 uint32_t count = sec->getNumRelocations();
153 if (!count)
Sam Cleggc94d3932017-11-17 18:14:09 +0000154 continue;
155
Rui Ueyama136d27a2019-07-11 05:40:30 +0000156 StringRef name;
157 if (sec->type == WASM_SEC_DATA)
158 name = "reloc.DATA";
159 else if (sec->type == WASM_SEC_CODE)
160 name = "reloc.CODE";
161 else if (sec->type == WASM_SEC_CUSTOM)
162 name = saver.save("reloc." + sec->name);
Sam Cleggc94d3932017-11-17 18:14:09 +0000163 else
Sam Cleggd177ab22018-05-04 23:14:42 +0000164 llvm_unreachable(
165 "relocations only supported for code, data, or custom sections");
Sam Cleggc94d3932017-11-17 18:14:09 +0000166
Rui Ueyama136d27a2019-07-11 05:40:30 +0000167 addSection(make<RelocSection>(name, sec));
Sam Cleggc94d3932017-11-17 18:14:09 +0000168 }
169}
170
Sam Clegg8fcf0122019-05-21 09:13:09 +0000171void Writer::populateProducers() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000172 for (ObjFile *file : symtab->objectFiles) {
173 const WasmProducerInfo &info = file->getWasmObj()->getProducerInfo();
174 out.producersSec->addInfo(info);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000175 }
176}
177
Sam Cleggc94d3932017-11-17 18:14:09 +0000178void Writer::writeHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000179 memcpy(buffer->getBufferStart(), header.data(), header.size());
Sam Cleggc94d3932017-11-17 18:14:09 +0000180}
181
182void Writer::writeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000183 uint8_t *buf = buffer->getBufferStart();
184 parallelForEach(outputSections, [buf](OutputSection *s) {
185 assert(s->isNeeded());
186 s->writeTo(buf);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000187 });
Sam Cleggc94d3932017-11-17 18:14:09 +0000188}
189
190// Fix the memory layout of the output binary. This assigns memory offsets
Sam Clegg49ed9262017-12-01 00:53:21 +0000191// to each of the input data sections as well as the explicit stack region.
Sam Clegga0f095e2018-05-03 17:21:53 +0000192// The default memory layout is as follows, from low to high.
193//
Fangrui Song33fdf822019-07-16 08:08:17 +0000194// - initialized data (starting at Config->globalBase)
Sam Cleggf0d433d2018-02-02 22:59:56 +0000195// - BSS data (not currently implemented in llvm)
196// - explicit stack (Config->ZStackSize)
197// - heap start / unallocated
Sam Clegga0f095e2018-05-03 17:21:53 +0000198//
199// The --stack-first option means that stack is placed before any static data.
Heejin Ahn4821ebf2018-08-29 21:03:16 +0000200// This can be useful since it means that stack overflow traps immediately
201// rather than overwriting global data, but also increases code size since all
202// static data loads and stores requires larger offsets.
Sam Cleggc94d3932017-11-17 18:14:09 +0000203void Writer::layoutMemory() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000204 uint32_t memoryPtr = 0;
Sam Clegga0f095e2018-05-03 17:21:53 +0000205
Rui Ueyama136d27a2019-07-11 05:40:30 +0000206 auto placeStack = [&]() {
Sam Cleggfd11ce32019-07-11 13:13:25 +0000207 if (config->relocatable || config->isPic)
Sam Clegga0f095e2018-05-03 17:21:53 +0000208 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000209 memoryPtr = alignTo(memoryPtr, stackAlignment);
210 if (config->zStackSize != alignTo(config->zStackSize, stackAlignment))
211 error("stack size must be " + Twine(stackAlignment) + "-byte aligned");
212 log("mem: stack size = " + Twine(config->zStackSize));
213 log("mem: stack base = " + Twine(memoryPtr));
214 memoryPtr += config->zStackSize;
215 auto *sp = cast<DefinedGlobal>(WasmSym::stackPointer);
216 sp->global->global.InitExpr.Value.Int32 = memoryPtr;
217 log("mem: stack top = " + Twine(memoryPtr));
Sam Clegga0f095e2018-05-03 17:21:53 +0000218 };
219
Rui Ueyama136d27a2019-07-11 05:40:30 +0000220 if (config->stackFirst) {
221 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000222 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000223 memoryPtr = config->globalBase;
224 log("mem: global base = " + Twine(config->globalBase));
Sam Clegga0f095e2018-05-03 17:21:53 +0000225 }
226
Rui Ueyama136d27a2019-07-11 05:40:30 +0000227 if (WasmSym::globalBase)
Sam Clegg7185a732019-08-13 17:02:02 +0000228 WasmSym::globalBase->setVirtualAddress(memoryPtr);
229 if (WasmSym::definedMemoryBase)
230 WasmSym::definedMemoryBase->setVirtualAddress(memoryPtr);
Guanzhong Chene15dc952019-06-26 20:12:33 +0000231
Rui Ueyama136d27a2019-07-11 05:40:30 +0000232 uint32_t dataStart = memoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000233
Sam Cleggf0d433d2018-02-02 22:59:56 +0000234 // Arbitrarily set __dso_handle handle to point to the start of the data
235 // segments.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000236 if (WasmSym::dsoHandle)
237 WasmSym::dsoHandle->setVirtualAddress(dataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000238
Rui Ueyama136d27a2019-07-11 05:40:30 +0000239 out.dylinkSec->memAlign = 0;
240 for (OutputSegment *seg : segments) {
241 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
242 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
243 seg->startVA = memoryPtr;
244 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
245 memoryPtr, seg->size, seg->alignment));
246 memoryPtr += seg->size;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000247
248 if (WasmSym::tlsSize && seg->name == ".tdata") {
249 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
250 tlsSize->global->global.InitExpr.Value.Int32 = seg->size;
Guanzhong Chen5204f762019-07-19 23:34:16 +0000251
252 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
253 tlsAlign->global->global.InitExpr.Value.Int32 = 1U << seg->alignment;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000254 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000255 }
256
Thomas Lively09768c52019-09-04 19:50:39 +0000257 // Make space for the memory initialization flag
258 if (WasmSym::initMemoryFlag) {
259 memoryPtr = alignTo(memoryPtr, 4);
260 WasmSym::initMemoryFlag->setVirtualAddress(memoryPtr);
261 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}",
262 "__wasm_init_memory_flag", memoryPtr, 4, 4));
263 memoryPtr += 4;
264 }
265
Sam Cleggf0d433d2018-02-02 22:59:56 +0000266 // TODO: Add .bss space here.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000267 if (WasmSym::dataEnd)
268 WasmSym::dataEnd->setVirtualAddress(memoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000269
Rui Ueyama136d27a2019-07-11 05:40:30 +0000270 log("mem: static data = " + Twine(memoryPtr - dataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000271
Rui Ueyama136d27a2019-07-11 05:40:30 +0000272 if (config->shared) {
273 out.dylinkSec->memSize = memoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000274 return;
275 }
276
Rui Ueyama136d27a2019-07-11 05:40:30 +0000277 if (!config->stackFirst)
278 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000279
280 // Set `__heap_base` to directly follow the end of the stack or global data.
281 // The fact that this comes last means that a malloc/brk implementation
282 // can grow the heap at runtime.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000283 log("mem: heap base = " + Twine(memoryPtr));
284 if (WasmSym::heapBase)
285 WasmSym::heapBase->setVirtualAddress(memoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000286
Rui Ueyama136d27a2019-07-11 05:40:30 +0000287 if (config->initialMemory != 0) {
288 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000289 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000290 if (memoryPtr > config->initialMemory)
291 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000292 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000293 memoryPtr = config->initialMemory;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000294 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000295 out.dylinkSec->memSize = memoryPtr;
296 out.memorySec->numMemoryPages =
297 alignTo(memoryPtr, WasmPageSize) / WasmPageSize;
298 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000299
Thomas Lively06391f32019-03-29 20:43:49 +0000300 // Check max if explicitly supplied or required by shared memory
Rui Ueyama136d27a2019-07-11 05:40:30 +0000301 if (config->maxMemory != 0 || config->sharedMemory) {
302 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000303 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000304 if (memoryPtr > config->maxMemory)
305 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
306 out.memorySec->maxMemoryPages = config->maxMemory / WasmPageSize;
307 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000308 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000309}
310
Rui Ueyama136d27a2019-07-11 05:40:30 +0000311void Writer::addSection(OutputSection *sec) {
312 if (!sec->isNeeded())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000313 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000314 log("addSection: " + toString(*sec));
315 sec->sectionIndex = outputSections.size();
316 outputSections.push_back(sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000317}
318
Sam Clegg4bce63a2019-05-23 10:06:03 +0000319// If a section name is valid as a C identifier (which is rare because of
320// the leading '.'), linkers are expected to define __start_<secname> and
321// __stop_<secname> symbols. They are at beginning and end of the section,
322// respectively. This is not requested by the ELF standard, but GNU ld and
323// gold provide the feature, and used by many programs.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000324static void addStartStopSymbols(const OutputSegment *seg) {
325 StringRef name = seg->name;
326 if (!isValidCIdentifier(name))
Sam Clegg4bce63a2019-05-23 10:06:03 +0000327 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000328 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
329 uint32_t start = seg->startVA;
330 uint32_t stop = start + seg->size;
331 symtab->addOptionalDataSymbol(saver.save("__start_" + name), start);
332 symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000333}
334
Sam Clegg8fcf0122019-05-21 09:13:09 +0000335void Writer::addSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000336 addSection(out.dylinkSec);
337 addSection(out.typeSec);
338 addSection(out.importSec);
339 addSection(out.functionSec);
340 addSection(out.tableSec);
341 addSection(out.memorySec);
342 addSection(out.globalSec);
343 addSection(out.eventSec);
344 addSection(out.exportSec);
Thomas Lively09768c52019-09-04 19:50:39 +0000345 addSection(out.startSec);
Rui Ueyama136d27a2019-07-11 05:40:30 +0000346 addSection(out.elemSec);
347 addSection(out.dataCountSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000348
Rui Ueyama136d27a2019-07-11 05:40:30 +0000349 addSection(make<CodeSection>(out.functionSec->inputFunctions));
350 addSection(make<DataSection>(segments));
Sam Clegg8fcf0122019-05-21 09:13:09 +0000351
Sam Clegg80ba4382018-04-10 16:12:49 +0000352 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000353
Rui Ueyama136d27a2019-07-11 05:40:30 +0000354 addSection(out.linkingSec);
355 if (config->emitRelocs || config->relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000356 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000357 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000358
Rui Ueyama136d27a2019-07-11 05:40:30 +0000359 addSection(out.nameSec);
360 addSection(out.producersSec);
361 addSection(out.targetFeaturesSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000362}
Sam Cleggc94d3932017-11-17 18:14:09 +0000363
Sam Clegg8fcf0122019-05-21 09:13:09 +0000364void Writer::finalizeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000365 for (OutputSection *s : outputSections) {
366 s->setOffset(fileSize);
367 s->finalizeContents();
368 fileSize += s->getSize();
Sam Cleggc94d3932017-11-17 18:14:09 +0000369 }
370}
371
Sam Clegg8fcf0122019-05-21 09:13:09 +0000372void Writer::populateTargetFeatures() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000373 StringMap<std::string> used;
374 StringMap<std::string> required;
375 StringMap<std::string> disallowed;
Thomas Lively09768c52019-09-04 19:50:39 +0000376 SmallSet<std::string, 8> &allowed = out.targetFeaturesSec->features;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000377 bool tlsUsed = false;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000378
Thomas Lively82de51a2019-03-26 04:11:05 +0000379 // Only infer used features if user did not specify features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000380 bool inferFeatures = !config->features.hasValue();
Thomas Lively82de51a2019-03-26 04:11:05 +0000381
Rui Ueyama136d27a2019-07-11 05:40:30 +0000382 if (!inferFeatures) {
Thomas Lively09768c52019-09-04 19:50:39 +0000383 auto &explicitFeatures = config->features.getValue();
384 allowed.insert(explicitFeatures.begin(), explicitFeatures.end());
Rui Ueyama136d27a2019-07-11 05:40:30 +0000385 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000386 return;
387 }
388
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000389 // Find the sets of used, required, and disallowed features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000390 for (ObjFile *file : symtab->objectFiles) {
391 StringRef fileName(file->getName());
392 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
393 switch (feature.Prefix) {
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000394 case WASM_FEATURE_PREFIX_USED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000395 used.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000396 break;
397 case WASM_FEATURE_PREFIX_REQUIRED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000398 used.insert({feature.Name, fileName});
399 required.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000400 break;
401 case WASM_FEATURE_PREFIX_DISALLOWED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000402 disallowed.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000403 break;
404 default:
405 error("Unrecognized feature policy prefix " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000406 std::to_string(feature.Prefix));
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000407 }
408 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000409
Thomas Lively09768c52019-09-04 19:50:39 +0000410 // Find TLS data segments
411 auto isTLS = [](InputSegment *segment) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000412 StringRef name = segment->getName();
Thomas Lively09768c52019-09-04 19:50:39 +0000413 return segment->live &&
414 (name.startswith(".tdata") || name.startswith(".tbss"));
415 };
416 tlsUsed = tlsUsed ||
417 std::any_of(file->segments.begin(), file->segments.end(), isTLS);
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000418 }
419
Rui Ueyama136d27a2019-07-11 05:40:30 +0000420 if (inferFeatures)
Thomas Lively09768c52019-09-04 19:50:39 +0000421 allowed.insert(used.keys().begin(), used.keys().end());
Thomas Lively82de51a2019-03-26 04:11:05 +0000422
Thomas Lively09768c52019-09-04 19:50:39 +0000423 if (allowed.count("atomics") && !config->sharedMemory) {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000424 if (inferFeatures)
425 error(Twine("'atomics' feature is used by ") + used["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000426 ", so --shared-memory must be used");
427 else
428 error("'atomics' feature is used, so --shared-memory must be used");
429 }
Thomas Lively06391f32019-03-29 20:43:49 +0000430
Rui Ueyama136d27a2019-07-11 05:40:30 +0000431 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000432 return;
433
Rui Ueyama136d27a2019-07-11 05:40:30 +0000434 if (disallowed.count("atomics") && config->sharedMemory)
435 error("'atomics' feature is disallowed by " + disallowed["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000436 ", so --shared-memory must not be used");
Thomas Lively06391f32019-03-29 20:43:49 +0000437
Thomas Lively09768c52019-09-04 19:50:39 +0000438 if (!allowed.count("atomics") && config->sharedMemory)
439 error("'atomics' feature must be used in order to use shared "
440 "memory");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000441
Thomas Lively09768c52019-09-04 19:50:39 +0000442 if (!allowed.count("bulk-memory") && config->sharedMemory)
443 error("'bulk-memory' feature must be used in order to use shared "
444 "memory");
445
446 if (!allowed.count("bulk-memory") && tlsUsed)
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000447 error("'bulk-memory' feature must be used in order to use thread-local "
448 "storage");
449
Thomas Lively82de51a2019-03-26 04:11:05 +0000450 // Validate that used features are allowed in output
Rui Ueyama136d27a2019-07-11 05:40:30 +0000451 if (!inferFeatures) {
452 for (auto &feature : used.keys()) {
Thomas Lively09768c52019-09-04 19:50:39 +0000453 if (!allowed.count(feature))
Rui Ueyama136d27a2019-07-11 05:40:30 +0000454 error(Twine("Target feature '") + feature + "' used by " +
455 used[feature] + " is not allowed.");
Thomas Lively82de51a2019-03-26 04:11:05 +0000456 }
457 }
458
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000459 // Validate the required and disallowed constraints for each file
Rui Ueyama136d27a2019-07-11 05:40:30 +0000460 for (ObjFile *file : symtab->objectFiles) {
461 StringRef fileName(file->getName());
462 SmallSet<std::string, 8> objectFeatures;
463 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
464 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000465 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000466 objectFeatures.insert(feature.Name);
467 if (disallowed.count(feature.Name))
468 error(Twine("Target feature '") + feature.Name + "' used in " +
469 fileName + " is disallowed by " + disallowed[feature.Name] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000470 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000471 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000472 for (auto &feature : required.keys()) {
473 if (!objectFeatures.count(feature))
474 error(Twine("Missing target feature '") + feature + "' in " + fileName +
475 ", required by " + required[feature] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000476 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000477 }
478 }
479}
480
Sam Cleggc94d3932017-11-17 18:14:09 +0000481void Writer::calculateImports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000482 for (Symbol *sym : symtab->getSymbols()) {
483 if (!sym->isUndefined())
Sam Clegg93102972018-02-23 05:08:53 +0000484 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000485 if (sym->isWeak() && !config->relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000486 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000487 if (!sym->isLive())
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000488 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000489 if (!sym->isUsedInRegularObj)
Sam Cleggc729c1b2018-05-30 18:07:52 +0000490 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000491 // We don't generate imports for data symbols. They however can be imported
492 // as GOT entries.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000493 if (isa<DataSymbol>(sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000494 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000495
Rui Ueyama136d27a2019-07-11 05:40:30 +0000496 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
497 out.importSec->addImport(sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000498 }
499}
500
Sam Cleggd3052d52018-01-18 23:40:49 +0000501void Writer::calculateExports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000502 if (config->relocatable)
Sam Clegg93102972018-02-23 05:08:53 +0000503 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000504
Rui Ueyama136d27a2019-07-11 05:40:30 +0000505 if (!config->relocatable && !config->importMemory)
506 out.exportSec->exports.push_back(
Sam Clegg8fcf0122019-05-21 09:13:09 +0000507 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000508
Rui Ueyama136d27a2019-07-11 05:40:30 +0000509 if (!config->relocatable && config->exportTable)
510 out.exportSec->exports.push_back(
511 WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000512
Rui Ueyama136d27a2019-07-11 05:40:30 +0000513 unsigned fakeGlobalIndex = out.importSec->getNumImportedGlobals() +
514 out.globalSec->inputGlobals.size();
Sam Cleggd6beb322018-05-10 18:10:34 +0000515
Rui Ueyama136d27a2019-07-11 05:40:30 +0000516 for (Symbol *sym : symtab->getSymbols()) {
517 if (!sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000518 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000519 if (!sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000520 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000521
Rui Ueyama136d27a2019-07-11 05:40:30 +0000522 StringRef name = sym->getName();
523 WasmExport export_;
524 if (auto *f = dyn_cast<DefinedFunction>(sym)) {
525 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
526 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000527 // TODO(sbc): Remove this check once to mutable global proposal is
528 // implement in all major browsers.
529 // See: https://github.com/WebAssembly/mutable-global
Rui Ueyama136d27a2019-07-11 05:40:30 +0000530 if (g->getGlobalType()->Mutable) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000531 // Only __stack_pointer and __tls_base should ever be create as mutable.
532 assert(g == WasmSym::stackPointer || g == WasmSym::tlsBase);
Sam Clegg177b4582018-06-07 01:27:07 +0000533 continue;
534 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000535 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
536 } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
537 export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000538 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000539 auto *d = cast<DefinedData>(sym);
540 out.globalSec->definedFakeGlobals.emplace_back(d);
541 export_ = {name, WASM_EXTERNAL_GLOBAL, fakeGlobalIndex++};
Sam Cleggd6beb322018-05-10 18:10:34 +0000542 }
543
Rui Ueyama136d27a2019-07-11 05:40:30 +0000544 LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
545 out.exportSec->exports.push_back(export_);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000546 }
Sam Clegg93102972018-02-23 05:08:53 +0000547}
548
Sam Clegg8fcf0122019-05-21 09:13:09 +0000549void Writer::populateSymtab() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000550 if (!config->relocatable && !config->emitRelocs)
Sam Clegg93102972018-02-23 05:08:53 +0000551 return;
552
Rui Ueyama136d27a2019-07-11 05:40:30 +0000553 for (Symbol *sym : symtab->getSymbols())
554 if (sym->isUsedInRegularObj && sym->isLive())
555 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000556
Rui Ueyama136d27a2019-07-11 05:40:30 +0000557 for (ObjFile *file : symtab->objectFiles) {
558 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
559 for (Symbol *sym : file->getSymbols())
560 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
561 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000562 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000563}
564
Sam Cleggc94d3932017-11-17 18:14:09 +0000565void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000566 // The output type section is the union of the following sets:
567 // 1. Any signature used in the TYPE relocation
568 // 2. The signatures of all imported functions
569 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000570 // 4. The signatures of all imported events
571 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000572
Rui Ueyama136d27a2019-07-11 05:40:30 +0000573 for (ObjFile *file : symtab->objectFiles) {
574 ArrayRef<WasmSignature> types = file->getWasmObj()->types();
575 for (uint32_t i = 0; i < types.size(); i++)
576 if (file->typeIsUsed[i])
577 file->typeMap[i] = out.typeSec->registerType(types[i]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000578 }
Sam Clegg50686852018-01-12 18:35:13 +0000579
Rui Ueyama136d27a2019-07-11 05:40:30 +0000580 for (const Symbol *sym : out.importSec->importedSymbols) {
581 if (auto *f = dyn_cast<FunctionSymbol>(sym))
582 out.typeSec->registerType(*f->signature);
583 else if (auto *e = dyn_cast<EventSymbol>(sym))
584 out.typeSec->registerType(*e->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000585 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000586
Rui Ueyama136d27a2019-07-11 05:40:30 +0000587 for (const InputFunction *f : out.functionSec->inputFunctions)
588 out.typeSec->registerType(f->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000589
Rui Ueyama136d27a2019-07-11 05:40:30 +0000590 for (const InputEvent *e : out.eventSec->inputEvents)
591 out.typeSec->registerType(e->signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000592}
593
Sam Clegg8fcf0122019-05-21 09:13:09 +0000594static void scanRelocations() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000595 for (ObjFile *file : symtab->objectFiles) {
596 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
597 for (InputChunk *chunk : file->functions)
598 scanRelocations(chunk);
599 for (InputChunk *chunk : file->segments)
600 scanRelocations(chunk);
601 for (auto &p : file->customSections)
602 scanRelocations(p);
Sam Clegg632c21792019-03-16 01:18:12 +0000603 }
604}
605
Sam Clegg8d146bb2018-01-09 23:56:44 +0000606void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000607 // Seal the import section, since other index spaces such as function and
608 // global are effected by the number of imports.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000609 out.importSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000610
Rui Ueyama136d27a2019-07-11 05:40:30 +0000611 for (InputFunction *func : symtab->syntheticFunctions)
612 out.functionSec->addFunction(func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000613
Rui Ueyama136d27a2019-07-11 05:40:30 +0000614 for (ObjFile *file : symtab->objectFiles) {
615 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
616 for (InputFunction *func : file->functions)
617 out.functionSec->addFunction(func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000618 }
619
Rui Ueyama136d27a2019-07-11 05:40:30 +0000620 for (InputGlobal *global : symtab->syntheticGlobals)
621 out.globalSec->addGlobal(global);
Sam Clegg93102972018-02-23 05:08:53 +0000622
Rui Ueyama136d27a2019-07-11 05:40:30 +0000623 for (ObjFile *file : symtab->objectFiles) {
624 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
625 for (InputGlobal *global : file->globals)
626 out.globalSec->addGlobal(global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000627 }
Heejin Ahne915a712018-12-08 06:17:43 +0000628
Rui Ueyama136d27a2019-07-11 05:40:30 +0000629 for (ObjFile *file : symtab->objectFiles) {
630 LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
631 for (InputEvent *event : file->events)
632 out.eventSec->addEvent(event);
Heejin Ahne915a712018-12-08 06:17:43 +0000633 }
Sam Clegg7185a732019-08-13 17:02:02 +0000634
635 out.globalSec->assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +0000636}
637
Rui Ueyama136d27a2019-07-11 05:40:30 +0000638static StringRef getOutputDataSegmentName(StringRef name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000639 // With PIC code we currently only support a single data segment since
640 // we only have a single __memory_base to use as our base address.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000641 if (config->isPic)
Sam Clegg51c2b992019-07-09 19:47:32 +0000642 return ".data";
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000643 // We only support one thread-local segment, so we must merge the segments
644 // despite --no-merge-data-segments.
645 // We also need to merge .tbss into .tdata so they share the same offsets.
646 if (name.startswith(".tdata") || name.startswith(".tbss"))
647 return ".tdata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000648 if (!config->mergeDataSegments)
649 return name;
650 if (name.startswith(".text."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000651 return ".text";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000652 if (name.startswith(".data."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000653 return ".data";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000654 if (name.startswith(".bss."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000655 return ".bss";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000656 if (name.startswith(".rodata."))
Sam Clegg57694c52018-08-08 18:02:55 +0000657 return ".rodata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000658 return name;
Sam Cleggc94d3932017-11-17 18:14:09 +0000659}
660
661void Writer::createOutputSegments() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000662 for (ObjFile *file : symtab->objectFiles) {
663 for (InputSegment *segment : file->segments) {
664 if (!segment->live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000665 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000666 StringRef name = getOutputDataSegmentName(segment->getName());
667 OutputSegment *&s = segmentMap[name];
668 if (s == nullptr) {
669 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
670 s = make<OutputSegment>(name, segments.size());
Thomas Lively09768c52019-09-04 19:50:39 +0000671 if (config->sharedMemory || name == ".tdata")
Rui Ueyama136d27a2019-07-11 05:40:30 +0000672 s->initFlags = WASM_SEGMENT_IS_PASSIVE;
673 segments.push_back(s);
Sam Cleggc94d3932017-11-17 18:14:09 +0000674 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000675 s->addInputSegment(segment);
676 LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000677 }
678 }
679}
680
Rui Ueyama136d27a2019-07-11 05:40:30 +0000681static void createFunction(DefinedFunction *func, StringRef bodyContent) {
682 std::string functionBody;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000683 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000684 raw_string_ostream os(functionBody);
685 writeUleb128(os, bodyContent.size(), "function size");
686 os << bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000687 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000688 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
689 cast<SyntheticFunction>(func->function)->setBody(body);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000690}
691
692void Writer::createInitMemoryFunction() {
693 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
Thomas Lively09768c52019-09-04 19:50:39 +0000694 assert(WasmSym::initMemoryFlag);
695 uint32_t flagAddress = WasmSym::initMemoryFlag->getVirtualAddress();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000696 std::string bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000697 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000698 raw_string_ostream os(bodyContent);
699 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000700
Thomas Lively09768c52019-09-04 19:50:39 +0000701 if (segments.size()) {
702 // Initialize memory in a thread-safe manner. The thread that successfully
703 // increments the flag from 0 to 1 is is responsible for performing the
704 // memory initialization. Other threads go sleep on the flag until the
705 // first thread finishing initializing memory, increments the flag to 2,
706 // and wakes all the other threads. Once the flag has been set to 2,
707 // subsequently started threads will skip the sleep. All threads
708 // unconditionally drop their passive data segments once memory has been
709 // initialized. The generated code is as follows:
710 //
711 // (func $__wasm_init_memory
712 // (if
713 // (i32.atomic.rmw.cmpxchg align=2 offset=0
714 // (i32.const $__init_memory_flag)
715 // (i32.const 0)
716 // (i32.const 1)
717 // )
718 // (then
719 // (drop
720 // (i32.atomic.wait align=2 offset=0
721 // (i32.const $__init_memory_flag)
722 // (i32.const 1)
723 // (i32.const -1)
724 // )
725 // )
726 // )
727 // (else
728 // ( ... initialize data segments ... )
729 // (i32.atomic.store align=2 offset=0
730 // (i32.const $__init_memory_flag)
731 // (i32.const 2)
732 // )
733 // (drop
734 // (i32.atomic.notify align=2 offset=0
735 // (i32.const $__init_memory_flag)
736 // (i32.const -1u)
737 // )
738 // )
739 // )
740 // )
741 // ( ... drop data segments ... )
742 // )
743
744 // Atomically check whether this is the main thread.
745 writeI32Const(os, flagAddress, "flag address");
746 writeI32Const(os, 0, "expected flag value");
747 writeI32Const(os, 1, "flag value");
748 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
749 writeUleb128(os, WASM_OPCODE_I32_RMW_CMPXCHG, "i32.atomic.rmw.cmpxchg");
750 writeMemArg(os, 2, 0);
751 writeU8(os, WASM_OPCODE_IF, "IF");
752 writeU8(os, WASM_TYPE_NORESULT, "blocktype");
753
754 // Did not increment 0, so wait for main thread to initialize memory
755 writeI32Const(os, flagAddress, "flag address");
756 writeI32Const(os, 1, "expected flag value");
757 writeI64Const(os, -1, "timeout");
758 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
759 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_WAIT, "i32.atomic.wait");
760 writeMemArg(os, 2, 0);
761 writeU8(os, WASM_OPCODE_DROP, "drop");
762
763 writeU8(os, WASM_OPCODE_ELSE, "ELSE");
764
765 // Did increment 0, so conditionally initialize passive data segments
766 for (const OutputSegment *s : segments) {
767 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
768 // destination address
769 writeI32Const(os, s->startVA, "destination address");
770 // source segment offset
771 writeI32Const(os, 0, "segment offset");
772 // memory region size
773 writeI32Const(os, s->size, "memory region size");
774 // memory.init instruction
775 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
776 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "memory.init");
777 writeUleb128(os, s->index, "segment index immediate");
778 writeU8(os, 0, "memory index immediate");
779 }
780 }
781
782 // Set flag to 2 to mark end of initialization
783 writeI32Const(os, flagAddress, "flag address");
784 writeI32Const(os, 2, "flag value");
785 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
786 writeUleb128(os, WASM_OPCODE_I32_ATOMIC_STORE, "i32.atomic.store");
787 writeMemArg(os, 2, 0);
788
789 // Notify any waiters that memory initialization is complete
790 writeI32Const(os, flagAddress, "flag address");
791 writeI32Const(os, -1, "number of waiters");
792 writeU8(os, WASM_OPCODE_ATOMICS_PREFIX, "atomics prefix");
793 writeUleb128(os, WASM_OPCODE_ATOMIC_NOTIFY, "atomic.notify");
794 writeMemArg(os, 2, 0);
795 writeU8(os, WASM_OPCODE_DROP, "drop");
796
797 writeU8(os, WASM_OPCODE_END, "END");
798
799 // Unconditionally drop passive data segments
800 for (const OutputSegment *s : segments) {
801 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
802 // data.drop instruction
803 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
804 writeUleb128(os, WASM_OPCODE_DATA_DROP, "data.drop");
805 writeUleb128(os, s->index, "segment index immediate");
806 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000807 }
808 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000809 writeU8(os, WASM_OPCODE_END, "END");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000810 }
811
Rui Ueyama136d27a2019-07-11 05:40:30 +0000812 createFunction(WasmSym::initMemory, bodyContent);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000813}
814
Sam Clegg09137be2019-04-04 18:40:51 +0000815// For -shared (PIC) output, we create create a synthetic function which will
816// apply any relocations to the data segments on startup. This function is
Thomas Lively6004d9a2019-07-03 22:04:54 +0000817// called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
818// before any of the constructors run.
Sam Clegg09137be2019-04-04 18:40:51 +0000819void Writer::createApplyRelocationsFunction() {
820 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
821 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000822 std::string bodyContent;
Sam Clegg09137be2019-04-04 18:40:51 +0000823 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000824 raw_string_ostream os(bodyContent);
825 writeUleb128(os, 0, "num locals");
826 for (const OutputSegment *seg : segments)
827 for (const InputSegment *inSeg : seg->inputSegments)
828 inSeg->generateRelocationCode(os);
829 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg09137be2019-04-04 18:40:51 +0000830 }
831
Rui Ueyama136d27a2019-07-11 05:40:30 +0000832 createFunction(WasmSym::applyRelocs, bodyContent);
Sam Clegg09137be2019-04-04 18:40:51 +0000833}
Sam Clegg50686852018-01-12 18:35:13 +0000834
835// Create synthetic "__wasm_call_ctors" function based on ctor functions
836// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000837void Writer::createCallCtorsFunction() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000838 if (!WasmSym::callCtors->isLive())
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000839 return;
840
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000841 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000842 std::string bodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000843 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000844 raw_string_ostream os(bodyContent);
845 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000846
Rui Ueyama136d27a2019-07-11 05:40:30 +0000847 if (config->isPic) {
848 writeU8(os, WASM_OPCODE_CALL, "CALL");
849 writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
Sam Clegg09137be2019-04-04 18:40:51 +0000850 "function index");
851 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000852
853 // Call constructors
Rui Ueyama136d27a2019-07-11 05:40:30 +0000854 for (const WasmInitEntry &f : initFunctions) {
855 writeU8(os, WASM_OPCODE_CALL, "CALL");
856 writeUleb128(os, f.sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000857 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000858 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000859 }
860
Rui Ueyama136d27a2019-07-11 05:40:30 +0000861 createFunction(WasmSym::callCtors, bodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000862}
863
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000864void Writer::createInitTLSFunction() {
865 if (!WasmSym::initTLS->isLive())
866 return;
867
868 std::string bodyContent;
869 {
870 raw_string_ostream os(bodyContent);
871
872 OutputSegment *tlsSeg = nullptr;
873 for (auto *seg : segments) {
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000874 if (seg->name == ".tdata") {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000875 tlsSeg = seg;
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000876 break;
877 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000878 }
879
880 writeUleb128(os, 0, "num locals");
881 if (tlsSeg) {
882 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
883 writeUleb128(os, 0, "local index");
884
885 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
886 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
887
888 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
889 writeUleb128(os, 0, "local index");
890
Thomas Lively09768c52019-09-04 19:50:39 +0000891 writeI32Const(os, 0, "segment offset");
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000892
Thomas Lively09768c52019-09-04 19:50:39 +0000893 writeI32Const(os, tlsSeg->size, "memory region size");
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000894
895 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
896 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
897 writeUleb128(os, tlsSeg->index, "segment index immediate");
898 writeU8(os, 0, "memory index immediate");
899 }
900 writeU8(os, WASM_OPCODE_END, "end function");
901 }
902
903 createFunction(WasmSym::initTLS, bodyContent);
904}
905
Sam Clegg50686852018-01-12 18:35:13 +0000906// Populate InitFunctions vector with init functions from all input objects.
907// This is then used either when creating the output linking section or to
908// synthesize the "__wasm_call_ctors" function.
909void Writer::calculateInitFunctions() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000910 if (!config->relocatable && !WasmSym::callCtors->isLive())
Sam Clegg61f13b32019-03-02 04:55:02 +0000911 return;
912
Rui Ueyama136d27a2019-07-11 05:40:30 +0000913 for (ObjFile *file : symtab->objectFiles) {
914 const WasmLinkingData &l = file->getWasmObj()->linkingData();
915 for (const WasmInitFunc &f : l.InitFunctions) {
916 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
Sam Cleggfd54fa52019-06-07 06:00:46 +0000917 // comdat exclusions can cause init functions be discarded.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000918 if (sym->isDiscarded())
Sam Cleggfd54fa52019-06-07 06:00:46 +0000919 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000920 assert(sym->isLive());
921 if (*sym->signature != WasmSignature{{}, {}})
922 error("invalid signature for init func: " + toString(*sym));
Sam Cleggaccad762019-07-17 18:43:36 +0000923 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000924 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000925 }
Sam Clegg50686852018-01-12 18:35:13 +0000926 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000927
Sam Clegg50686852018-01-12 18:35:13 +0000928 // Sort in order of priority (lowest first) so that they are called
929 // in the correct order.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000930 llvm::stable_sort(initFunctions,
931 [](const WasmInitEntry &l, const WasmInitEntry &r) {
932 return l.priority < r.priority;
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000933 });
Sam Clegg50686852018-01-12 18:35:13 +0000934}
935
Sam Clegg8fcf0122019-05-21 09:13:09 +0000936void Writer::createSyntheticSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000937 out.dylinkSec = make<DylinkSection>();
938 out.typeSec = make<TypeSection>();
939 out.importSec = make<ImportSection>();
940 out.functionSec = make<FunctionSection>();
941 out.tableSec = make<TableSection>();
942 out.memorySec = make<MemorySection>();
943 out.globalSec = make<GlobalSection>();
944 out.eventSec = make<EventSection>();
945 out.exportSec = make<ExportSection>();
Thomas Lively09768c52019-09-04 19:50:39 +0000946 out.startSec = make<StartSection>(segments.size());
Sam Clegg1a1df722019-08-27 04:19:34 +0000947 out.elemSec = make<ElemSection>();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000948 out.dataCountSec = make<DataCountSection>(segments.size());
949 out.linkingSec = make<LinkingSection>(initFunctions, segments);
950 out.nameSec = make<NameSection>();
951 out.producersSec = make<ProducersSection>();
952 out.targetFeaturesSec = make<TargetFeaturesSection>();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000953}
954
Sam Cleggc94d3932017-11-17 18:14:09 +0000955void Writer::run() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000956 if (config->relocatable || config->isPic)
957 config->globalBase = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000958
Sam Cleggbfb75342018-11-15 00:37:21 +0000959 // For PIC code the table base is assigned dynamically by the loader.
960 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
Sam Clegg7185a732019-08-13 17:02:02 +0000961 if (!config->isPic) {
Sam Clegg1a1df722019-08-27 04:19:34 +0000962 config->tableBase = 1;
Sam Clegg7185a732019-08-13 17:02:02 +0000963 if (WasmSym::definedTableBase)
Sam Clegg1a1df722019-08-27 04:19:34 +0000964 WasmSym::definedTableBase->setVirtualAddress(config->tableBase);
Sam Clegg7185a732019-08-13 17:02:02 +0000965 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000966
Sam Clegg8fcf0122019-05-21 09:13:09 +0000967 log("-- createOutputSegments");
968 createOutputSegments();
969 log("-- createSyntheticSections");
970 createSyntheticSections();
971 log("-- populateProducers");
972 populateProducers();
973 log("-- populateTargetFeatures");
974 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +0000975 log("-- calculateImports");
976 calculateImports();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000977 log("-- layoutMemory");
978 layoutMemory();
979
Rui Ueyama136d27a2019-07-11 05:40:30 +0000980 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000981 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
982 // This has to be done after memory layout is performed.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000983 for (const OutputSegment *seg : segments)
984 addStartStopSymbols(seg);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000985 }
986
Sam Cleggb9889bb2019-05-23 09:41:03 +0000987 log("-- scanRelocations");
988 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000989 log("-- assignIndexes");
990 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000991 log("-- calculateInitFunctions");
992 calculateInitFunctions();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000993
Rui Ueyama136d27a2019-07-11 05:40:30 +0000994 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000995 // Create linker synthesized functions
Thomas Lively09768c52019-09-04 19:50:39 +0000996 if (config->sharedMemory)
Thomas Lively6004d9a2019-07-03 22:04:54 +0000997 createInitMemoryFunction();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000998 if (config->isPic)
Sam Clegg09137be2019-04-04 18:40:51 +0000999 createApplyRelocationsFunction();
1000 createCallCtorsFunction();
1001 }
Sam Clegg4bce63a2019-05-23 10:06:03 +00001002
Guanzhong Chen0cb776e2019-08-06 20:09:04 +00001003 if (!config->relocatable && config->sharedMemory && !config->shared)
Guanzhong Chen42bba4b2019-07-16 22:00:45 +00001004 createInitTLSFunction();
1005
1006 if (errorCount())
1007 return;
1008
Sam Clegg4bce63a2019-05-23 10:06:03 +00001009 log("-- calculateTypes");
1010 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +00001011 log("-- calculateExports");
1012 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +00001013 log("-- calculateCustomSections");
1014 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +00001015 log("-- populateSymtab");
1016 populateSymtab();
1017 log("-- addSections");
1018 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +00001019
Rui Ueyama136d27a2019-07-11 05:40:30 +00001020 if (errorHandler().verbose) {
1021 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
1022 log("Defined Globals : " + Twine(out.globalSec->inputGlobals.size()));
1023 log("Defined Events : " + Twine(out.eventSec->inputEvents.size()));
Rui Ueyama7e296ad2019-07-10 09:10:01 +00001024 log("Function Imports : " +
Rui Ueyama136d27a2019-07-11 05:40:30 +00001025 Twine(out.importSec->getNumImportedFunctions()));
1026 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals()));
1027 log("Event Imports : " + Twine(out.importSec->getNumImportedEvents()));
1028 for (ObjFile *file : symtab->objectFiles)
1029 file->dumpInfo();
Sam Cleggc94d3932017-11-17 18:14:09 +00001030 }
1031
Sam Cleggc94d3932017-11-17 18:14:09 +00001032 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +00001033 log("-- finalizeSections");
1034 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +00001035
1036 log("-- openFile");
1037 openFile();
1038 if (errorCount())
1039 return;
1040
1041 writeHeader();
1042
1043 log("-- writeSections");
1044 writeSections();
1045 if (errorCount())
1046 return;
1047
Rui Ueyama136d27a2019-07-11 05:40:30 +00001048 if (Error e = buffer->commit())
1049 fatal("failed to write the output file: " + toString(std::move(e)));
Sam Cleggc94d3932017-11-17 18:14:09 +00001050}
1051
1052// Open a result file.
1053void Writer::openFile() {
Rui Ueyama136d27a2019-07-11 05:40:30 +00001054 log("writing: " + config->outputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +00001055
Rui Ueyama136d27a2019-07-11 05:40:30 +00001056 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
1057 FileOutputBuffer::create(config->outputFile, fileSize,
Sam Cleggc94d3932017-11-17 18:14:09 +00001058 FileOutputBuffer::F_executable);
1059
Rui Ueyama136d27a2019-07-11 05:40:30 +00001060 if (!bufferOrErr)
1061 error("failed to open " + config->outputFile + ": " +
1062 toString(bufferOrErr.takeError()));
Sam Cleggc94d3932017-11-17 18:14:09 +00001063 else
Rui Ueyama136d27a2019-07-11 05:40:30 +00001064 buffer = std::move(*bufferOrErr);
Sam Cleggc94d3932017-11-17 18:14:09 +00001065}
1066
1067void Writer::createHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +00001068 raw_string_ostream os(header);
1069 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
1070 writeU32(os, WasmVersion, "wasm version");
1071 os.flush();
1072 fileSize += header.size();
Sam Cleggc94d3932017-11-17 18:14:09 +00001073}
1074
1075void lld::wasm::writeResult() { Writer().run(); }