Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 1 | //===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements Wasm object file writer information. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
| 14 | #include "llvm/ADT/STLExtras.h" |
| 15 | #include "llvm/ADT/SmallPtrSet.h" |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 16 | #include "llvm/MC/MCAsmBackend.h" |
| 17 | #include "llvm/MC/MCAsmInfo.h" |
| 18 | #include "llvm/MC/MCAsmLayout.h" |
| 19 | #include "llvm/MC/MCAssembler.h" |
| 20 | #include "llvm/MC/MCContext.h" |
| 21 | #include "llvm/MC/MCExpr.h" |
| 22 | #include "llvm/MC/MCFixupKindInfo.h" |
| 23 | #include "llvm/MC/MCObjectFileInfo.h" |
| 24 | #include "llvm/MC/MCObjectWriter.h" |
| 25 | #include "llvm/MC/MCSectionWasm.h" |
| 26 | #include "llvm/MC/MCSymbolWasm.h" |
| 27 | #include "llvm/MC/MCValue.h" |
| 28 | #include "llvm/MC/MCWasmObjectWriter.h" |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 29 | #include "llvm/Support/Casting.h" |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 30 | #include "llvm/Support/Debug.h" |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 31 | #include "llvm/Support/ErrorHandling.h" |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 32 | #include "llvm/Support/LEB128.h" |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 33 | #include "llvm/Support/StringSaver.h" |
Dan Gohman | 7ea5adf | 2017-02-22 18:50:20 +0000 | [diff] [blame] | 34 | #include "llvm/Support/Wasm.h" |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 35 | #include <vector> |
| 36 | |
| 37 | using namespace llvm; |
| 38 | |
| 39 | #undef DEBUG_TYPE |
| 40 | #define DEBUG_TYPE "reloc-info" |
| 41 | |
| 42 | namespace { |
Sam Clegg | 9e15f35 | 2017-06-03 02:01:24 +0000 | [diff] [blame] | 43 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 44 | // For patching purposes, we need to remember where each section starts, both |
| 45 | // for patching up the section size field, and for patching up references to |
| 46 | // locations within the section. |
| 47 | struct SectionBookkeeping { |
| 48 | // Where the size of the section is written. |
| 49 | uint64_t SizeOffset; |
| 50 | // Where the contents of the section starts (after the header). |
| 51 | uint64_t ContentsOffset; |
| 52 | }; |
| 53 | |
Sam Clegg | 9e15f35 | 2017-06-03 02:01:24 +0000 | [diff] [blame] | 54 | // The signature of a wasm function, in a struct capable of being used as a |
| 55 | // DenseMap key. |
| 56 | struct WasmFunctionType { |
| 57 | // Support empty and tombstone instances, needed by DenseMap. |
| 58 | enum { Plain, Empty, Tombstone } State; |
| 59 | |
| 60 | // The return types of the function. |
| 61 | SmallVector<wasm::ValType, 1> Returns; |
| 62 | |
| 63 | // The parameter types of the function. |
| 64 | SmallVector<wasm::ValType, 4> Params; |
| 65 | |
| 66 | WasmFunctionType() : State(Plain) {} |
| 67 | |
| 68 | bool operator==(const WasmFunctionType &Other) const { |
| 69 | return State == Other.State && Returns == Other.Returns && |
| 70 | Params == Other.Params; |
| 71 | } |
| 72 | }; |
| 73 | |
| 74 | // Traits for using WasmFunctionType in a DenseMap. |
| 75 | struct WasmFunctionTypeDenseMapInfo { |
| 76 | static WasmFunctionType getEmptyKey() { |
| 77 | WasmFunctionType FuncTy; |
| 78 | FuncTy.State = WasmFunctionType::Empty; |
| 79 | return FuncTy; |
| 80 | } |
| 81 | static WasmFunctionType getTombstoneKey() { |
| 82 | WasmFunctionType FuncTy; |
| 83 | FuncTy.State = WasmFunctionType::Tombstone; |
| 84 | return FuncTy; |
| 85 | } |
| 86 | static unsigned getHashValue(const WasmFunctionType &FuncTy) { |
| 87 | uintptr_t Value = FuncTy.State; |
| 88 | for (wasm::ValType Ret : FuncTy.Returns) |
| 89 | Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Ret)); |
| 90 | for (wasm::ValType Param : FuncTy.Params) |
| 91 | Value += DenseMapInfo<int32_t>::getHashValue(int32_t(Param)); |
| 92 | return Value; |
| 93 | } |
| 94 | static bool isEqual(const WasmFunctionType &LHS, |
| 95 | const WasmFunctionType &RHS) { |
| 96 | return LHS == RHS; |
| 97 | } |
| 98 | }; |
| 99 | |
| 100 | // A wasm import to be written into the import section. |
| 101 | struct WasmImport { |
| 102 | StringRef ModuleName; |
| 103 | StringRef FieldName; |
| 104 | unsigned Kind; |
| 105 | int32_t Type; |
| 106 | }; |
| 107 | |
| 108 | // A wasm function to be written into the function section. |
| 109 | struct WasmFunction { |
| 110 | int32_t Type; |
| 111 | const MCSymbolWasm *Sym; |
| 112 | }; |
| 113 | |
| 114 | // A wasm export to be written into the export section. |
| 115 | struct WasmExport { |
| 116 | StringRef FieldName; |
| 117 | unsigned Kind; |
| 118 | uint32_t Index; |
| 119 | }; |
| 120 | |
| 121 | // A wasm global to be written into the global section. |
| 122 | struct WasmGlobal { |
| 123 | wasm::ValType Type; |
| 124 | bool IsMutable; |
| 125 | bool HasImport; |
| 126 | uint64_t InitialValue; |
| 127 | uint32_t ImportIndex; |
| 128 | }; |
| 129 | |
Sam Clegg | 6dc65e9 | 2017-06-06 16:38:59 +0000 | [diff] [blame] | 130 | // Information about a single relocation. |
| 131 | struct WasmRelocationEntry { |
| 132 | uint64_t Offset; // Where is the relocation. |
| 133 | const MCSymbolWasm *Symbol; // The symbol to relocate with. |
| 134 | int64_t Addend; // A value to add to the symbol. |
| 135 | unsigned Type; // The type of the relocation. |
| 136 | MCSectionWasm *FixupSection;// The section the relocation is targeting. |
| 137 | |
| 138 | WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol, |
| 139 | int64_t Addend, unsigned Type, |
| 140 | MCSectionWasm *FixupSection) |
| 141 | : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type), |
| 142 | FixupSection(FixupSection) {} |
| 143 | |
| 144 | void print(raw_ostream &Out) const { |
| 145 | Out << "Off=" << Offset << ", Sym=" << Symbol << ", Addend=" << Addend |
| 146 | << ", Type=" << Type << ", FixupSection=" << FixupSection; |
| 147 | } |
| 148 | void dump() const { print(errs()); } |
| 149 | }; |
| 150 | |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 151 | class WasmObjectWriter : public MCObjectWriter { |
| 152 | /// Helper struct for containing some precomputed information on symbols. |
| 153 | struct WasmSymbolData { |
| 154 | const MCSymbolWasm *Symbol; |
| 155 | StringRef Name; |
| 156 | |
| 157 | // Support lexicographic sorting. |
| 158 | bool operator<(const WasmSymbolData &RHS) const { return Name < RHS.Name; } |
| 159 | }; |
| 160 | |
| 161 | /// The target specific Wasm writer instance. |
| 162 | std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter; |
| 163 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 164 | // Relocations for fixing up references in the code section. |
| 165 | std::vector<WasmRelocationEntry> CodeRelocations; |
| 166 | |
| 167 | // Relocations for fixing up references in the data section. |
| 168 | std::vector<WasmRelocationEntry> DataRelocations; |
| 169 | |
| 170 | // Fixups for call_indirect type indices. |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 171 | std::vector<WasmRelocationEntry> TypeIndexFixups; |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 172 | |
| 173 | // Index values to use for fixing up call_indirect type indices. |
| 174 | std::vector<uint32_t> TypeIndexFixupTypes; |
| 175 | |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 176 | // TargetObjectWriter wrappers. |
| 177 | bool is64Bit() const { return TargetObjectWriter->is64Bit(); } |
| 178 | unsigned getRelocType(MCContext &Ctx, const MCValue &Target, |
| 179 | const MCFixup &Fixup, bool IsPCRel) const { |
| 180 | return TargetObjectWriter->getRelocType(Ctx, Target, Fixup, IsPCRel); |
| 181 | } |
| 182 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 183 | void startSection(SectionBookkeeping &Section, unsigned SectionId, |
| 184 | const char *Name = nullptr); |
| 185 | void endSection(SectionBookkeeping &Section); |
| 186 | |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 187 | public: |
| 188 | WasmObjectWriter(MCWasmObjectTargetWriter *MOTW, raw_pwrite_stream &OS) |
| 189 | : MCObjectWriter(OS, /*IsLittleEndian=*/true), TargetObjectWriter(MOTW) {} |
| 190 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 191 | private: |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 192 | ~WasmObjectWriter() override; |
| 193 | |
| 194 | void writeHeader(const MCAssembler &Asm); |
| 195 | |
| 196 | void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout, |
| 197 | const MCFragment *Fragment, const MCFixup &Fixup, |
| 198 | MCValue Target, bool &IsPCRel, |
| 199 | uint64_t &FixedValue) override; |
| 200 | |
| 201 | void executePostLayoutBinding(MCAssembler &Asm, |
| 202 | const MCAsmLayout &Layout) override; |
| 203 | |
| 204 | void writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override; |
Sam Clegg | 9e15f35 | 2017-06-03 02:01:24 +0000 | [diff] [blame] | 205 | |
| 206 | void writeValueType(wasm::ValType Ty) { |
| 207 | encodeSLEB128(int32_t(Ty), getStream()); |
| 208 | } |
| 209 | |
| 210 | void writeTypeSection(const SmallVector<WasmFunctionType, 4> &FunctionTypes); |
| 211 | void writeImportSection(const SmallVector<WasmImport, 4> &Imports); |
| 212 | void writeFunctionSection(const SmallVector<WasmFunction, 4> &Functions); |
| 213 | void writeTableSection(const SmallVector<uint32_t, 4> &TableElems); |
| 214 | void writeMemorySection(const SmallVector<char, 0> &DataBytes); |
| 215 | void writeGlobalSection(const SmallVector<WasmGlobal, 4> &Globals); |
| 216 | void writeExportSection(const SmallVector<WasmExport, 4> &Exports); |
| 217 | void writeElemSection(const SmallVector<uint32_t, 4> &TableElems); |
| 218 | void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout, |
| 219 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices, |
| 220 | const SmallVector<WasmFunction, 4> &Functions); |
| 221 | uint64_t |
| 222 | writeDataSection(const SmallVector<char, 0> &DataBytes, |
| 223 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices); |
| 224 | void writeNameSection(const SmallVector<WasmFunction, 4> &Functions, |
| 225 | const SmallVector<WasmImport, 4> &Imports, |
| 226 | uint32_t NumFuncImports); |
| 227 | void writeCodeRelocSection( |
| 228 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices); |
| 229 | void writeDataRelocSection( |
| 230 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices, |
| 231 | uint64_t DataSectionHeaderSize); |
| 232 | void writeLinkingMetaDataSection(bool HasStackPointer, |
| 233 | uint32_t StackPointerGlobal); |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 234 | }; |
Sam Clegg | 9e15f35 | 2017-06-03 02:01:24 +0000 | [diff] [blame] | 235 | |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 236 | } // end anonymous namespace |
| 237 | |
| 238 | WasmObjectWriter::~WasmObjectWriter() {} |
| 239 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 240 | // Return the padding size to write a 32-bit value into a 5-byte ULEB128. |
| 241 | static unsigned PaddingFor5ByteULEB128(uint32_t X) { |
| 242 | return X == 0 ? 4 : (4u - (31u - countLeadingZeros(X)) / 7u); |
| 243 | } |
| 244 | |
| 245 | // Return the padding size to write a 32-bit value into a 5-byte SLEB128. |
| 246 | static unsigned PaddingFor5ByteSLEB128(int32_t X) { |
| 247 | return 5 - getSLEB128Size(X); |
| 248 | } |
| 249 | |
| 250 | // Write out a section header and a patchable section size field. |
| 251 | void WasmObjectWriter::startSection(SectionBookkeeping &Section, |
| 252 | unsigned SectionId, |
| 253 | const char *Name) { |
| 254 | assert((Name != nullptr) == (SectionId == wasm::WASM_SEC_CUSTOM) && |
| 255 | "Only custom sections can have names"); |
| 256 | |
Derek Schuff | e2688c4 | 2017-03-14 20:23:22 +0000 | [diff] [blame] | 257 | encodeULEB128(SectionId, getStream()); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 258 | |
| 259 | Section.SizeOffset = getStream().tell(); |
| 260 | |
| 261 | // The section size. We don't know the size yet, so reserve enough space |
| 262 | // for any 32-bit value; we'll patch it later. |
| 263 | encodeULEB128(UINT32_MAX, getStream()); |
| 264 | |
| 265 | // The position where the section starts, for measuring its size. |
| 266 | Section.ContentsOffset = getStream().tell(); |
| 267 | |
| 268 | // Custom sections in wasm also have a string identifier. |
| 269 | if (SectionId == wasm::WASM_SEC_CUSTOM) { |
| 270 | encodeULEB128(strlen(Name), getStream()); |
| 271 | writeBytes(Name); |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | // Now that the section is complete and we know how big it is, patch up the |
| 276 | // section size field at the start of the section. |
| 277 | void WasmObjectWriter::endSection(SectionBookkeeping &Section) { |
| 278 | uint64_t Size = getStream().tell() - Section.ContentsOffset; |
| 279 | if (uint32_t(Size) != Size) |
| 280 | report_fatal_error("section size does not fit in a uint32_t"); |
| 281 | |
| 282 | unsigned Padding = PaddingFor5ByteULEB128(Size); |
| 283 | |
| 284 | // Write the final section size to the payload_len field, which follows |
| 285 | // the section id byte. |
| 286 | uint8_t Buffer[16]; |
| 287 | unsigned SizeLen = encodeULEB128(Size, Buffer, Padding); |
| 288 | assert(SizeLen == 5); |
| 289 | getStream().pwrite((char *)Buffer, SizeLen, Section.SizeOffset); |
| 290 | } |
| 291 | |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 292 | // Emit the Wasm header. |
| 293 | void WasmObjectWriter::writeHeader(const MCAssembler &Asm) { |
Dan Gohman | 7ea5adf | 2017-02-22 18:50:20 +0000 | [diff] [blame] | 294 | writeBytes(StringRef(wasm::WasmMagic, sizeof(wasm::WasmMagic))); |
| 295 | writeLE32(wasm::WasmVersion); |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 296 | } |
| 297 | |
| 298 | void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm, |
| 299 | const MCAsmLayout &Layout) { |
| 300 | } |
| 301 | |
| 302 | void WasmObjectWriter::recordRelocation(MCAssembler &Asm, |
| 303 | const MCAsmLayout &Layout, |
| 304 | const MCFragment *Fragment, |
| 305 | const MCFixup &Fixup, MCValue Target, |
| 306 | bool &IsPCRel, uint64_t &FixedValue) { |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 307 | MCSectionWasm &FixupSection = cast<MCSectionWasm>(*Fragment->getParent()); |
| 308 | uint64_t C = Target.getConstant(); |
| 309 | uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset(); |
| 310 | MCContext &Ctx = Asm.getContext(); |
| 311 | |
| 312 | if (const MCSymbolRefExpr *RefB = Target.getSymB()) { |
| 313 | assert(RefB->getKind() == MCSymbolRefExpr::VK_None && |
| 314 | "Should not have constructed this"); |
| 315 | |
| 316 | // Let A, B and C being the components of Target and R be the location of |
| 317 | // the fixup. If the fixup is not pcrel, we want to compute (A - B + C). |
| 318 | // If it is pcrel, we want to compute (A - B + C - R). |
| 319 | |
| 320 | // In general, Wasm has no relocations for -B. It can only represent (A + C) |
| 321 | // or (A + C - R). If B = R + K and the relocation is not pcrel, we can |
| 322 | // replace B to implement it: (A - R - K + C) |
| 323 | if (IsPCRel) { |
| 324 | Ctx.reportError( |
| 325 | Fixup.getLoc(), |
| 326 | "No relocation available to represent this relative expression"); |
| 327 | return; |
| 328 | } |
| 329 | |
| 330 | const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol()); |
| 331 | |
| 332 | if (SymB.isUndefined()) { |
| 333 | Ctx.reportError(Fixup.getLoc(), |
| 334 | Twine("symbol '") + SymB.getName() + |
| 335 | "' can not be undefined in a subtraction expression"); |
| 336 | return; |
| 337 | } |
| 338 | |
| 339 | assert(!SymB.isAbsolute() && "Should have been folded"); |
| 340 | const MCSection &SecB = SymB.getSection(); |
| 341 | if (&SecB != &FixupSection) { |
| 342 | Ctx.reportError(Fixup.getLoc(), |
| 343 | "Cannot represent a difference across sections"); |
| 344 | return; |
| 345 | } |
| 346 | |
| 347 | uint64_t SymBOffset = Layout.getSymbolOffset(SymB); |
| 348 | uint64_t K = SymBOffset - FixupOffset; |
| 349 | IsPCRel = true; |
| 350 | C -= K; |
| 351 | } |
| 352 | |
| 353 | // We either rejected the fixup or folded B into C at this point. |
| 354 | const MCSymbolRefExpr *RefA = Target.getSymA(); |
| 355 | const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : nullptr; |
| 356 | |
| 357 | bool ViaWeakRef = false; |
| 358 | if (SymA && SymA->isVariable()) { |
| 359 | const MCExpr *Expr = SymA->getVariableValue(); |
| 360 | if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr)) { |
| 361 | if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF) { |
| 362 | SymA = cast<MCSymbolWasm>(&Inner->getSymbol()); |
| 363 | ViaWeakRef = true; |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | // Put any constant offset in an addend. Offsets can be negative, and |
| 369 | // LLVM expects wrapping, in contrast to wasm's immediates which can't |
| 370 | // be negative and don't wrap. |
| 371 | FixedValue = 0; |
| 372 | |
| 373 | if (SymA) { |
| 374 | if (ViaWeakRef) |
| 375 | llvm_unreachable("weakref used in reloc not yet implemented"); |
| 376 | else |
| 377 | SymA->setUsedInReloc(); |
| 378 | } |
| 379 | |
| 380 | if (RefA) { |
| 381 | if (RefA->getKind() == MCSymbolRefExpr::VK_WebAssembly_TYPEINDEX) { |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 382 | assert(C == 0); |
| 383 | WasmRelocationEntry Rec(FixupOffset, SymA, C, |
| 384 | wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB, |
| 385 | &FixupSection); |
| 386 | TypeIndexFixups.push_back(Rec); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 387 | return; |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | unsigned Type = getRelocType(Ctx, Target, Fixup, IsPCRel); |
| 392 | |
| 393 | WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection); |
| 394 | |
| 395 | if (FixupSection.hasInstructions()) |
| 396 | CodeRelocations.push_back(Rec); |
| 397 | else |
| 398 | DataRelocations.push_back(Rec); |
| 399 | } |
| 400 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 401 | // Write X as an (unsigned) LEB value at offset Offset in Stream, padded |
| 402 | // to allow patching. |
| 403 | static void |
| 404 | WritePatchableLEB(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { |
| 405 | uint8_t Buffer[5]; |
| 406 | unsigned Padding = PaddingFor5ByteULEB128(X); |
| 407 | unsigned SizeLen = encodeULEB128(X, Buffer, Padding); |
| 408 | assert(SizeLen == 5); |
| 409 | Stream.pwrite((char *)Buffer, SizeLen, Offset); |
| 410 | } |
| 411 | |
| 412 | // Write X as an signed LEB value at offset Offset in Stream, padded |
| 413 | // to allow patching. |
| 414 | static void |
| 415 | WritePatchableSLEB(raw_pwrite_stream &Stream, int32_t X, uint64_t Offset) { |
| 416 | uint8_t Buffer[5]; |
| 417 | unsigned Padding = PaddingFor5ByteSLEB128(X); |
| 418 | unsigned SizeLen = encodeSLEB128(X, Buffer, Padding); |
| 419 | assert(SizeLen == 5); |
| 420 | Stream.pwrite((char *)Buffer, SizeLen, Offset); |
| 421 | } |
| 422 | |
| 423 | // Write X as a plain integer value at offset Offset in Stream. |
| 424 | static void WriteI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) { |
| 425 | uint8_t Buffer[4]; |
| 426 | support::endian::write32le(Buffer, X); |
| 427 | Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset); |
| 428 | } |
| 429 | |
| 430 | // Compute a value to write into the code at the location covered |
| 431 | // by RelEntry. This value isn't used by the static linker, since |
| 432 | // we have addends; it just serves to make the code more readable |
| 433 | // and to make standalone wasm modules directly usable. |
| 434 | static uint32_t ProvisionalValue(const WasmRelocationEntry &RelEntry) { |
| 435 | const MCSymbolWasm *Sym = RelEntry.Symbol; |
| 436 | |
| 437 | // For undefined symbols, use a hopefully invalid value. |
| 438 | if (!Sym->isDefined(false)) |
| 439 | return UINT32_MAX; |
| 440 | |
| 441 | MCSectionWasm &Section = |
| 442 | cast<MCSectionWasm>(RelEntry.Symbol->getSection(false)); |
| 443 | uint64_t Address = Section.getSectionOffset() + RelEntry.Addend; |
| 444 | |
| 445 | // Ignore overflow. LLVM allows address arithmetic to silently wrap. |
| 446 | uint32_t Value = Address; |
| 447 | |
| 448 | return Value; |
| 449 | } |
| 450 | |
| 451 | // Apply the portions of the relocation records that we can handle ourselves |
| 452 | // directly. |
| 453 | static void ApplyRelocations( |
| 454 | ArrayRef<WasmRelocationEntry> Relocations, |
| 455 | raw_pwrite_stream &Stream, |
| 456 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices, |
| 457 | uint64_t ContentsOffset) |
| 458 | { |
| 459 | for (const WasmRelocationEntry &RelEntry : Relocations) { |
| 460 | uint64_t Offset = ContentsOffset + |
| 461 | RelEntry.FixupSection->getSectionOffset() + |
| 462 | RelEntry.Offset; |
| 463 | switch (RelEntry.Type) { |
| 464 | case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: { |
Sam Clegg | 1c154a6 | 2017-05-25 21:08:07 +0000 | [diff] [blame] | 465 | assert(SymbolIndices.count(RelEntry.Symbol)); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 466 | uint32_t Index = SymbolIndices[RelEntry.Symbol]; |
| 467 | assert(RelEntry.Addend == 0); |
| 468 | |
| 469 | WritePatchableLEB(Stream, Index, Offset); |
| 470 | break; |
| 471 | } |
| 472 | case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: { |
Sam Clegg | 1c154a6 | 2017-05-25 21:08:07 +0000 | [diff] [blame] | 473 | assert(SymbolIndices.count(RelEntry.Symbol)); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 474 | uint32_t Index = SymbolIndices[RelEntry.Symbol]; |
| 475 | assert(RelEntry.Addend == 0); |
| 476 | |
| 477 | WritePatchableSLEB(Stream, Index, Offset); |
| 478 | break; |
| 479 | } |
| 480 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: { |
| 481 | uint32_t Value = ProvisionalValue(RelEntry); |
| 482 | |
| 483 | WritePatchableSLEB(Stream, Value, Offset); |
| 484 | break; |
| 485 | } |
| 486 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: { |
| 487 | uint32_t Value = ProvisionalValue(RelEntry); |
| 488 | |
| 489 | WritePatchableLEB(Stream, Value, Offset); |
| 490 | break; |
| 491 | } |
| 492 | case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: { |
Sam Clegg | 1c154a6 | 2017-05-25 21:08:07 +0000 | [diff] [blame] | 493 | assert(SymbolIndices.count(RelEntry.Symbol)); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 494 | uint32_t Index = SymbolIndices[RelEntry.Symbol]; |
| 495 | assert(RelEntry.Addend == 0); |
| 496 | |
| 497 | WriteI32(Stream, Index, Offset); |
| 498 | break; |
| 499 | } |
| 500 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: { |
| 501 | uint32_t Value = ProvisionalValue(RelEntry); |
| 502 | |
| 503 | WriteI32(Stream, Value, Offset); |
| 504 | break; |
| 505 | } |
| 506 | default: |
| 507 | break; |
| 508 | } |
| 509 | } |
| 510 | } |
| 511 | |
| 512 | // Write out the portions of the relocation records that the linker will |
| 513 | // need to handle. |
Sam Clegg | a06de02 | 2017-04-28 21:22:38 +0000 | [diff] [blame] | 514 | static void |
| 515 | WriteRelocations(ArrayRef<WasmRelocationEntry> Relocations, |
| 516 | raw_pwrite_stream &Stream, |
| 517 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices, |
| 518 | uint64_t HeaderSize) { |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 519 | for (const WasmRelocationEntry RelEntry : Relocations) { |
| 520 | encodeULEB128(RelEntry.Type, Stream); |
| 521 | |
| 522 | uint64_t Offset = RelEntry.Offset + |
Sam Clegg | a06de02 | 2017-04-28 21:22:38 +0000 | [diff] [blame] | 523 | RelEntry.FixupSection->getSectionOffset() + HeaderSize; |
Sam Clegg | 1c154a6 | 2017-05-25 21:08:07 +0000 | [diff] [blame] | 524 | assert(SymbolIndices.count(RelEntry.Symbol)); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 525 | uint32_t Index = SymbolIndices[RelEntry.Symbol]; |
| 526 | int64_t Addend = RelEntry.Addend; |
| 527 | |
| 528 | switch (RelEntry.Type) { |
| 529 | case wasm::R_WEBASSEMBLY_FUNCTION_INDEX_LEB: |
| 530 | case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: |
| 531 | case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: |
| 532 | encodeULEB128(Offset, Stream); |
| 533 | encodeULEB128(Index, Stream); |
| 534 | assert(Addend == 0 && "addends not supported for functions"); |
| 535 | break; |
| 536 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_LEB: |
| 537 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: |
| 538 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: |
| 539 | encodeULEB128(Offset, Stream); |
| 540 | encodeULEB128(Index, Stream); |
| 541 | encodeSLEB128(Addend, Stream); |
| 542 | break; |
| 543 | default: |
| 544 | llvm_unreachable("unsupported relocation type"); |
| 545 | } |
| 546 | } |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 547 | } |
| 548 | |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 549 | // Write out the the type relocation records that the linker will |
| 550 | // need to handle. |
| 551 | static void WriteTypeRelocations( |
| 552 | ArrayRef<WasmRelocationEntry> TypeIndexFixups, |
| 553 | ArrayRef<uint32_t> TypeIndexFixupTypes, |
| 554 | raw_pwrite_stream &Stream) |
| 555 | { |
| 556 | for (size_t i = 0, e = TypeIndexFixups.size(); i < e; ++i) { |
| 557 | const WasmRelocationEntry &Fixup = TypeIndexFixups[i]; |
| 558 | uint32_t Type = TypeIndexFixupTypes[i]; |
| 559 | |
| 560 | assert(Fixup.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB); |
| 561 | assert(Fixup.Addend == 0); |
| 562 | |
| 563 | uint64_t Offset = Fixup.Offset + |
| 564 | Fixup.FixupSection->getSectionOffset(); |
| 565 | |
| 566 | encodeULEB128(Fixup.Type, Stream); |
| 567 | encodeULEB128(Offset, Stream); |
| 568 | encodeULEB128(Type, Stream); |
| 569 | } |
| 570 | } |
| 571 | |
Sam Clegg | 9e15f35 | 2017-06-03 02:01:24 +0000 | [diff] [blame] | 572 | void WasmObjectWriter::writeTypeSection( |
| 573 | const SmallVector<WasmFunctionType, 4> &FunctionTypes) { |
| 574 | if (FunctionTypes.empty()) |
| 575 | return; |
| 576 | |
| 577 | SectionBookkeeping Section; |
| 578 | startSection(Section, wasm::WASM_SEC_TYPE); |
| 579 | |
| 580 | encodeULEB128(FunctionTypes.size(), getStream()); |
| 581 | |
| 582 | for (const WasmFunctionType &FuncTy : FunctionTypes) { |
| 583 | encodeSLEB128(wasm::WASM_TYPE_FUNC, getStream()); |
| 584 | encodeULEB128(FuncTy.Params.size(), getStream()); |
| 585 | for (wasm::ValType Ty : FuncTy.Params) |
| 586 | writeValueType(Ty); |
| 587 | encodeULEB128(FuncTy.Returns.size(), getStream()); |
| 588 | for (wasm::ValType Ty : FuncTy.Returns) |
| 589 | writeValueType(Ty); |
| 590 | } |
| 591 | |
| 592 | endSection(Section); |
| 593 | } |
| 594 | |
| 595 | void WasmObjectWriter::writeImportSection( |
| 596 | const SmallVector<WasmImport, 4> &Imports) { |
| 597 | if (Imports.empty()) |
| 598 | return; |
| 599 | |
| 600 | SectionBookkeeping Section; |
| 601 | startSection(Section, wasm::WASM_SEC_IMPORT); |
| 602 | |
| 603 | encodeULEB128(Imports.size(), getStream()); |
| 604 | for (const WasmImport &Import : Imports) { |
| 605 | StringRef ModuleName = Import.ModuleName; |
| 606 | encodeULEB128(ModuleName.size(), getStream()); |
| 607 | writeBytes(ModuleName); |
| 608 | |
| 609 | StringRef FieldName = Import.FieldName; |
| 610 | encodeULEB128(FieldName.size(), getStream()); |
| 611 | writeBytes(FieldName); |
| 612 | |
| 613 | encodeULEB128(Import.Kind, getStream()); |
| 614 | |
| 615 | switch (Import.Kind) { |
| 616 | case wasm::WASM_EXTERNAL_FUNCTION: |
| 617 | encodeULEB128(Import.Type, getStream()); |
| 618 | break; |
| 619 | case wasm::WASM_EXTERNAL_GLOBAL: |
| 620 | encodeSLEB128(int32_t(Import.Type), getStream()); |
| 621 | encodeULEB128(0, getStream()); // mutability |
| 622 | break; |
| 623 | default: |
| 624 | llvm_unreachable("unsupported import kind"); |
| 625 | } |
| 626 | } |
| 627 | |
| 628 | endSection(Section); |
| 629 | } |
| 630 | |
| 631 | void WasmObjectWriter::writeFunctionSection( |
| 632 | const SmallVector<WasmFunction, 4> &Functions) { |
| 633 | if (Functions.empty()) |
| 634 | return; |
| 635 | |
| 636 | SectionBookkeeping Section; |
| 637 | startSection(Section, wasm::WASM_SEC_FUNCTION); |
| 638 | |
| 639 | encodeULEB128(Functions.size(), getStream()); |
| 640 | for (const WasmFunction &Func : Functions) |
| 641 | encodeULEB128(Func.Type, getStream()); |
| 642 | |
| 643 | endSection(Section); |
| 644 | } |
| 645 | |
| 646 | void WasmObjectWriter::writeTableSection( |
| 647 | const SmallVector<uint32_t, 4> &TableElems) { |
| 648 | // For now, always emit the table section, since indirect calls are not |
| 649 | // valid without it. In the future, we could perhaps be more clever and omit |
| 650 | // it if there are no indirect calls. |
| 651 | SectionBookkeeping Section; |
| 652 | startSection(Section, wasm::WASM_SEC_TABLE); |
| 653 | |
| 654 | // The number of tables, fixed to 1 for now. |
| 655 | encodeULEB128(1, getStream()); |
| 656 | |
| 657 | encodeSLEB128(wasm::WASM_TYPE_ANYFUNC, getStream()); |
| 658 | |
| 659 | encodeULEB128(0, getStream()); // flags |
| 660 | encodeULEB128(TableElems.size(), getStream()); // initial |
| 661 | |
| 662 | endSection(Section); |
| 663 | } |
| 664 | |
| 665 | void WasmObjectWriter::writeMemorySection( |
| 666 | const SmallVector<char, 0> &DataBytes) { |
| 667 | // For now, always emit the memory section, since loads and stores are not |
| 668 | // valid without it. In the future, we could perhaps be more clever and omit |
| 669 | // it if there are no loads or stores. |
| 670 | SectionBookkeeping Section; |
| 671 | uint32_t NumPages = |
| 672 | (DataBytes.size() + wasm::WasmPageSize - 1) / wasm::WasmPageSize; |
| 673 | |
| 674 | startSection(Section, wasm::WASM_SEC_MEMORY); |
| 675 | encodeULEB128(1, getStream()); // number of memory spaces |
| 676 | |
| 677 | encodeULEB128(0, getStream()); // flags |
| 678 | encodeULEB128(NumPages, getStream()); // initial |
| 679 | |
| 680 | endSection(Section); |
| 681 | } |
| 682 | |
| 683 | void WasmObjectWriter::writeGlobalSection( |
| 684 | const SmallVector<WasmGlobal, 4> &Globals) { |
| 685 | if (Globals.empty()) |
| 686 | return; |
| 687 | |
| 688 | SectionBookkeeping Section; |
| 689 | startSection(Section, wasm::WASM_SEC_GLOBAL); |
| 690 | |
| 691 | encodeULEB128(Globals.size(), getStream()); |
| 692 | for (const WasmGlobal &Global : Globals) { |
| 693 | writeValueType(Global.Type); |
| 694 | write8(Global.IsMutable); |
| 695 | |
| 696 | if (Global.HasImport) { |
| 697 | assert(Global.InitialValue == 0); |
| 698 | write8(wasm::WASM_OPCODE_GET_GLOBAL); |
| 699 | encodeULEB128(Global.ImportIndex, getStream()); |
| 700 | } else { |
| 701 | assert(Global.ImportIndex == 0); |
| 702 | write8(wasm::WASM_OPCODE_I32_CONST); |
| 703 | encodeSLEB128(Global.InitialValue, getStream()); // offset |
| 704 | } |
| 705 | write8(wasm::WASM_OPCODE_END); |
| 706 | } |
| 707 | |
| 708 | endSection(Section); |
| 709 | } |
| 710 | |
| 711 | void WasmObjectWriter::writeExportSection( |
| 712 | const SmallVector<WasmExport, 4> &Exports) { |
| 713 | if (Exports.empty()) |
| 714 | return; |
| 715 | |
| 716 | SectionBookkeeping Section; |
| 717 | startSection(Section, wasm::WASM_SEC_EXPORT); |
| 718 | |
| 719 | encodeULEB128(Exports.size(), getStream()); |
| 720 | for (const WasmExport &Export : Exports) { |
| 721 | encodeULEB128(Export.FieldName.size(), getStream()); |
| 722 | writeBytes(Export.FieldName); |
| 723 | |
| 724 | encodeSLEB128(Export.Kind, getStream()); |
| 725 | |
| 726 | encodeULEB128(Export.Index, getStream()); |
| 727 | } |
| 728 | |
| 729 | endSection(Section); |
| 730 | } |
| 731 | |
| 732 | void WasmObjectWriter::writeElemSection( |
| 733 | const SmallVector<uint32_t, 4> &TableElems) { |
| 734 | if (TableElems.empty()) |
| 735 | return; |
| 736 | |
| 737 | SectionBookkeeping Section; |
| 738 | startSection(Section, wasm::WASM_SEC_ELEM); |
| 739 | |
| 740 | encodeULEB128(1, getStream()); // number of "segments" |
| 741 | encodeULEB128(0, getStream()); // the table index |
| 742 | |
| 743 | // init expr for starting offset |
| 744 | write8(wasm::WASM_OPCODE_I32_CONST); |
| 745 | encodeSLEB128(0, getStream()); |
| 746 | write8(wasm::WASM_OPCODE_END); |
| 747 | |
| 748 | encodeULEB128(TableElems.size(), getStream()); |
| 749 | for (uint32_t Elem : TableElems) |
| 750 | encodeULEB128(Elem, getStream()); |
| 751 | |
| 752 | endSection(Section); |
| 753 | } |
| 754 | |
| 755 | void WasmObjectWriter::writeCodeSection( |
| 756 | const MCAssembler &Asm, const MCAsmLayout &Layout, |
| 757 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices, |
| 758 | const SmallVector<WasmFunction, 4> &Functions) { |
| 759 | if (Functions.empty()) |
| 760 | return; |
| 761 | |
| 762 | SectionBookkeeping Section; |
| 763 | startSection(Section, wasm::WASM_SEC_CODE); |
| 764 | |
| 765 | encodeULEB128(Functions.size(), getStream()); |
| 766 | |
| 767 | for (const WasmFunction &Func : Functions) { |
| 768 | MCSectionWasm &FuncSection = |
| 769 | static_cast<MCSectionWasm &>(Func.Sym->getSection()); |
| 770 | |
| 771 | if (Func.Sym->isVariable()) |
| 772 | report_fatal_error("weak symbols not supported yet"); |
| 773 | |
| 774 | if (Func.Sym->getOffset() != 0) |
| 775 | report_fatal_error("function sections must contain one function each"); |
| 776 | |
| 777 | if (!Func.Sym->getSize()) |
| 778 | report_fatal_error("function symbols must have a size set with .size"); |
| 779 | |
| 780 | int64_t Size = 0; |
| 781 | if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout)) |
| 782 | report_fatal_error(".size expression must be evaluatable"); |
| 783 | |
| 784 | encodeULEB128(Size, getStream()); |
| 785 | |
| 786 | FuncSection.setSectionOffset(getStream().tell() - |
| 787 | Section.ContentsOffset); |
| 788 | |
| 789 | Asm.writeSectionData(&FuncSection, Layout); |
| 790 | } |
| 791 | |
| 792 | // Apply the type index fixups for call_indirect etc. instructions. |
| 793 | for (size_t i = 0, e = TypeIndexFixups.size(); i < e; ++i) { |
| 794 | uint32_t Type = TypeIndexFixupTypes[i]; |
| 795 | unsigned Padding = PaddingFor5ByteULEB128(Type); |
| 796 | |
| 797 | const WasmRelocationEntry &Fixup = TypeIndexFixups[i]; |
| 798 | assert(Fixup.Addend == 0); |
| 799 | assert(Fixup.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB); |
| 800 | uint64_t Offset = Fixup.Offset + |
| 801 | Fixup.FixupSection->getSectionOffset(); |
| 802 | |
| 803 | uint8_t Buffer[16]; |
| 804 | unsigned SizeLen = encodeULEB128(Type, Buffer, Padding); |
| 805 | assert(SizeLen == 5); |
| 806 | getStream().pwrite((char *)Buffer, SizeLen, |
| 807 | Section.ContentsOffset + Offset); |
| 808 | } |
| 809 | |
| 810 | // Apply fixups. |
| 811 | ApplyRelocations(CodeRelocations, getStream(), SymbolIndices, |
| 812 | Section.ContentsOffset); |
| 813 | |
| 814 | endSection(Section); |
| 815 | } |
| 816 | |
| 817 | uint64_t WasmObjectWriter::writeDataSection( |
| 818 | const SmallVector<char, 0> &DataBytes, |
| 819 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices) { |
| 820 | if (DataBytes.empty()) |
| 821 | return 0; |
| 822 | |
| 823 | SectionBookkeeping Section; |
| 824 | startSection(Section, wasm::WASM_SEC_DATA); |
| 825 | |
| 826 | encodeULEB128(1, getStream()); // count |
| 827 | encodeULEB128(0, getStream()); // memory index |
| 828 | write8(wasm::WASM_OPCODE_I32_CONST); |
| 829 | encodeSLEB128(0, getStream()); // offset |
| 830 | write8(wasm::WASM_OPCODE_END); |
| 831 | encodeULEB128(DataBytes.size(), getStream()); // size |
| 832 | uint32_t HeaderSize = getStream().tell() - Section.ContentsOffset; |
| 833 | writeBytes(DataBytes); // data |
| 834 | |
| 835 | // Apply fixups. |
| 836 | ApplyRelocations(DataRelocations, getStream(), SymbolIndices, |
| 837 | Section.ContentsOffset + HeaderSize); |
| 838 | |
| 839 | endSection(Section); |
| 840 | return HeaderSize; |
| 841 | } |
| 842 | |
| 843 | void WasmObjectWriter::writeNameSection( |
| 844 | const SmallVector<WasmFunction, 4> &Functions, |
| 845 | const SmallVector<WasmImport, 4> &Imports, |
| 846 | unsigned NumFuncImports) { |
| 847 | uint32_t TotalFunctions = NumFuncImports + Functions.size(); |
| 848 | if (TotalFunctions == 0) |
| 849 | return; |
| 850 | |
| 851 | SectionBookkeeping Section; |
| 852 | startSection(Section, wasm::WASM_SEC_CUSTOM, "name"); |
| 853 | SectionBookkeeping SubSection; |
| 854 | startSection(SubSection, wasm::WASM_NAMES_FUNCTION); |
| 855 | |
| 856 | encodeULEB128(TotalFunctions, getStream()); |
| 857 | uint32_t Index = 0; |
| 858 | for (const WasmImport &Import : Imports) { |
| 859 | if (Import.Kind == wasm::WASM_EXTERNAL_FUNCTION) { |
| 860 | encodeULEB128(Index, getStream()); |
| 861 | encodeULEB128(Import.FieldName.size(), getStream()); |
| 862 | writeBytes(Import.FieldName); |
| 863 | ++Index; |
| 864 | } |
| 865 | } |
| 866 | for (const WasmFunction &Func : Functions) { |
| 867 | encodeULEB128(Index, getStream()); |
| 868 | encodeULEB128(Func.Sym->getName().size(), getStream()); |
| 869 | writeBytes(Func.Sym->getName()); |
| 870 | ++Index; |
| 871 | } |
| 872 | |
| 873 | endSection(SubSection); |
| 874 | endSection(Section); |
| 875 | } |
| 876 | |
| 877 | void WasmObjectWriter::writeCodeRelocSection( |
| 878 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices) { |
| 879 | // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md |
| 880 | // for descriptions of the reloc sections. |
| 881 | |
| 882 | if (CodeRelocations.empty()) |
| 883 | return; |
| 884 | |
| 885 | SectionBookkeeping Section; |
| 886 | startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.CODE"); |
| 887 | |
| 888 | encodeULEB128(wasm::WASM_SEC_CODE, getStream()); |
| 889 | encodeULEB128(CodeRelocations.size() + TypeIndexFixups.size(), getStream()); |
| 890 | |
| 891 | WriteRelocations(CodeRelocations, getStream(), SymbolIndices, 0); |
| 892 | WriteTypeRelocations(TypeIndexFixups, TypeIndexFixupTypes, getStream()); |
| 893 | |
| 894 | endSection(Section); |
| 895 | } |
| 896 | |
| 897 | void WasmObjectWriter::writeDataRelocSection( |
| 898 | DenseMap<const MCSymbolWasm *, uint32_t> &SymbolIndices, |
| 899 | uint64_t DataSectionHeaderSize) { |
| 900 | // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md |
| 901 | // for descriptions of the reloc sections. |
| 902 | |
| 903 | if (DataRelocations.empty()) |
| 904 | return; |
| 905 | |
| 906 | SectionBookkeeping Section; |
| 907 | startSection(Section, wasm::WASM_SEC_CUSTOM, "reloc.DATA"); |
| 908 | |
| 909 | encodeULEB128(wasm::WASM_SEC_DATA, getStream()); |
| 910 | encodeULEB128(DataRelocations.size(), getStream()); |
| 911 | |
| 912 | WriteRelocations(DataRelocations, getStream(), SymbolIndices, |
| 913 | DataSectionHeaderSize); |
| 914 | |
| 915 | endSection(Section); |
| 916 | } |
| 917 | |
| 918 | void WasmObjectWriter::writeLinkingMetaDataSection( |
| 919 | bool HasStackPointer, uint32_t StackPointerGlobal) { |
| 920 | if (!HasStackPointer) |
| 921 | return; |
| 922 | SectionBookkeeping Section; |
| 923 | startSection(Section, wasm::WASM_SEC_CUSTOM, "linking"); |
| 924 | |
| 925 | encodeULEB128(1, getStream()); // count |
| 926 | |
| 927 | encodeULEB128(wasm::WASM_STACK_POINTER, getStream()); // type |
| 928 | encodeULEB128(StackPointerGlobal, getStream()); // id |
| 929 | |
| 930 | endSection(Section); |
| 931 | } |
| 932 | |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 933 | void WasmObjectWriter::writeObject(MCAssembler &Asm, |
| 934 | const MCAsmLayout &Layout) { |
Dan Gohman | 82607f5 | 2017-02-24 23:46:05 +0000 | [diff] [blame] | 935 | MCContext &Ctx = Asm.getContext(); |
Derek Schuff | b879539 | 2017-03-16 20:49:48 +0000 | [diff] [blame] | 936 | wasm::ValType PtrType = is64Bit() ? wasm::ValType::I64 : wasm::ValType::I32; |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 937 | |
| 938 | // Collect information from the available symbols. |
Derek Schuff | b879539 | 2017-03-16 20:49:48 +0000 | [diff] [blame] | 939 | DenseMap<WasmFunctionType, int32_t, WasmFunctionTypeDenseMapInfo> |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 940 | FunctionTypeIndices; |
| 941 | SmallVector<WasmFunctionType, 4> FunctionTypes; |
| 942 | SmallVector<WasmFunction, 4> Functions; |
| 943 | SmallVector<uint32_t, 4> TableElems; |
| 944 | SmallVector<WasmGlobal, 4> Globals; |
| 945 | SmallVector<WasmImport, 4> Imports; |
| 946 | SmallVector<WasmExport, 4> Exports; |
| 947 | DenseMap<const MCSymbolWasm *, uint32_t> SymbolIndices; |
| 948 | SmallPtrSet<const MCSymbolWasm *, 4> IsAddressTaken; |
| 949 | unsigned NumFuncImports = 0; |
| 950 | unsigned NumGlobalImports = 0; |
| 951 | SmallVector<char, 0> DataBytes; |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 952 | uint32_t StackPointerGlobal = 0; |
| 953 | bool HasStackPointer = false; |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 954 | |
| 955 | // Populate the IsAddressTaken set. |
| 956 | for (WasmRelocationEntry RelEntry : CodeRelocations) { |
| 957 | switch (RelEntry.Type) { |
| 958 | case wasm::R_WEBASSEMBLY_TABLE_INDEX_SLEB: |
| 959 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_SLEB: |
| 960 | IsAddressTaken.insert(RelEntry.Symbol); |
| 961 | break; |
| 962 | default: |
| 963 | break; |
| 964 | } |
| 965 | } |
| 966 | for (WasmRelocationEntry RelEntry : DataRelocations) { |
| 967 | switch (RelEntry.Type) { |
| 968 | case wasm::R_WEBASSEMBLY_TABLE_INDEX_I32: |
| 969 | case wasm::R_WEBASSEMBLY_GLOBAL_ADDR_I32: |
| 970 | IsAddressTaken.insert(RelEntry.Symbol); |
| 971 | break; |
| 972 | default: |
| 973 | break; |
| 974 | } |
| 975 | } |
| 976 | |
| 977 | // Populate the Imports set. |
| 978 | for (const MCSymbol &S : Asm.symbols()) { |
| 979 | const auto &WS = static_cast<const MCSymbolWasm &>(S); |
Derek Schuff | b879539 | 2017-03-16 20:49:48 +0000 | [diff] [blame] | 980 | int32_t Type; |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 981 | |
| 982 | if (WS.isFunction()) { |
| 983 | // Prepare the function's type, if we haven't seen it yet. |
| 984 | WasmFunctionType F; |
| 985 | F.Returns = WS.getReturns(); |
| 986 | F.Params = WS.getParams(); |
| 987 | auto Pair = |
| 988 | FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); |
| 989 | if (Pair.second) |
| 990 | FunctionTypes.push_back(F); |
| 991 | |
| 992 | Type = Pair.first->second; |
| 993 | } else { |
Derek Schuff | b879539 | 2017-03-16 20:49:48 +0000 | [diff] [blame] | 994 | Type = int32_t(PtrType); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 995 | } |
| 996 | |
| 997 | // If the symbol is not defined in this translation unit, import it. |
| 998 | if (!WS.isTemporary() && !WS.isDefined(/*SetUsed=*/false)) { |
| 999 | WasmImport Import; |
| 1000 | Import.ModuleName = WS.getModuleName(); |
| 1001 | Import.FieldName = WS.getName(); |
| 1002 | |
| 1003 | if (WS.isFunction()) { |
| 1004 | Import.Kind = wasm::WASM_EXTERNAL_FUNCTION; |
| 1005 | Import.Type = Type; |
| 1006 | SymbolIndices[&WS] = NumFuncImports; |
| 1007 | ++NumFuncImports; |
| 1008 | } else { |
| 1009 | Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; |
| 1010 | Import.Type = Type; |
| 1011 | SymbolIndices[&WS] = NumGlobalImports; |
| 1012 | ++NumGlobalImports; |
| 1013 | } |
| 1014 | |
| 1015 | Imports.push_back(Import); |
| 1016 | } |
| 1017 | } |
| 1018 | |
Dan Gohman | 82607f5 | 2017-02-24 23:46:05 +0000 | [diff] [blame] | 1019 | // In the special .global_variables section, we've encoded global |
| 1020 | // variables used by the function. Translate them into the Globals |
| 1021 | // list. |
| 1022 | MCSectionWasm *GlobalVars = Ctx.getWasmSection(".global_variables", 0, 0); |
| 1023 | if (!GlobalVars->getFragmentList().empty()) { |
| 1024 | if (GlobalVars->getFragmentList().size() != 1) |
| 1025 | report_fatal_error("only one .global_variables fragment supported"); |
| 1026 | const MCFragment &Frag = *GlobalVars->begin(); |
| 1027 | if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) |
| 1028 | report_fatal_error("only data supported in .global_variables"); |
| 1029 | const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag); |
| 1030 | if (!DataFrag.getFixups().empty()) |
| 1031 | report_fatal_error("fixups not supported in .global_variables"); |
| 1032 | const SmallVectorImpl<char> &Contents = DataFrag.getContents(); |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 1033 | for (const uint8_t *p = (const uint8_t *)Contents.data(), |
| 1034 | *end = (const uint8_t *)Contents.data() + Contents.size(); |
| 1035 | p != end; ) { |
Dan Gohman | 82607f5 | 2017-02-24 23:46:05 +0000 | [diff] [blame] | 1036 | WasmGlobal G; |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 1037 | if (end - p < 3) |
| 1038 | report_fatal_error("truncated global variable encoding"); |
| 1039 | G.Type = wasm::ValType(int8_t(*p++)); |
| 1040 | G.IsMutable = bool(*p++); |
| 1041 | G.HasImport = bool(*p++); |
| 1042 | if (G.HasImport) { |
| 1043 | G.InitialValue = 0; |
| 1044 | |
| 1045 | WasmImport Import; |
| 1046 | Import.ModuleName = (const char *)p; |
| 1047 | const uint8_t *nul = (const uint8_t *)memchr(p, '\0', end - p); |
| 1048 | if (!nul) |
| 1049 | report_fatal_error("global module name must be nul-terminated"); |
| 1050 | p = nul + 1; |
| 1051 | nul = (const uint8_t *)memchr(p, '\0', end - p); |
| 1052 | if (!nul) |
| 1053 | report_fatal_error("global base name must be nul-terminated"); |
| 1054 | Import.FieldName = (const char *)p; |
| 1055 | p = nul + 1; |
| 1056 | |
| 1057 | Import.Kind = wasm::WASM_EXTERNAL_GLOBAL; |
| 1058 | Import.Type = int32_t(G.Type); |
| 1059 | |
| 1060 | G.ImportIndex = NumGlobalImports; |
| 1061 | ++NumGlobalImports; |
| 1062 | |
| 1063 | Imports.push_back(Import); |
| 1064 | } else { |
| 1065 | unsigned n; |
| 1066 | G.InitialValue = decodeSLEB128(p, &n); |
| 1067 | G.ImportIndex = 0; |
Simon Pilgrim | c8da0c0 | 2017-03-31 10:45:35 +0000 | [diff] [blame] | 1068 | if ((ptrdiff_t)n > end - p) |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 1069 | report_fatal_error("global initial value must be valid SLEB128"); |
| 1070 | p += n; |
| 1071 | } |
Dan Gohman | 82607f5 | 2017-02-24 23:46:05 +0000 | [diff] [blame] | 1072 | Globals.push_back(G); |
| 1073 | } |
| 1074 | } |
| 1075 | |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 1076 | // In the special .stack_pointer section, we've encoded the stack pointer |
| 1077 | // index. |
| 1078 | MCSectionWasm *StackPtr = Ctx.getWasmSection(".stack_pointer", 0, 0); |
| 1079 | if (!StackPtr->getFragmentList().empty()) { |
| 1080 | if (StackPtr->getFragmentList().size() != 1) |
| 1081 | report_fatal_error("only one .stack_pointer fragment supported"); |
| 1082 | const MCFragment &Frag = *StackPtr->begin(); |
| 1083 | if (Frag.hasInstructions() || Frag.getKind() != MCFragment::FT_Data) |
| 1084 | report_fatal_error("only data supported in .stack_pointer"); |
| 1085 | const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag); |
| 1086 | if (!DataFrag.getFixups().empty()) |
| 1087 | report_fatal_error("fixups not supported in .stack_pointer"); |
| 1088 | const SmallVectorImpl<char> &Contents = DataFrag.getContents(); |
| 1089 | if (Contents.size() != 4) |
| 1090 | report_fatal_error("only one entry supported in .stack_pointer"); |
| 1091 | HasStackPointer = true; |
| 1092 | StackPointerGlobal = NumGlobalImports + *(const int32_t *)Contents.data(); |
| 1093 | } |
| 1094 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1095 | // Handle defined symbols. |
| 1096 | for (const MCSymbol &S : Asm.symbols()) { |
| 1097 | // Ignore unnamed temporary symbols, which aren't ever exported, imported, |
| 1098 | // or used in relocations. |
| 1099 | if (S.isTemporary() && S.getName().empty()) |
| 1100 | continue; |
| 1101 | const auto &WS = static_cast<const MCSymbolWasm &>(S); |
| 1102 | unsigned Index; |
| 1103 | if (WS.isFunction()) { |
| 1104 | // Prepare the function's type, if we haven't seen it yet. |
| 1105 | WasmFunctionType F; |
| 1106 | F.Returns = WS.getReturns(); |
| 1107 | F.Params = WS.getParams(); |
| 1108 | auto Pair = |
| 1109 | FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); |
| 1110 | if (Pair.second) |
| 1111 | FunctionTypes.push_back(F); |
| 1112 | |
Derek Schuff | b879539 | 2017-03-16 20:49:48 +0000 | [diff] [blame] | 1113 | int32_t Type = Pair.first->second; |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1114 | |
| 1115 | if (WS.isDefined(/*SetUsed=*/false)) { |
| 1116 | // A definition. Take the next available index. |
| 1117 | Index = NumFuncImports + Functions.size(); |
| 1118 | |
| 1119 | // Prepare the function. |
| 1120 | WasmFunction Func; |
| 1121 | Func.Type = Type; |
| 1122 | Func.Sym = &WS; |
| 1123 | SymbolIndices[&WS] = Index; |
| 1124 | Functions.push_back(Func); |
| 1125 | } else { |
| 1126 | // An import; the index was assigned above. |
| 1127 | Index = SymbolIndices.find(&WS)->second; |
| 1128 | } |
| 1129 | |
| 1130 | // If needed, prepare the function to be called indirectly. |
| 1131 | if (IsAddressTaken.count(&WS)) |
| 1132 | TableElems.push_back(Index); |
| 1133 | } else { |
Sam Clegg | c38e947 | 2017-06-02 01:05:24 +0000 | [diff] [blame] | 1134 | if (WS.isTemporary() && !WS.getSize()) |
| 1135 | continue; |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1136 | |
| 1137 | if (WS.isDefined(false)) { |
Sam Clegg | c38e947 | 2017-06-02 01:05:24 +0000 | [diff] [blame] | 1138 | if (WS.getOffset() != 0) |
| 1139 | report_fatal_error("data sections must contain one variable each: " + |
| 1140 | WS.getName()); |
| 1141 | if (!WS.getSize()) |
| 1142 | report_fatal_error("data symbols must have a size set with .size: " + |
| 1143 | WS.getName()); |
| 1144 | |
| 1145 | int64_t Size = 0; |
| 1146 | if (!WS.getSize()->evaluateAsAbsolute(Size, Layout)) |
| 1147 | report_fatal_error(".size expression must be evaluatable"); |
| 1148 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1149 | MCSectionWasm &DataSection = |
| 1150 | static_cast<MCSectionWasm &>(WS.getSection()); |
| 1151 | |
| 1152 | if (uint64_t(Size) != Layout.getSectionFileSize(&DataSection)) |
| 1153 | report_fatal_error("data sections must contain at most one variable"); |
| 1154 | |
| 1155 | DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment())); |
| 1156 | |
| 1157 | DataSection.setSectionOffset(DataBytes.size()); |
| 1158 | |
| 1159 | for (MCSection::iterator I = DataSection.begin(), E = DataSection.end(); |
| 1160 | I != E; ++I) { |
| 1161 | const MCFragment &Frag = *I; |
| 1162 | if (Frag.hasInstructions()) |
| 1163 | report_fatal_error("only data supported in data sections"); |
| 1164 | |
| 1165 | if (const MCAlignFragment *Align = dyn_cast<MCAlignFragment>(&Frag)) { |
| 1166 | if (Align->getValueSize() != 1) |
| 1167 | report_fatal_error("only byte values supported for alignment"); |
| 1168 | // If nops are requested, use zeros, as this is the data section. |
| 1169 | uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue(); |
| 1170 | uint64_t Size = std::min<uint64_t>(alignTo(DataBytes.size(), |
| 1171 | Align->getAlignment()), |
| 1172 | DataBytes.size() + |
| 1173 | Align->getMaxBytesToEmit()); |
| 1174 | DataBytes.resize(Size, Value); |
| 1175 | } else if (const MCFillFragment *Fill = |
| 1176 | dyn_cast<MCFillFragment>(&Frag)) { |
| 1177 | DataBytes.insert(DataBytes.end(), Size, Fill->getValue()); |
| 1178 | } else { |
| 1179 | const MCDataFragment &DataFrag = cast<MCDataFragment>(Frag); |
| 1180 | const SmallVectorImpl<char> &Contents = DataFrag.getContents(); |
| 1181 | |
| 1182 | DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end()); |
| 1183 | } |
| 1184 | } |
| 1185 | |
Sam Clegg | 1c154a6 | 2017-05-25 21:08:07 +0000 | [diff] [blame] | 1186 | // For each global, prepare a corresponding wasm global holding its |
| 1187 | // address. For externals these will also be named exports. |
| 1188 | Index = NumGlobalImports + Globals.size(); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1189 | |
Sam Clegg | 1c154a6 | 2017-05-25 21:08:07 +0000 | [diff] [blame] | 1190 | WasmGlobal Global; |
| 1191 | Global.Type = PtrType; |
| 1192 | Global.IsMutable = false; |
| 1193 | Global.HasImport = false; |
| 1194 | Global.InitialValue = DataSection.getSectionOffset(); |
| 1195 | Global.ImportIndex = 0; |
| 1196 | SymbolIndices[&WS] = Index; |
| 1197 | Globals.push_back(Global); |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1198 | } |
| 1199 | } |
| 1200 | |
| 1201 | // If the symbol is visible outside this translation unit, export it. |
| 1202 | if (WS.isExternal()) { |
| 1203 | assert(WS.isDefined(false)); |
| 1204 | WasmExport Export; |
| 1205 | Export.FieldName = WS.getName(); |
| 1206 | Export.Index = Index; |
| 1207 | |
| 1208 | if (WS.isFunction()) |
| 1209 | Export.Kind = wasm::WASM_EXTERNAL_FUNCTION; |
| 1210 | else |
| 1211 | Export.Kind = wasm::WASM_EXTERNAL_GLOBAL; |
| 1212 | |
| 1213 | Exports.push_back(Export); |
| 1214 | } |
| 1215 | } |
| 1216 | |
| 1217 | // Add types for indirect function calls. |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 1218 | for (const WasmRelocationEntry &Fixup : TypeIndexFixups) { |
| 1219 | assert(Fixup.Addend == 0); |
| 1220 | assert(Fixup.Type == wasm::R_WEBASSEMBLY_TYPE_INDEX_LEB); |
| 1221 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1222 | WasmFunctionType F; |
| 1223 | F.Returns = Fixup.Symbol->getReturns(); |
| 1224 | F.Params = Fixup.Symbol->getParams(); |
| 1225 | auto Pair = |
| 1226 | FunctionTypeIndices.insert(std::make_pair(F, FunctionTypes.size())); |
| 1227 | if (Pair.second) |
| 1228 | FunctionTypes.push_back(F); |
| 1229 | |
| 1230 | TypeIndexFixupTypes.push_back(Pair.first->second); |
| 1231 | } |
| 1232 | |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 1233 | // Write out the Wasm header. |
| 1234 | writeHeader(Asm); |
| 1235 | |
Sam Clegg | 9e15f35 | 2017-06-03 02:01:24 +0000 | [diff] [blame] | 1236 | writeTypeSection(FunctionTypes); |
| 1237 | writeImportSection(Imports); |
| 1238 | writeFunctionSection(Functions); |
| 1239 | writeTableSection(TableElems); |
| 1240 | writeMemorySection(DataBytes); |
| 1241 | writeGlobalSection(Globals); |
| 1242 | writeExportSection(Exports); |
| 1243 | // TODO: Start Section |
| 1244 | writeElemSection(TableElems); |
| 1245 | writeCodeSection(Asm, Layout, SymbolIndices, Functions); |
| 1246 | uint64_t DataSectionHeaderSize = writeDataSection(DataBytes, SymbolIndices); |
| 1247 | writeNameSection(Functions, Imports, NumFuncImports); |
| 1248 | writeCodeRelocSection(SymbolIndices); |
| 1249 | writeDataRelocSection(SymbolIndices, DataSectionHeaderSize); |
| 1250 | writeLinkingMetaDataSection(HasStackPointer, StackPointerGlobal); |
Dan Gohman | 970d02c | 2017-03-30 23:58:19 +0000 | [diff] [blame] | 1251 | |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1252 | // TODO: Translate the .comment section to the output. |
Dan Gohman | d934cb8 | 2017-02-24 23:18:00 +0000 | [diff] [blame] | 1253 | // TODO: Translate debug sections to the output. |
Dan Gohman | 18eafb6 | 2017-02-22 01:23:18 +0000 | [diff] [blame] | 1254 | } |
| 1255 | |
| 1256 | MCObjectWriter *llvm::createWasmObjectWriter(MCWasmObjectTargetWriter *MOTW, |
| 1257 | raw_pwrite_stream &OS) { |
| 1258 | return new WasmObjectWriter(MOTW, OS); |
| 1259 | } |