blob: 5a3b6290c0134091871520ea87e3d669676be2be [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)
Sam Clegg7185a732019-08-13 17:02:02 +0000229 WasmSym::globalBase->setVirtualAddress(memoryPtr);
230 if (WasmSym::definedMemoryBase)
231 WasmSym::definedMemoryBase->setVirtualAddress(memoryPtr);
Guanzhong Chene15dc952019-06-26 20:12:33 +0000232
Rui Ueyama136d27a2019-07-11 05:40:30 +0000233 uint32_t dataStart = memoryPtr;
Sam Clegga0f095e2018-05-03 17:21:53 +0000234
Sam Cleggf0d433d2018-02-02 22:59:56 +0000235 // Arbitrarily set __dso_handle handle to point to the start of the data
236 // segments.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000237 if (WasmSym::dsoHandle)
238 WasmSym::dsoHandle->setVirtualAddress(dataStart);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000239
Rui Ueyama136d27a2019-07-11 05:40:30 +0000240 out.dylinkSec->memAlign = 0;
241 for (OutputSegment *seg : segments) {
242 out.dylinkSec->memAlign = std::max(out.dylinkSec->memAlign, seg->alignment);
243 memoryPtr = alignTo(memoryPtr, 1ULL << seg->alignment);
244 seg->startVA = memoryPtr;
245 log(formatv("mem: {0,-15} offset={1,-8} size={2,-8} align={3}", seg->name,
246 memoryPtr, seg->size, seg->alignment));
247 memoryPtr += seg->size;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000248
249 if (WasmSym::tlsSize && seg->name == ".tdata") {
250 auto *tlsSize = cast<DefinedGlobal>(WasmSym::tlsSize);
251 tlsSize->global->global.InitExpr.Value.Int32 = seg->size;
Guanzhong Chen5204f762019-07-19 23:34:16 +0000252
253 auto *tlsAlign = cast<DefinedGlobal>(WasmSym::tlsAlign);
254 tlsAlign->global->global.InitExpr.Value.Int32 = 1U << seg->alignment;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000255 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000256 }
257
Sam Cleggf0d433d2018-02-02 22:59:56 +0000258 // TODO: Add .bss space here.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000259 if (WasmSym::dataEnd)
260 WasmSym::dataEnd->setVirtualAddress(memoryPtr);
Sam Cleggf0d433d2018-02-02 22:59:56 +0000261
Rui Ueyama136d27a2019-07-11 05:40:30 +0000262 log("mem: static data = " + Twine(memoryPtr - dataStart));
Sam Cleggc94d3932017-11-17 18:14:09 +0000263
Rui Ueyama136d27a2019-07-11 05:40:30 +0000264 if (config->shared) {
265 out.dylinkSec->memSize = memoryPtr;
Sam Clegg2dad4e22018-11-15 18:15:54 +0000266 return;
267 }
268
Rui Ueyama136d27a2019-07-11 05:40:30 +0000269 if (!config->stackFirst)
270 placeStack();
Sam Clegga0f095e2018-05-03 17:21:53 +0000271
272 // Set `__heap_base` to directly follow the end of the stack or global data.
273 // The fact that this comes last means that a malloc/brk implementation
274 // can grow the heap at runtime.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000275 log("mem: heap base = " + Twine(memoryPtr));
276 if (WasmSym::heapBase)
277 WasmSym::heapBase->setVirtualAddress(memoryPtr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000278
Rui Ueyama136d27a2019-07-11 05:40:30 +0000279 if (config->initialMemory != 0) {
280 if (config->initialMemory != alignTo(config->initialMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000281 error("initial memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000282 if (memoryPtr > config->initialMemory)
283 error("initial memory too small, " + Twine(memoryPtr) + " bytes needed");
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000284 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000285 memoryPtr = config->initialMemory;
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000286 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000287 out.dylinkSec->memSize = memoryPtr;
288 out.memorySec->numMemoryPages =
289 alignTo(memoryPtr, WasmPageSize) / WasmPageSize;
290 log("mem: total pages = " + Twine(out.memorySec->numMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000291
Thomas Lively06391f32019-03-29 20:43:49 +0000292 // Check max if explicitly supplied or required by shared memory
Rui Ueyama136d27a2019-07-11 05:40:30 +0000293 if (config->maxMemory != 0 || config->sharedMemory) {
294 if (config->maxMemory != alignTo(config->maxMemory, WasmPageSize))
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000295 error("maximum memory must be " + Twine(WasmPageSize) + "-byte aligned");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000296 if (memoryPtr > config->maxMemory)
297 error("maximum memory too small, " + Twine(memoryPtr) + " bytes needed");
298 out.memorySec->maxMemoryPages = config->maxMemory / WasmPageSize;
299 log("mem: max pages = " + Twine(out.memorySec->maxMemoryPages));
Nicholas Wilson2eb39c12018-03-14 13:53:58 +0000300 }
Sam Cleggc94d3932017-11-17 18:14:09 +0000301}
302
Rui Ueyama136d27a2019-07-11 05:40:30 +0000303void Writer::addSection(OutputSection *sec) {
304 if (!sec->isNeeded())
Sam Clegg8fcf0122019-05-21 09:13:09 +0000305 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000306 log("addSection: " + toString(*sec));
307 sec->sectionIndex = outputSections.size();
308 outputSections.push_back(sec);
Sam Cleggc94d3932017-11-17 18:14:09 +0000309}
310
Sam Clegg4bce63a2019-05-23 10:06:03 +0000311// If a section name is valid as a C identifier (which is rare because of
312// the leading '.'), linkers are expected to define __start_<secname> and
313// __stop_<secname> symbols. They are at beginning and end of the section,
314// respectively. This is not requested by the ELF standard, but GNU ld and
315// gold provide the feature, and used by many programs.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000316static void addStartStopSymbols(const OutputSegment *seg) {
317 StringRef name = seg->name;
318 if (!isValidCIdentifier(name))
Sam Clegg4bce63a2019-05-23 10:06:03 +0000319 return;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000320 LLVM_DEBUG(dbgs() << "addStartStopSymbols: " << name << "\n");
321 uint32_t start = seg->startVA;
322 uint32_t stop = start + seg->size;
323 symtab->addOptionalDataSymbol(saver.save("__start_" + name), start);
324 symtab->addOptionalDataSymbol(saver.save("__stop_" + name), stop);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000325}
326
Sam Clegg8fcf0122019-05-21 09:13:09 +0000327void Writer::addSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000328 addSection(out.dylinkSec);
329 addSection(out.typeSec);
330 addSection(out.importSec);
331 addSection(out.functionSec);
332 addSection(out.tableSec);
333 addSection(out.memorySec);
334 addSection(out.globalSec);
335 addSection(out.eventSec);
336 addSection(out.exportSec);
337 addSection(out.elemSec);
338 addSection(out.dataCountSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000339
Rui Ueyama136d27a2019-07-11 05:40:30 +0000340 addSection(make<CodeSection>(out.functionSec->inputFunctions));
341 addSection(make<DataSection>(segments));
Sam Clegg8fcf0122019-05-21 09:13:09 +0000342
Sam Clegg80ba4382018-04-10 16:12:49 +0000343 createCustomSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000344
Rui Ueyama136d27a2019-07-11 05:40:30 +0000345 addSection(out.linkingSec);
346 if (config->emitRelocs || config->relocatable) {
Nicholas Wilson94d3b162018-03-05 12:33:58 +0000347 createRelocSections();
Sam Clegg99eb42c2018-02-27 23:58:03 +0000348 }
Thomas Lively2a0868f2019-01-17 02:29:41 +0000349
Rui Ueyama136d27a2019-07-11 05:40:30 +0000350 addSection(out.nameSec);
351 addSection(out.producersSec);
352 addSection(out.targetFeaturesSec);
Sam Clegg8fcf0122019-05-21 09:13:09 +0000353}
Sam Cleggc94d3932017-11-17 18:14:09 +0000354
Sam Clegg8fcf0122019-05-21 09:13:09 +0000355void Writer::finalizeSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000356 for (OutputSection *s : outputSections) {
357 s->setOffset(fileSize);
358 s->finalizeContents();
359 fileSize += s->getSize();
Sam Cleggc94d3932017-11-17 18:14:09 +0000360 }
361}
362
Sam Clegg8fcf0122019-05-21 09:13:09 +0000363void Writer::populateTargetFeatures() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000364 StringMap<std::string> used;
365 StringMap<std::string> required;
366 StringMap<std::string> disallowed;
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000367 bool tlsUsed = false;
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000368
Thomas Lively82de51a2019-03-26 04:11:05 +0000369 // Only infer used features if user did not specify features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000370 bool inferFeatures = !config->features.hasValue();
Thomas Lively82de51a2019-03-26 04:11:05 +0000371
Rui Ueyama136d27a2019-07-11 05:40:30 +0000372 if (!inferFeatures) {
373 for (auto &feature : config->features.getValue())
374 out.targetFeaturesSec->features.insert(feature);
Thomas Lively82de51a2019-03-26 04:11:05 +0000375 // No need to read or check features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000376 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000377 return;
378 }
379
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000380 // Find the sets of used, required, and disallowed features
Rui Ueyama136d27a2019-07-11 05:40:30 +0000381 for (ObjFile *file : symtab->objectFiles) {
382 StringRef fileName(file->getName());
383 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
384 switch (feature.Prefix) {
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000385 case WASM_FEATURE_PREFIX_USED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000386 used.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000387 break;
388 case WASM_FEATURE_PREFIX_REQUIRED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000389 used.insert({feature.Name, fileName});
390 required.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000391 break;
392 case WASM_FEATURE_PREFIX_DISALLOWED:
Rui Ueyama136d27a2019-07-11 05:40:30 +0000393 disallowed.insert({feature.Name, fileName});
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000394 break;
395 default:
396 error("Unrecognized feature policy prefix " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000397 std::to_string(feature.Prefix));
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000398 }
399 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000400
401 for (InputSegment *segment : file->segments) {
402 if (!segment->live)
403 continue;
404 StringRef name = segment->getName();
405 if (name.startswith(".tdata") || name.startswith(".tbss"))
406 tlsUsed = true;
407 }
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000408 }
409
Rui Ueyama136d27a2019-07-11 05:40:30 +0000410 if (inferFeatures)
411 out.targetFeaturesSec->features.insert(used.keys().begin(),
412 used.keys().end());
Thomas Lively82de51a2019-03-26 04:11:05 +0000413
Rui Ueyama136d27a2019-07-11 05:40:30 +0000414 if (out.targetFeaturesSec->features.count("atomics") &&
415 !config->sharedMemory) {
416 if (inferFeatures)
417 error(Twine("'atomics' feature is used by ") + used["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000418 ", so --shared-memory must be used");
419 else
420 error("'atomics' feature is used, so --shared-memory must be used");
421 }
Thomas Lively06391f32019-03-29 20:43:49 +0000422
Rui Ueyama136d27a2019-07-11 05:40:30 +0000423 if (!config->checkFeatures)
Thomas Lively82de51a2019-03-26 04:11:05 +0000424 return;
425
Rui Ueyama136d27a2019-07-11 05:40:30 +0000426 if (disallowed.count("atomics") && config->sharedMemory)
427 error("'atomics' feature is disallowed by " + disallowed["atomics"] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000428 ", so --shared-memory must not be used");
Thomas Lively06391f32019-03-29 20:43:49 +0000429
Rui Ueyama136d27a2019-07-11 05:40:30 +0000430 if (!used.count("bulk-memory") && config->passiveSegments)
Thomas Lively6004d9a2019-07-03 22:04:54 +0000431 error("'bulk-memory' feature must be used in order to emit passive "
432 "segments");
433
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000434 if (!used.count("bulk-memory") && tlsUsed)
435 error("'bulk-memory' feature must be used in order to use thread-local "
436 "storage");
437
Thomas Lively82de51a2019-03-26 04:11:05 +0000438 // Validate that used features are allowed in output
Rui Ueyama136d27a2019-07-11 05:40:30 +0000439 if (!inferFeatures) {
440 for (auto &feature : used.keys()) {
441 if (!out.targetFeaturesSec->features.count(feature))
442 error(Twine("Target feature '") + feature + "' used by " +
443 used[feature] + " is not allowed.");
Thomas Lively82de51a2019-03-26 04:11:05 +0000444 }
445 }
446
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000447 // Validate the required and disallowed constraints for each file
Rui Ueyama136d27a2019-07-11 05:40:30 +0000448 for (ObjFile *file : symtab->objectFiles) {
449 StringRef fileName(file->getName());
450 SmallSet<std::string, 8> objectFeatures;
451 for (auto &feature : file->getWasmObj()->getTargetFeatures()) {
452 if (feature.Prefix == WASM_FEATURE_PREFIX_DISALLOWED)
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000453 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000454 objectFeatures.insert(feature.Name);
455 if (disallowed.count(feature.Name))
456 error(Twine("Target feature '") + feature.Name + "' used in " +
457 fileName + " is disallowed by " + disallowed[feature.Name] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000458 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000459 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000460 for (auto &feature : required.keys()) {
461 if (!objectFeatures.count(feature))
462 error(Twine("Missing target feature '") + feature + "' in " + fileName +
463 ", required by " + required[feature] +
Thomas Lively86e73f52019-05-30 21:57:23 +0000464 ". Use --no-check-features to suppress.");
Thomas Livelyf6f4f842019-03-20 20:26:45 +0000465 }
466 }
467}
468
Sam Cleggc94d3932017-11-17 18:14:09 +0000469void Writer::calculateImports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000470 for (Symbol *sym : symtab->getSymbols()) {
471 if (!sym->isUndefined())
Sam Clegg93102972018-02-23 05:08:53 +0000472 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000473 if (sym->isWeak() && !config->relocatable)
Sam Clegg574d7ce2017-12-15 19:23:49 +0000474 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000475 if (!sym->isLive())
Nicholas Wilsona1e299f2018-04-20 17:18:06 +0000476 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000477 if (!sym->isUsedInRegularObj)
Sam Cleggc729c1b2018-05-30 18:07:52 +0000478 continue;
Sam Clegg492f7522019-03-26 19:46:15 +0000479 // We don't generate imports for data symbols. They however can be imported
480 // as GOT entries.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000481 if (isa<DataSymbol>(sym))
Sam Cleggd425d6b2019-03-12 21:53:23 +0000482 continue;
Sam Cleggc94d3932017-11-17 18:14:09 +0000483
Rui Ueyama136d27a2019-07-11 05:40:30 +0000484 LLVM_DEBUG(dbgs() << "import: " << sym->getName() << "\n");
485 out.importSec->addImport(sym);
Sam Cleggc94d3932017-11-17 18:14:09 +0000486 }
487}
488
Sam Cleggd3052d52018-01-18 23:40:49 +0000489void Writer::calculateExports() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000490 if (config->relocatable)
Sam Clegg93102972018-02-23 05:08:53 +0000491 return;
Sam Cleggf0d433d2018-02-02 22:59:56 +0000492
Rui Ueyama136d27a2019-07-11 05:40:30 +0000493 if (!config->relocatable && !config->importMemory)
494 out.exportSec->exports.push_back(
Sam Clegg8fcf0122019-05-21 09:13:09 +0000495 WasmExport{"memory", WASM_EXTERNAL_MEMORY, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000496
Rui Ueyama136d27a2019-07-11 05:40:30 +0000497 if (!config->relocatable && config->exportTable)
498 out.exportSec->exports.push_back(
499 WasmExport{functionTableName, WASM_EXTERNAL_TABLE, 0});
Sam Cleggd6beb322018-05-10 18:10:34 +0000500
Rui Ueyama136d27a2019-07-11 05:40:30 +0000501 unsigned fakeGlobalIndex = out.importSec->getNumImportedGlobals() +
502 out.globalSec->inputGlobals.size();
Sam Cleggd6beb322018-05-10 18:10:34 +0000503
Rui Ueyama136d27a2019-07-11 05:40:30 +0000504 for (Symbol *sym : symtab->getSymbols()) {
505 if (!sym->isExported())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000506 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000507 if (!sym->isLive())
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000508 continue;
Sam Clegg93102972018-02-23 05:08:53 +0000509
Rui Ueyama136d27a2019-07-11 05:40:30 +0000510 StringRef name = sym->getName();
511 WasmExport export_;
512 if (auto *f = dyn_cast<DefinedFunction>(sym)) {
513 export_ = {name, WASM_EXTERNAL_FUNCTION, f->getFunctionIndex()};
514 } else if (auto *g = dyn_cast<DefinedGlobal>(sym)) {
Sam Clegg177b4582018-06-07 01:27:07 +0000515 // TODO(sbc): Remove this check once to mutable global proposal is
516 // implement in all major browsers.
517 // See: https://github.com/WebAssembly/mutable-global
Rui Ueyama136d27a2019-07-11 05:40:30 +0000518 if (g->getGlobalType()->Mutable) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000519 // Only __stack_pointer and __tls_base should ever be create as mutable.
520 assert(g == WasmSym::stackPointer || g == WasmSym::tlsBase);
Sam Clegg177b4582018-06-07 01:27:07 +0000521 continue;
522 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000523 export_ = {name, WASM_EXTERNAL_GLOBAL, g->getGlobalIndex()};
524 } else if (auto *e = dyn_cast<DefinedEvent>(sym)) {
525 export_ = {name, WASM_EXTERNAL_EVENT, e->getEventIndex()};
Sam Cleggd6beb322018-05-10 18:10:34 +0000526 } else {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000527 auto *d = cast<DefinedData>(sym);
528 out.globalSec->definedFakeGlobals.emplace_back(d);
529 export_ = {name, WASM_EXTERNAL_GLOBAL, fakeGlobalIndex++};
Sam Cleggd6beb322018-05-10 18:10:34 +0000530 }
531
Rui Ueyama136d27a2019-07-11 05:40:30 +0000532 LLVM_DEBUG(dbgs() << "Export: " << name << "\n");
533 out.exportSec->exports.push_back(export_);
Nicholas Wilson4cdf5b82018-03-01 09:38:02 +0000534 }
Sam Clegg93102972018-02-23 05:08:53 +0000535}
536
Sam Clegg8fcf0122019-05-21 09:13:09 +0000537void Writer::populateSymtab() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000538 if (!config->relocatable && !config->emitRelocs)
Sam Clegg93102972018-02-23 05:08:53 +0000539 return;
540
Rui Ueyama136d27a2019-07-11 05:40:30 +0000541 for (Symbol *sym : symtab->getSymbols())
542 if (sym->isUsedInRegularObj && sym->isLive())
543 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000544
Rui Ueyama136d27a2019-07-11 05:40:30 +0000545 for (ObjFile *file : symtab->objectFiles) {
546 LLVM_DEBUG(dbgs() << "Local symtab entries: " << file->getName() << "\n");
547 for (Symbol *sym : file->getSymbols())
548 if (sym->isLocal() && !isa<SectionSymbol>(sym) && sym->isLive())
549 out.linkingSec->addToSymtab(sym);
Sam Clegg89e4dcb2019-01-30 18:55:15 +0000550 }
Sam Cleggd3052d52018-01-18 23:40:49 +0000551}
552
Sam Cleggc94d3932017-11-17 18:14:09 +0000553void Writer::calculateTypes() {
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000554 // The output type section is the union of the following sets:
555 // 1. Any signature used in the TYPE relocation
556 // 2. The signatures of all imported functions
557 // 3. The signatures of all defined functions
Heejin Ahne915a712018-12-08 06:17:43 +0000558 // 4. The signatures of all imported events
559 // 5. The signatures of all defined events
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000560
Rui Ueyama136d27a2019-07-11 05:40:30 +0000561 for (ObjFile *file : symtab->objectFiles) {
562 ArrayRef<WasmSignature> types = file->getWasmObj()->types();
563 for (uint32_t i = 0; i < types.size(); i++)
564 if (file->typeIsUsed[i])
565 file->typeMap[i] = out.typeSec->registerType(types[i]);
Sam Cleggc94d3932017-11-17 18:14:09 +0000566 }
Sam Clegg50686852018-01-12 18:35:13 +0000567
Rui Ueyama136d27a2019-07-11 05:40:30 +0000568 for (const Symbol *sym : out.importSec->importedSymbols) {
569 if (auto *f = dyn_cast<FunctionSymbol>(sym))
570 out.typeSec->registerType(*f->signature);
571 else if (auto *e = dyn_cast<EventSymbol>(sym))
572 out.typeSec->registerType(*e->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000573 }
Sam Clegg8f6d2de2018-01-31 23:48:14 +0000574
Rui Ueyama136d27a2019-07-11 05:40:30 +0000575 for (const InputFunction *f : out.functionSec->inputFunctions)
576 out.typeSec->registerType(f->signature);
Heejin Ahne915a712018-12-08 06:17:43 +0000577
Rui Ueyama136d27a2019-07-11 05:40:30 +0000578 for (const InputEvent *e : out.eventSec->inputEvents)
579 out.typeSec->registerType(e->signature);
Sam Cleggc94d3932017-11-17 18:14:09 +0000580}
581
Sam Clegg8fcf0122019-05-21 09:13:09 +0000582static void scanRelocations() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000583 for (ObjFile *file : symtab->objectFiles) {
584 LLVM_DEBUG(dbgs() << "scanRelocations: " << file->getName() << "\n");
585 for (InputChunk *chunk : file->functions)
586 scanRelocations(chunk);
587 for (InputChunk *chunk : file->segments)
588 scanRelocations(chunk);
589 for (auto &p : file->customSections)
590 scanRelocations(p);
Sam Clegg632c21792019-03-16 01:18:12 +0000591 }
592}
593
Sam Clegg8d146bb2018-01-09 23:56:44 +0000594void Writer::assignIndexes() {
Sam Cleggb9889bb2019-05-23 09:41:03 +0000595 // Seal the import section, since other index spaces such as function and
596 // global are effected by the number of imports.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000597 out.importSec->seal();
Nicholas Wilsonebda41f2018-03-09 16:43:05 +0000598
Rui Ueyama136d27a2019-07-11 05:40:30 +0000599 for (InputFunction *func : symtab->syntheticFunctions)
600 out.functionSec->addFunction(func);
Nicholas Wilson5639da82018-03-12 15:44:07 +0000601
Rui Ueyama136d27a2019-07-11 05:40:30 +0000602 for (ObjFile *file : symtab->objectFiles) {
603 LLVM_DEBUG(dbgs() << "Functions: " << file->getName() << "\n");
604 for (InputFunction *func : file->functions)
605 out.functionSec->addFunction(func);
Sam Clegg8d146bb2018-01-09 23:56:44 +0000606 }
607
Rui Ueyama136d27a2019-07-11 05:40:30 +0000608 for (InputGlobal *global : symtab->syntheticGlobals)
609 out.globalSec->addGlobal(global);
Sam Clegg93102972018-02-23 05:08:53 +0000610
Rui Ueyama136d27a2019-07-11 05:40:30 +0000611 for (ObjFile *file : symtab->objectFiles) {
612 LLVM_DEBUG(dbgs() << "Globals: " << file->getName() << "\n");
613 for (InputGlobal *global : file->globals)
614 out.globalSec->addGlobal(global);
Sam Cleggc94d3932017-11-17 18:14:09 +0000615 }
Heejin Ahne915a712018-12-08 06:17:43 +0000616
Rui Ueyama136d27a2019-07-11 05:40:30 +0000617 for (ObjFile *file : symtab->objectFiles) {
618 LLVM_DEBUG(dbgs() << "Events: " << file->getName() << "\n");
619 for (InputEvent *event : file->events)
620 out.eventSec->addEvent(event);
Heejin Ahne915a712018-12-08 06:17:43 +0000621 }
Sam Clegg7185a732019-08-13 17:02:02 +0000622
623 out.globalSec->assignIndexes();
Sam Cleggc94d3932017-11-17 18:14:09 +0000624}
625
Rui Ueyama136d27a2019-07-11 05:40:30 +0000626static StringRef getOutputDataSegmentName(StringRef name) {
Sam Cleggbfb75342018-11-15 00:37:21 +0000627 // With PIC code we currently only support a single data segment since
628 // we only have a single __memory_base to use as our base address.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000629 if (config->isPic)
Sam Clegg51c2b992019-07-09 19:47:32 +0000630 return ".data";
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000631 // We only support one thread-local segment, so we must merge the segments
632 // despite --no-merge-data-segments.
633 // We also need to merge .tbss into .tdata so they share the same offsets.
634 if (name.startswith(".tdata") || name.startswith(".tbss"))
635 return ".tdata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000636 if (!config->mergeDataSegments)
637 return name;
638 if (name.startswith(".text."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000639 return ".text";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000640 if (name.startswith(".data."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000641 return ".data";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000642 if (name.startswith(".bss."))
Rui Ueyama4764b572018-02-28 00:57:28 +0000643 return ".bss";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000644 if (name.startswith(".rodata."))
Sam Clegg57694c52018-08-08 18:02:55 +0000645 return ".rodata";
Rui Ueyama136d27a2019-07-11 05:40:30 +0000646 return name;
Sam Cleggc94d3932017-11-17 18:14:09 +0000647}
648
649void Writer::createOutputSegments() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000650 for (ObjFile *file : symtab->objectFiles) {
651 for (InputSegment *segment : file->segments) {
652 if (!segment->live)
Sam Clegge0f6fcd2018-01-12 22:25:17 +0000653 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000654 StringRef name = getOutputDataSegmentName(segment->getName());
655 OutputSegment *&s = segmentMap[name];
656 if (s == nullptr) {
657 LLVM_DEBUG(dbgs() << "new segment: " << name << "\n");
658 s = make<OutputSegment>(name, segments.size());
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000659 if (config->passiveSegments || name == ".tdata")
Rui Ueyama136d27a2019-07-11 05:40:30 +0000660 s->initFlags = WASM_SEGMENT_IS_PASSIVE;
661 segments.push_back(s);
Sam Cleggc94d3932017-11-17 18:14:09 +0000662 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000663 s->addInputSegment(segment);
664 LLVM_DEBUG(dbgs() << "added data: " << name << ": " << s->size << "\n");
Sam Cleggc94d3932017-11-17 18:14:09 +0000665 }
666 }
667}
668
Rui Ueyama136d27a2019-07-11 05:40:30 +0000669static void createFunction(DefinedFunction *func, StringRef bodyContent) {
670 std::string functionBody;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000671 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000672 raw_string_ostream os(functionBody);
673 writeUleb128(os, bodyContent.size(), "function size");
674 os << bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000675 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000676 ArrayRef<uint8_t> body = arrayRefFromStringRef(saver.save(functionBody));
677 cast<SyntheticFunction>(func->function)->setBody(body);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000678}
679
680void Writer::createInitMemoryFunction() {
681 LLVM_DEBUG(dbgs() << "createInitMemoryFunction\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000682 std::string bodyContent;
Thomas Lively6004d9a2019-07-03 22:04:54 +0000683 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000684 raw_string_ostream os(bodyContent);
685 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000686
687 // initialize passive data segments
Rui Ueyama136d27a2019-07-11 05:40:30 +0000688 for (const OutputSegment *s : segments) {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000689 if (s->initFlags & WASM_SEGMENT_IS_PASSIVE && s->name != ".tdata") {
Thomas Lively6004d9a2019-07-03 22:04:54 +0000690 // destination address
Rui Ueyama136d27a2019-07-11 05:40:30 +0000691 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
Thomas Lively26a6b952019-07-12 17:55:07 +0000692 writeSleb128(os, s->startVA, "destination address");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000693 // source segment offset
Rui Ueyama136d27a2019-07-11 05:40:30 +0000694 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
Thomas Lively26a6b952019-07-12 17:55:07 +0000695 writeSleb128(os, 0, "segment offset");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000696 // memory region size
Rui Ueyama136d27a2019-07-11 05:40:30 +0000697 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
Thomas Lively26a6b952019-07-12 17:55:07 +0000698 writeSleb128(os, s->size, "memory region size");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000699 // memory.init instruction
Rui Ueyama136d27a2019-07-11 05:40:30 +0000700 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
701 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
702 writeUleb128(os, s->index, "segment index immediate");
703 writeU8(os, 0, "memory index immediate");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000704 // data.drop instruction
Rui Ueyama136d27a2019-07-11 05:40:30 +0000705 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
706 writeUleb128(os, WASM_OPCODE_DATA_DROP, "DATA.DROP");
707 writeUleb128(os, s->index, "segment index immediate");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000708 }
709 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000710 writeU8(os, WASM_OPCODE_END, "END");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000711 }
712
Rui Ueyama136d27a2019-07-11 05:40:30 +0000713 createFunction(WasmSym::initMemory, bodyContent);
Thomas Lively6004d9a2019-07-03 22:04:54 +0000714}
715
Sam Clegg09137be2019-04-04 18:40:51 +0000716// For -shared (PIC) output, we create create a synthetic function which will
717// apply any relocations to the data segments on startup. This function is
Thomas Lively6004d9a2019-07-03 22:04:54 +0000718// called __wasm_apply_relocs and is added at the beginning of __wasm_call_ctors
719// before any of the constructors run.
Sam Clegg09137be2019-04-04 18:40:51 +0000720void Writer::createApplyRelocationsFunction() {
721 LLVM_DEBUG(dbgs() << "createApplyRelocationsFunction\n");
722 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000723 std::string bodyContent;
Sam Clegg09137be2019-04-04 18:40:51 +0000724 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000725 raw_string_ostream os(bodyContent);
726 writeUleb128(os, 0, "num locals");
727 for (const OutputSegment *seg : segments)
728 for (const InputSegment *inSeg : seg->inputSegments)
729 inSeg->generateRelocationCode(os);
730 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg09137be2019-04-04 18:40:51 +0000731 }
732
Rui Ueyama136d27a2019-07-11 05:40:30 +0000733 createFunction(WasmSym::applyRelocs, bodyContent);
Sam Clegg09137be2019-04-04 18:40:51 +0000734}
Sam Clegg50686852018-01-12 18:35:13 +0000735
736// Create synthetic "__wasm_call_ctors" function based on ctor functions
737// in input object.
Sam Clegg09137be2019-04-04 18:40:51 +0000738void Writer::createCallCtorsFunction() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000739 if (!WasmSym::callCtors->isLive())
Sam Clegg0e6b42f2019-03-01 22:35:47 +0000740 return;
741
Nicholas Wilsonf6dbc2e2018-03-02 14:48:50 +0000742 // First write the body's contents to a string.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000743 std::string bodyContent;
Sam Clegg50686852018-01-12 18:35:13 +0000744 {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000745 raw_string_ostream os(bodyContent);
746 writeUleb128(os, 0, "num locals");
Thomas Lively6004d9a2019-07-03 22:04:54 +0000747
Rui Ueyama136d27a2019-07-11 05:40:30 +0000748 if (config->passiveSegments) {
749 writeU8(os, WASM_OPCODE_CALL, "CALL");
750 writeUleb128(os, WasmSym::initMemory->getFunctionIndex(),
Thomas Lively6004d9a2019-07-03 22:04:54 +0000751 "function index");
752 }
753
Rui Ueyama136d27a2019-07-11 05:40:30 +0000754 if (config->isPic) {
755 writeU8(os, WASM_OPCODE_CALL, "CALL");
756 writeUleb128(os, WasmSym::applyRelocs->getFunctionIndex(),
Sam Clegg09137be2019-04-04 18:40:51 +0000757 "function index");
758 }
Thomas Lively6004d9a2019-07-03 22:04:54 +0000759
760 // Call constructors
Rui Ueyama136d27a2019-07-11 05:40:30 +0000761 for (const WasmInitEntry &f : initFunctions) {
762 writeU8(os, WASM_OPCODE_CALL, "CALL");
763 writeUleb128(os, f.sym->getFunctionIndex(), "function index");
Sam Clegg50686852018-01-12 18:35:13 +0000764 }
Rui Ueyama136d27a2019-07-11 05:40:30 +0000765 writeU8(os, WASM_OPCODE_END, "END");
Sam Clegg50686852018-01-12 18:35:13 +0000766 }
767
Rui Ueyama136d27a2019-07-11 05:40:30 +0000768 createFunction(WasmSym::callCtors, bodyContent);
Sam Clegg50686852018-01-12 18:35:13 +0000769}
770
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000771void Writer::createInitTLSFunction() {
772 if (!WasmSym::initTLS->isLive())
773 return;
774
775 std::string bodyContent;
776 {
777 raw_string_ostream os(bodyContent);
778
779 OutputSegment *tlsSeg = nullptr;
780 for (auto *seg : segments) {
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000781 if (seg->name == ".tdata") {
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000782 tlsSeg = seg;
Guanzhong Chen21aafc22019-07-18 21:18:24 +0000783 break;
784 }
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000785 }
786
787 writeUleb128(os, 0, "num locals");
788 if (tlsSeg) {
789 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
790 writeUleb128(os, 0, "local index");
791
792 writeU8(os, WASM_OPCODE_GLOBAL_SET, "global.set");
793 writeUleb128(os, WasmSym::tlsBase->getGlobalIndex(), "global index");
794
795 writeU8(os, WASM_OPCODE_LOCAL_GET, "local.get");
796 writeUleb128(os, 0, "local index");
797
798 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
799 writeSleb128(os, 0, "segment offset");
800
801 writeU8(os, WASM_OPCODE_I32_CONST, "i32.const");
802 writeSleb128(os, tlsSeg->size, "memory region size");
803
804 writeU8(os, WASM_OPCODE_MISC_PREFIX, "bulk-memory prefix");
805 writeUleb128(os, WASM_OPCODE_MEMORY_INIT, "MEMORY.INIT");
806 writeUleb128(os, tlsSeg->index, "segment index immediate");
807 writeU8(os, 0, "memory index immediate");
808 }
809 writeU8(os, WASM_OPCODE_END, "end function");
810 }
811
812 createFunction(WasmSym::initTLS, bodyContent);
813}
814
Sam Clegg50686852018-01-12 18:35:13 +0000815// Populate InitFunctions vector with init functions from all input objects.
816// This is then used either when creating the output linking section or to
817// synthesize the "__wasm_call_ctors" function.
818void Writer::calculateInitFunctions() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000819 if (!config->relocatable && !WasmSym::callCtors->isLive())
Sam Clegg61f13b32019-03-02 04:55:02 +0000820 return;
821
Rui Ueyama136d27a2019-07-11 05:40:30 +0000822 for (ObjFile *file : symtab->objectFiles) {
823 const WasmLinkingData &l = file->getWasmObj()->linkingData();
824 for (const WasmInitFunc &f : l.InitFunctions) {
825 FunctionSymbol *sym = file->getFunctionSymbol(f.Symbol);
Sam Cleggfd54fa52019-06-07 06:00:46 +0000826 // comdat exclusions can cause init functions be discarded.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000827 if (sym->isDiscarded())
Sam Cleggfd54fa52019-06-07 06:00:46 +0000828 continue;
Rui Ueyama136d27a2019-07-11 05:40:30 +0000829 assert(sym->isLive());
830 if (*sym->signature != WasmSignature{{}, {}})
831 error("invalid signature for init func: " + toString(*sym));
Sam Cleggaccad762019-07-17 18:43:36 +0000832 LLVM_DEBUG(dbgs() << "initFunctions: " << toString(*sym) << "\n");
Rui Ueyama136d27a2019-07-11 05:40:30 +0000833 initFunctions.emplace_back(WasmInitEntry{sym, f.Priority});
Nicholas Wilsoncb81a0c2018-03-02 14:46:54 +0000834 }
Sam Clegg50686852018-01-12 18:35:13 +0000835 }
Rui Ueyamada69b712018-02-28 00:15:59 +0000836
Sam Clegg50686852018-01-12 18:35:13 +0000837 // Sort in order of priority (lowest first) so that they are called
838 // in the correct order.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000839 llvm::stable_sort(initFunctions,
840 [](const WasmInitEntry &l, const WasmInitEntry &r) {
841 return l.priority < r.priority;
Fangrui Song32c0ebe2019-04-23 02:42:06 +0000842 });
Sam Clegg50686852018-01-12 18:35:13 +0000843}
844
Sam Clegg8fcf0122019-05-21 09:13:09 +0000845void Writer::createSyntheticSections() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000846 out.dylinkSec = make<DylinkSection>();
847 out.typeSec = make<TypeSection>();
848 out.importSec = make<ImportSection>();
849 out.functionSec = make<FunctionSection>();
850 out.tableSec = make<TableSection>();
851 out.memorySec = make<MemorySection>();
852 out.globalSec = make<GlobalSection>();
853 out.eventSec = make<EventSection>();
854 out.exportSec = make<ExportSection>();
855 out.elemSec = make<ElemSection>(tableBase);
856 out.dataCountSec = make<DataCountSection>(segments.size());
857 out.linkingSec = make<LinkingSection>(initFunctions, segments);
858 out.nameSec = make<NameSection>();
859 out.producersSec = make<ProducersSection>();
860 out.targetFeaturesSec = make<TargetFeaturesSection>();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000861}
862
Sam Cleggc94d3932017-11-17 18:14:09 +0000863void Writer::run() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000864 if (config->relocatable || config->isPic)
865 config->globalBase = 0;
Sam Clegg99eb42c2018-02-27 23:58:03 +0000866
Sam Cleggbfb75342018-11-15 00:37:21 +0000867 // For PIC code the table base is assigned dynamically by the loader.
868 // For non-PIC, we start at 1 so that accessing table index 0 always traps.
Sam Clegg7185a732019-08-13 17:02:02 +0000869 if (!config->isPic) {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000870 tableBase = 1;
Sam Clegg7185a732019-08-13 17:02:02 +0000871 if (WasmSym::definedTableBase)
872 WasmSym::definedTableBase->setVirtualAddress(tableBase);
873 }
Sam Cleggbfb75342018-11-15 00:37:21 +0000874
Sam Clegg8fcf0122019-05-21 09:13:09 +0000875 log("-- createOutputSegments");
876 createOutputSegments();
877 log("-- createSyntheticSections");
878 createSyntheticSections();
879 log("-- populateProducers");
880 populateProducers();
881 log("-- populateTargetFeatures");
882 populateTargetFeatures();
Sam Cleggc94d3932017-11-17 18:14:09 +0000883 log("-- calculateImports");
884 calculateImports();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000885 log("-- layoutMemory");
886 layoutMemory();
887
Rui Ueyama136d27a2019-07-11 05:40:30 +0000888 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000889 // Create linker synthesized __start_SECNAME/__stop_SECNAME symbols
890 // This has to be done after memory layout is performed.
Rui Ueyama136d27a2019-07-11 05:40:30 +0000891 for (const OutputSegment *seg : segments)
892 addStartStopSymbols(seg);
Sam Clegg4bce63a2019-05-23 10:06:03 +0000893 }
894
Sam Cleggb9889bb2019-05-23 09:41:03 +0000895 log("-- scanRelocations");
896 scanRelocations();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000897 log("-- assignIndexes");
898 assignIndexes();
Sam Clegg7804dbd2019-05-21 10:07:30 +0000899 log("-- calculateInitFunctions");
900 calculateInitFunctions();
Sam Clegg4bce63a2019-05-23 10:06:03 +0000901
Rui Ueyama136d27a2019-07-11 05:40:30 +0000902 if (!config->relocatable) {
Sam Clegg4bce63a2019-05-23 10:06:03 +0000903 // Create linker synthesized functions
Rui Ueyama136d27a2019-07-11 05:40:30 +0000904 if (config->passiveSegments)
Thomas Lively6004d9a2019-07-03 22:04:54 +0000905 createInitMemoryFunction();
Rui Ueyama136d27a2019-07-11 05:40:30 +0000906 if (config->isPic)
Sam Clegg09137be2019-04-04 18:40:51 +0000907 createApplyRelocationsFunction();
908 createCallCtorsFunction();
909 }
Sam Clegg4bce63a2019-05-23 10:06:03 +0000910
Guanzhong Chen0cb776e2019-08-06 20:09:04 +0000911 if (!config->relocatable && config->sharedMemory && !config->shared)
Guanzhong Chen42bba4b2019-07-16 22:00:45 +0000912 createInitTLSFunction();
913
914 if (errorCount())
915 return;
916
Sam Clegg4bce63a2019-05-23 10:06:03 +0000917 log("-- calculateTypes");
918 calculateTypes();
Sam Clegg93102972018-02-23 05:08:53 +0000919 log("-- calculateExports");
920 calculateExports();
Sam Cleggd177ab22018-05-04 23:14:42 +0000921 log("-- calculateCustomSections");
922 calculateCustomSections();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000923 log("-- populateSymtab");
924 populateSymtab();
925 log("-- addSections");
926 addSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000927
Rui Ueyama136d27a2019-07-11 05:40:30 +0000928 if (errorHandler().verbose) {
929 log("Defined Functions: " + Twine(out.functionSec->inputFunctions.size()));
930 log("Defined Globals : " + Twine(out.globalSec->inputGlobals.size()));
931 log("Defined Events : " + Twine(out.eventSec->inputEvents.size()));
Rui Ueyama7e296ad2019-07-10 09:10:01 +0000932 log("Function Imports : " +
Rui Ueyama136d27a2019-07-11 05:40:30 +0000933 Twine(out.importSec->getNumImportedFunctions()));
934 log("Global Imports : " + Twine(out.importSec->getNumImportedGlobals()));
935 log("Event Imports : " + Twine(out.importSec->getNumImportedEvents()));
936 for (ObjFile *file : symtab->objectFiles)
937 file->dumpInfo();
Sam Cleggc94d3932017-11-17 18:14:09 +0000938 }
939
Sam Cleggc94d3932017-11-17 18:14:09 +0000940 createHeader();
Sam Clegg8fcf0122019-05-21 09:13:09 +0000941 log("-- finalizeSections");
942 finalizeSections();
Sam Cleggc94d3932017-11-17 18:14:09 +0000943
944 log("-- openFile");
945 openFile();
946 if (errorCount())
947 return;
948
949 writeHeader();
950
951 log("-- writeSections");
952 writeSections();
953 if (errorCount())
954 return;
955
Rui Ueyama136d27a2019-07-11 05:40:30 +0000956 if (Error e = buffer->commit())
957 fatal("failed to write the output file: " + toString(std::move(e)));
Sam Cleggc94d3932017-11-17 18:14:09 +0000958}
959
960// Open a result file.
961void Writer::openFile() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000962 log("writing: " + config->outputFile);
Sam Cleggc94d3932017-11-17 18:14:09 +0000963
Rui Ueyama136d27a2019-07-11 05:40:30 +0000964 Expected<std::unique_ptr<FileOutputBuffer>> bufferOrErr =
965 FileOutputBuffer::create(config->outputFile, fileSize,
Sam Cleggc94d3932017-11-17 18:14:09 +0000966 FileOutputBuffer::F_executable);
967
Rui Ueyama136d27a2019-07-11 05:40:30 +0000968 if (!bufferOrErr)
969 error("failed to open " + config->outputFile + ": " +
970 toString(bufferOrErr.takeError()));
Sam Cleggc94d3932017-11-17 18:14:09 +0000971 else
Rui Ueyama136d27a2019-07-11 05:40:30 +0000972 buffer = std::move(*bufferOrErr);
Sam Cleggc94d3932017-11-17 18:14:09 +0000973}
974
975void Writer::createHeader() {
Rui Ueyama136d27a2019-07-11 05:40:30 +0000976 raw_string_ostream os(header);
977 writeBytes(os, WasmMagic, sizeof(WasmMagic), "wasm magic");
978 writeU32(os, WasmVersion, "wasm version");
979 os.flush();
980 fileSize += header.size();
Sam Cleggc94d3932017-11-17 18:14:09 +0000981}
982
983void lld::wasm::writeResult() { Writer().run(); }