Sam Clegg | c94d393 | 2017-11-17 18:14:09 +0000 | [diff] [blame] | 1 | //===- Writer.cpp ---------------------------------------------------------===// |
| 2 | // |
| 3 | // The LLVM Linker |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "Writer.h" |
| 11 | |
| 12 | #include "Config.h" |
Sam Clegg | c94d393 | 2017-11-17 18:14:09 +0000 | [diff] [blame] | 13 | #include "OutputSections.h" |
| 14 | #include "OutputSegment.h" |
| 15 | #include "SymbolTable.h" |
| 16 | #include "WriterUtils.h" |
| 17 | #include "lld/Common/ErrorHandler.h" |
Rui Ueyama | 2017d52 | 2017-11-28 20:39:17 +0000 | [diff] [blame] | 18 | #include "lld/Common/Memory.h" |
Sam Clegg | c94d393 | 2017-11-17 18:14:09 +0000 | [diff] [blame] | 19 | #include "lld/Common/Threads.h" |
| 20 | #include "llvm/Support/FileOutputBuffer.h" |
| 21 | #include "llvm/Support/Format.h" |
| 22 | #include "llvm/Support/FormatVariadic.h" |
| 23 | #include "llvm/Support/LEB128.h" |
| 24 | |
| 25 | #include <cstdarg> |
| 26 | |
| 27 | #define DEBUG_TYPE "lld" |
| 28 | |
| 29 | using namespace llvm; |
| 30 | using namespace llvm::wasm; |
| 31 | using namespace lld; |
| 32 | using namespace lld::wasm; |
| 33 | |
| 34 | static constexpr int kStackAlignment = 16; |
| 35 | |
| 36 | namespace { |
| 37 | |
| 38 | // Needed for WasmSignatureDenseMapInfo |
| 39 | bool operator==(const WasmSignature &LHS, const WasmSignature &RHS) { |
| 40 | return LHS.ReturnType == RHS.ReturnType && LHS.ParamTypes == RHS.ParamTypes; |
| 41 | } |
| 42 | |
| 43 | // Traits for using WasmSignature in a DenseMap. |
| 44 | struct WasmSignatureDenseMapInfo { |
| 45 | static WasmSignature getEmptyKey() { |
| 46 | WasmSignature Sig; |
| 47 | Sig.ReturnType = 1; |
| 48 | return Sig; |
| 49 | } |
| 50 | static WasmSignature getTombstoneKey() { |
| 51 | WasmSignature Sig; |
| 52 | Sig.ReturnType = 2; |
| 53 | return Sig; |
| 54 | } |
| 55 | static unsigned getHashValue(const WasmSignature &Sig) { |
| 56 | uintptr_t Value = 0; |
| 57 | Value += DenseMapInfo<int32_t>::getHashValue(Sig.ReturnType); |
| 58 | for (int32_t Param : Sig.ParamTypes) |
| 59 | Value += DenseMapInfo<int32_t>::getHashValue(Param); |
| 60 | return Value; |
| 61 | } |
| 62 | static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) { |
| 63 | return LHS == RHS; |
| 64 | } |
| 65 | }; |
| 66 | |
| 67 | // The writer writes a SymbolTable result to a file. |
| 68 | class Writer { |
| 69 | public: |
| 70 | void run(); |
| 71 | |
| 72 | private: |
| 73 | void openFile(); |
| 74 | |
| 75 | void assignSymbolIndexes(); |
| 76 | void calculateImports(); |
| 77 | void calculateOffsets(); |
| 78 | void calculateTypes(); |
| 79 | void createOutputSegments(); |
| 80 | void layoutMemory(); |
| 81 | void createHeader(); |
| 82 | void createSections(); |
| 83 | SyntheticSection *createSyntheticSection(uint32_t Type, |
| 84 | std::string Name = ""); |
| 85 | |
| 86 | // Builtin sections |
| 87 | void createTypeSection(); |
| 88 | void createFunctionSection(); |
| 89 | void createTableSection(); |
| 90 | void createGlobalSection(); |
| 91 | void createExportSection(); |
| 92 | void createImportSection(); |
| 93 | void createMemorySection(); |
| 94 | void createElemSection(); |
| 95 | void createStartSection(); |
| 96 | void createCodeSection(); |
| 97 | void createDataSection(); |
| 98 | |
| 99 | // Custom sections |
| 100 | void createRelocSections(); |
| 101 | void createLinkingSection(); |
| 102 | void createNameSection(); |
| 103 | |
| 104 | void writeHeader(); |
| 105 | void writeSections(); |
| 106 | |
| 107 | uint64_t FileSize = 0; |
| 108 | uint32_t DataSize = 0; |
| 109 | uint32_t NumFunctions = 0; |
| 110 | uint32_t NumGlobals = 0; |
| 111 | uint32_t NumMemoryPages = 0; |
| 112 | uint32_t NumTableElems = 0; |
| 113 | uint32_t NumElements = 0; |
| 114 | uint32_t InitialTableOffset = 0; |
| 115 | |
| 116 | std::vector<const WasmSignature *> Types; |
| 117 | DenseMap<WasmSignature, int32_t, WasmSignatureDenseMapInfo> TypeIndices; |
| 118 | std::vector<Symbol *> FunctionImports; |
| 119 | std::vector<Symbol *> GlobalImports; |
| 120 | |
| 121 | // Elements that are used to construct the final output |
| 122 | std::string Header; |
| 123 | std::vector<OutputSection *> OutputSections; |
| 124 | |
| 125 | std::unique_ptr<FileOutputBuffer> Buffer; |
| 126 | |
| 127 | std::vector<OutputSegment *> Segments; |
| 128 | llvm::SmallDenseMap<StringRef, OutputSegment *> SegmentMap; |
| 129 | }; |
| 130 | |
| 131 | } // anonymous namespace |
| 132 | |
| 133 | static void debugPrint(const char *fmt, ...) { |
| 134 | if (!errorHandler().Verbose) |
| 135 | return; |
| 136 | fprintf(stderr, "lld: "); |
| 137 | va_list ap; |
| 138 | va_start(ap, fmt); |
| 139 | vfprintf(stderr, fmt, ap); |
| 140 | va_end(ap); |
| 141 | } |
| 142 | |
| 143 | void Writer::createImportSection() { |
| 144 | uint32_t NumImports = FunctionImports.size() + GlobalImports.size(); |
| 145 | if (Config->ImportMemory) |
| 146 | ++NumImports; |
| 147 | |
| 148 | if (NumImports == 0) |
| 149 | return; |
| 150 | |
| 151 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_IMPORT); |
| 152 | raw_ostream &OS = Section->getStream(); |
| 153 | |
| 154 | writeUleb128(OS, NumImports, "import count"); |
| 155 | |
| 156 | for (Symbol *Sym : FunctionImports) { |
| 157 | WasmImport Import; |
| 158 | Import.Module = "env"; |
| 159 | Import.Field = Sym->getName(); |
| 160 | Import.Kind = WASM_EXTERNAL_FUNCTION; |
| 161 | auto *Obj = cast<ObjFile>(Sym->getFile()); |
| 162 | Import.SigIndex = Obj->relocateTypeIndex(Sym->getFunctionTypeIndex()); |
| 163 | writeImport(OS, Import); |
| 164 | } |
| 165 | |
| 166 | if (Config->ImportMemory) { |
| 167 | WasmImport Import; |
| 168 | Import.Module = "env"; |
| 169 | Import.Field = "memory"; |
| 170 | Import.Kind = WASM_EXTERNAL_MEMORY; |
| 171 | Import.Memory.Flags = 0; |
| 172 | Import.Memory.Initial = NumMemoryPages; |
| 173 | writeImport(OS, Import); |
| 174 | } |
| 175 | |
| 176 | for (Symbol *Sym : GlobalImports) { |
| 177 | WasmImport Import; |
| 178 | Import.Module = "env"; |
| 179 | Import.Field = Sym->getName(); |
| 180 | Import.Kind = WASM_EXTERNAL_GLOBAL; |
| 181 | Import.Global.Mutable = false; |
| 182 | assert(isa<ObjFile>(Sym->getFile())); |
| 183 | // TODO(sbc): Set type of this import |
| 184 | // ObjFile* Obj = dyn_cast<ObjFile>(Sym->getFile()); |
| 185 | Import.Global.Type = WASM_TYPE_I32; // Sym->getGlobalType(); |
| 186 | writeImport(OS, Import); |
| 187 | } |
| 188 | } |
| 189 | |
| 190 | void Writer::createTypeSection() { |
| 191 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_TYPE); |
| 192 | raw_ostream &OS = Section->getStream(); |
| 193 | writeUleb128(OS, Types.size(), "type count"); |
| 194 | for (const WasmSignature *Sig : Types) { |
| 195 | writeSig(OS, *Sig); |
| 196 | } |
| 197 | } |
| 198 | |
| 199 | void Writer::createFunctionSection() { |
| 200 | if (!NumFunctions) |
| 201 | return; |
| 202 | |
| 203 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_FUNCTION); |
| 204 | raw_ostream &OS = Section->getStream(); |
| 205 | |
| 206 | writeUleb128(OS, NumFunctions, "function count"); |
| 207 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 208 | for (uint32_t Sig : File->getWasmObj()->functionTypes()) { |
| 209 | writeUleb128(OS, File->relocateTypeIndex(Sig), "sig index"); |
| 210 | } |
| 211 | } |
| 212 | } |
| 213 | |
| 214 | void Writer::createMemorySection() { |
| 215 | if (Config->ImportMemory) |
| 216 | return; |
| 217 | |
| 218 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_MEMORY); |
| 219 | raw_ostream &OS = Section->getStream(); |
| 220 | |
| 221 | writeUleb128(OS, 1, "memory count"); |
| 222 | writeUleb128(OS, 0, "memory limits flags"); |
| 223 | writeUleb128(OS, NumMemoryPages, "initial pages"); |
| 224 | } |
| 225 | |
| 226 | void Writer::createGlobalSection() { |
| 227 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_GLOBAL); |
| 228 | raw_ostream &OS = Section->getStream(); |
| 229 | |
| 230 | writeUleb128(OS, NumGlobals, "global count"); |
| 231 | for (auto &Pair : Config->SyntheticGlobals) { |
| 232 | WasmGlobal &Global = Pair.second; |
| 233 | writeGlobal(OS, Global); |
| 234 | } |
| 235 | |
| 236 | if (Config->Relocatable || Config->EmitRelocs) { |
| 237 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 238 | uint32_t GlobalIndex = File->NumGlobalImports(); |
| 239 | for (const WasmGlobal &Global : File->getWasmObj()->globals()) { |
| 240 | WasmGlobal RelocatedGlobal(Global); |
| 241 | if (Global.Type != WASM_TYPE_I32) |
| 242 | fatal("unsupported global type: " + Twine(Global.Type)); |
| 243 | if (Global.InitExpr.Opcode != WASM_OPCODE_I32_CONST) |
| 244 | fatal("unsupported global init opcode: " + |
| 245 | Twine(Global.InitExpr.Opcode)); |
| 246 | RelocatedGlobal.InitExpr.Value.Int32 = |
| 247 | File->getRelocatedAddress(GlobalIndex); |
| 248 | writeGlobal(OS, RelocatedGlobal); |
| 249 | ++GlobalIndex; |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | } |
| 254 | |
| 255 | void Writer::createTableSection() { |
| 256 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_TABLE); |
| 257 | raw_ostream &OS = Section->getStream(); |
| 258 | |
| 259 | writeUleb128(OS, 1, "table count"); |
| 260 | writeSleb128(OS, WASM_TYPE_ANYFUNC, "table type"); |
| 261 | writeUleb128(OS, WASM_LIMITS_FLAG_HAS_MAX, "table flags"); |
| 262 | writeUleb128(OS, NumTableElems, "table initial size"); |
| 263 | writeUleb128(OS, NumTableElems, "table max size"); |
| 264 | } |
| 265 | |
| 266 | void Writer::createExportSection() { |
| 267 | // Memory is and main function are exported for executables. |
| 268 | bool ExportMemory = !Config->Relocatable && !Config->ImportMemory; |
| 269 | bool ExportMain = !Config->Relocatable; |
| 270 | bool ExportOther = true; // Config->Relocatable; |
| 271 | |
| 272 | uint32_t NumExports = 0; |
| 273 | |
| 274 | if (ExportMemory) |
| 275 | ++NumExports; |
| 276 | |
| 277 | if (ExportMain && !ExportOther) |
| 278 | ++NumExports; |
| 279 | |
| 280 | if (ExportOther) { |
| 281 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 282 | for (Symbol *Sym : File->getSymbols()) { |
| 283 | if (!Sym->isFunction() || Sym->isLocal() || Sym->isUndefined() || |
| 284 | Sym->WrittenToSymtab) |
| 285 | continue; |
| 286 | Sym->WrittenToSymtab = true; |
| 287 | ++NumExports; |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | if (!NumExports) |
| 293 | return; |
| 294 | |
| 295 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_EXPORT); |
| 296 | raw_ostream &OS = Section->getStream(); |
| 297 | |
| 298 | writeUleb128(OS, NumExports, "export count"); |
| 299 | |
| 300 | if (ExportMemory) { |
| 301 | WasmExport MemoryExport; |
| 302 | MemoryExport.Name = "memory"; |
| 303 | MemoryExport.Kind = WASM_EXTERNAL_MEMORY; |
| 304 | MemoryExport.Index = 0; |
| 305 | writeExport(OS, MemoryExport); |
| 306 | } |
| 307 | |
| 308 | if (ExportMain) { |
| 309 | Symbol *Sym = Symtab->find(Config->Entry); |
| 310 | if (Sym->isDefined()) { |
| 311 | if (!Sym->isFunction()) |
| 312 | fatal("entry point is not a function: " + Sym->getName()); |
| 313 | |
| 314 | if (!ExportOther) { |
| 315 | WasmExport MainExport; |
| 316 | MainExport.Name = Config->Entry; |
| 317 | MainExport.Kind = WASM_EXTERNAL_FUNCTION; |
| 318 | MainExport.Index = Sym->getOutputIndex(); |
| 319 | writeExport(OS, MainExport); |
| 320 | } |
| 321 | } |
| 322 | } |
| 323 | |
| 324 | if (ExportOther) { |
| 325 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 326 | for (Symbol *Sym : File->getSymbols()) { |
| 327 | if (!Sym->isFunction() || Sym->isLocal() | Sym->isUndefined() || |
| 328 | !Sym->WrittenToSymtab) |
| 329 | continue; |
| 330 | Sym->WrittenToSymtab = false; |
| 331 | log("Export: " + Sym->getName()); |
| 332 | WasmExport Export; |
| 333 | Export.Name = Sym->getName(); |
| 334 | Export.Index = Sym->getOutputIndex(); |
| 335 | if (Sym->isFunction()) |
| 336 | Export.Kind = WASM_EXTERNAL_FUNCTION; |
| 337 | else |
| 338 | Export.Kind = WASM_EXTERNAL_GLOBAL; |
| 339 | writeExport(OS, Export); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | // TODO(sbc): Export local symbols too, Even though they are not part |
| 344 | // of the symbol table? |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | void Writer::createStartSection() {} |
| 349 | |
| 350 | void Writer::createElemSection() { |
| 351 | if (!NumElements) |
| 352 | return; |
| 353 | |
| 354 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_ELEM); |
| 355 | raw_ostream &OS = Section->getStream(); |
| 356 | |
| 357 | writeUleb128(OS, 1, "segment count"); |
| 358 | writeUleb128(OS, 0, "table index"); |
| 359 | WasmInitExpr InitExpr; |
| 360 | InitExpr.Opcode = WASM_OPCODE_I32_CONST; |
| 361 | InitExpr.Value.Int32 = InitialTableOffset; |
| 362 | writeInitExpr(OS, InitExpr); |
| 363 | writeUleb128(OS, NumElements, "elem count"); |
| 364 | |
| 365 | for (ObjFile *File : Symtab->ObjectFiles) |
| 366 | for (const WasmElemSegment &Segment : File->getWasmObj()->elements()) |
| 367 | for (uint64_t FunctionIndex : Segment.Functions) |
| 368 | writeUleb128(OS, File->relocateFunctionIndex(FunctionIndex), |
| 369 | "function index"); |
| 370 | } |
| 371 | |
| 372 | void Writer::createCodeSection() { |
| 373 | if (!NumFunctions) |
| 374 | return; |
| 375 | |
| 376 | log("createCodeSection"); |
| 377 | |
| 378 | auto Section = make<CodeSection>(NumFunctions, Symtab->ObjectFiles); |
| 379 | OutputSections.push_back(Section); |
| 380 | } |
| 381 | |
| 382 | void Writer::createDataSection() { |
| 383 | if (!Segments.size()) |
| 384 | return; |
| 385 | |
| 386 | log("createDataSection"); |
| 387 | auto Section = make<DataSection>(Segments); |
| 388 | OutputSections.push_back(Section); |
| 389 | } |
| 390 | |
| 391 | // Create reloctions sections in the final output. |
| 392 | // These are only created when relocatable output is requested. |
| 393 | void Writer::createRelocSections() { |
| 394 | log("createRelocSections"); |
| 395 | // Don't use iterator here since we are adding to OutputSection |
| 396 | size_t OrigSize = OutputSections.size(); |
| 397 | for (size_t i = 0; i < OrigSize; i++) { |
| 398 | OutputSection *S = OutputSections[i]; |
| 399 | const char *name; |
| 400 | uint32_t Count = S->numRelocations(); |
| 401 | if (!Count) |
| 402 | continue; |
| 403 | |
| 404 | if (S->Type == WASM_SEC_DATA) |
| 405 | name = "reloc.DATA"; |
| 406 | else if (S->Type == WASM_SEC_CODE) |
| 407 | name = "reloc.CODE"; |
| 408 | else |
| 409 | llvm_unreachable("relocations only support for code and data"); |
| 410 | |
| 411 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, name); |
| 412 | raw_ostream &OS = Section->getStream(); |
| 413 | writeUleb128(OS, S->Type, "reloc section"); |
| 414 | writeUleb128(OS, Count, "reloc count"); |
| 415 | S->writeRelocations(OS); |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | // Create the custome "linking" section containing linker metadata. |
| 420 | // This is only created when relocatable output is requested. |
| 421 | void Writer::createLinkingSection() { |
| 422 | SyntheticSection *Section = |
| 423 | createSyntheticSection(WASM_SEC_CUSTOM, "linking"); |
| 424 | raw_ostream &OS = Section->getStream(); |
| 425 | |
| 426 | SubSection DataSizeSubSection(WASM_DATA_SIZE); |
| 427 | writeUleb128(DataSizeSubSection.getStream(), DataSize, "data size"); |
| 428 | DataSizeSubSection.finalizeContents(); |
| 429 | DataSizeSubSection.writeToStream(OS); |
| 430 | |
| 431 | if (Segments.size() && Config->Relocatable) { |
| 432 | SubSection SubSection(WASM_SEGMENT_INFO); |
| 433 | writeUleb128(SubSection.getStream(), Segments.size(), "num data segments"); |
| 434 | for (const OutputSegment *S : Segments) { |
| 435 | writeStr(SubSection.getStream(), S->Name, "segment name"); |
| 436 | writeUleb128(SubSection.getStream(), S->Alignment, "alignment"); |
| 437 | writeUleb128(SubSection.getStream(), 0, "flags"); |
| 438 | } |
| 439 | SubSection.finalizeContents(); |
| 440 | SubSection.writeToStream(OS); |
| 441 | } |
| 442 | } |
| 443 | |
| 444 | // Create the custom "name" section containing debug symbol names. |
| 445 | void Writer::createNameSection() { |
| 446 | // Create an array of all function sorted by function index space |
| 447 | std::vector<const Symbol *> Names; |
| 448 | |
| 449 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 450 | Names.reserve(Names.size() + File->getSymbols().size()); |
| 451 | for (Symbol *S : File->getSymbols()) { |
| 452 | if (!S->isFunction() || S->isWeak() || S->WrittenToNameSec) |
| 453 | continue; |
| 454 | S->WrittenToNameSec = true; |
| 455 | Names.emplace_back(S); |
| 456 | } |
| 457 | } |
| 458 | |
| 459 | SyntheticSection *Section = createSyntheticSection(WASM_SEC_CUSTOM, "name"); |
| 460 | |
| 461 | std::sort(Names.begin(), Names.end(), [](const Symbol *A, const Symbol *B) { |
| 462 | return A->getOutputIndex() < B->getOutputIndex(); |
| 463 | }); |
| 464 | |
| 465 | SubSection FunctionSubsection(WASM_NAMES_FUNCTION); |
| 466 | raw_ostream &OS = FunctionSubsection.getStream(); |
| 467 | writeUleb128(OS, Names.size(), "name count"); |
| 468 | |
| 469 | // We have to iterate through the inputs twice so that all the imports |
| 470 | // appear first before any of the local function names. |
| 471 | for (const Symbol *S : Names) { |
| 472 | writeUleb128(OS, S->getOutputIndex(), "func index"); |
| 473 | writeStr(OS, S->getName(), "symbol name"); |
| 474 | } |
| 475 | |
| 476 | FunctionSubsection.finalizeContents(); |
| 477 | FunctionSubsection.writeToStream(Section->getStream()); |
| 478 | } |
| 479 | |
| 480 | void Writer::writeHeader() { |
| 481 | memcpy(Buffer->getBufferStart(), Header.data(), Header.size()); |
| 482 | } |
| 483 | |
| 484 | void Writer::writeSections() { |
| 485 | uint8_t *Buf = Buffer->getBufferStart(); |
| 486 | parallelForEach(OutputSections, [Buf](OutputSection *S) { S->writeTo(Buf); }); |
| 487 | } |
| 488 | |
| 489 | // Fix the memory layout of the output binary. This assigns memory offsets |
| 490 | // to each of the intput data sections as well as the explicit stack region. |
| 491 | void Writer::layoutMemory() { |
| 492 | uint32_t MemoryPtr = 0; |
| 493 | if (!Config->Relocatable) { |
| 494 | MemoryPtr = Config->GlobalBase; |
| 495 | debugPrint("mem: global base = %d\n", Config->GlobalBase); |
| 496 | } |
| 497 | |
| 498 | createOutputSegments(); |
| 499 | |
| 500 | // Static data comes first |
| 501 | for (OutputSegment *Seg : Segments) { |
| 502 | MemoryPtr = alignTo(MemoryPtr, Seg->Alignment); |
| 503 | Seg->StartVA = MemoryPtr; |
| 504 | debugPrint("mem: %-10s offset=%-8d size=%-4d align=%d\n", |
| 505 | Seg->Name.str().c_str(), MemoryPtr, Seg->Size, Seg->Alignment); |
| 506 | MemoryPtr += Seg->Size; |
| 507 | } |
| 508 | |
| 509 | DataSize = MemoryPtr; |
| 510 | if (!Config->Relocatable) |
| 511 | DataSize -= Config->GlobalBase; |
| 512 | debugPrint("mem: static data = %d\n", DataSize); |
| 513 | |
| 514 | // Stack comes after static data |
| 515 | if (!Config->Relocatable) { |
| 516 | MemoryPtr = alignTo(MemoryPtr, kStackAlignment); |
| 517 | if (Config->ZStackSize != alignTo(Config->ZStackSize, kStackAlignment)) |
| 518 | error("stack size must be " + Twine(kStackAlignment) + "-byte aligned"); |
| 519 | debugPrint("mem: stack size = %d\n", Config->ZStackSize); |
| 520 | debugPrint("mem: stack base = %d\n", MemoryPtr); |
| 521 | MemoryPtr += Config->ZStackSize; |
| 522 | Config->SyntheticGlobals[0].second.InitExpr.Value.Int32 = MemoryPtr; |
| 523 | debugPrint("mem: stack top = %d\n", MemoryPtr); |
| 524 | } |
| 525 | |
| 526 | uint32_t MemSize = alignTo(MemoryPtr, WasmPageSize); |
| 527 | NumMemoryPages = MemSize / WasmPageSize; |
| 528 | debugPrint("mem: total pages = %d\n", NumMemoryPages); |
| 529 | } |
| 530 | |
| 531 | SyntheticSection *Writer::createSyntheticSection(uint32_t Type, |
| 532 | std::string Name) { |
| 533 | auto Sec = make<SyntheticSection>(Type, Name); |
| 534 | log("createSection: " + toString(Sec)); |
| 535 | OutputSections.push_back(Sec); |
| 536 | return Sec; |
| 537 | } |
| 538 | |
| 539 | void Writer::createSections() { |
| 540 | // Known sections |
| 541 | createTypeSection(); |
| 542 | createImportSection(); |
| 543 | createFunctionSection(); |
| 544 | createTableSection(); |
| 545 | createMemorySection(); |
| 546 | createGlobalSection(); |
| 547 | createExportSection(); |
| 548 | createStartSection(); |
| 549 | createElemSection(); |
| 550 | createCodeSection(); |
| 551 | createDataSection(); |
| 552 | |
| 553 | // Custom sections |
| 554 | if (Config->EmitRelocs || Config->Relocatable) |
| 555 | createRelocSections(); |
| 556 | createLinkingSection(); |
| 557 | if (!Config->StripDebug && !Config->StripAll) |
| 558 | createNameSection(); |
| 559 | |
| 560 | for (OutputSection *S : OutputSections) { |
| 561 | S->setOffset(FileSize); |
| 562 | S->finalizeContents(); |
| 563 | FileSize += S->getSize(); |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | void Writer::calculateOffsets() { |
| 568 | NumGlobals = Config->SyntheticGlobals.size(); |
| 569 | NumTableElems = InitialTableOffset; |
| 570 | |
| 571 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 572 | const WasmObjectFile *WasmFile = File->getWasmObj(); |
| 573 | |
| 574 | // Function Index |
| 575 | File->FunctionIndexOffset = |
| 576 | FunctionImports.size() - File->NumFunctionImports() + NumFunctions; |
| 577 | NumFunctions += WasmFile->functions().size(); |
| 578 | |
| 579 | // Global Index |
| 580 | if (Config->Relocatable || Config->EmitRelocs) { |
| 581 | File->GlobalIndexOffset = |
| 582 | GlobalImports.size() - File->NumGlobalImports() + NumGlobals; |
| 583 | NumGlobals += WasmFile->globals().size(); |
| 584 | } |
| 585 | |
| 586 | // Memory |
| 587 | if (WasmFile->memories().size()) { |
| 588 | if (WasmFile->memories().size() > 1) { |
| 589 | fatal(File->getName() + ": contains more than one memory"); |
| 590 | } |
| 591 | } |
| 592 | |
| 593 | // Table |
| 594 | uint32_t TableCount = WasmFile->tables().size(); |
| 595 | if (TableCount) { |
| 596 | if (TableCount > 1) |
| 597 | fatal(File->getName() + ": contains more than one table"); |
| 598 | File->TableIndexOffset = NumTableElems; |
| 599 | NumTableElems += WasmFile->tables()[0].Limits.Initial; |
| 600 | } |
| 601 | |
| 602 | // Elem |
| 603 | uint32_t SegmentCount = WasmFile->elements().size(); |
| 604 | if (SegmentCount) { |
Rui Ueyama | e48f223 | 2017-11-29 20:45:58 +0000 | [diff] [blame^] | 605 | if (SegmentCount > 1) |
Sam Clegg | c94d393 | 2017-11-17 18:14:09 +0000 | [diff] [blame] | 606 | fatal(File->getName() + ": contains more than element segment"); |
Rui Ueyama | e48f223 | 2017-11-29 20:45:58 +0000 | [diff] [blame^] | 607 | |
| 608 | const WasmElemSegment &Segment = WasmFile->elements()[0]; |
| 609 | if (Segment.TableIndex != 0) |
| 610 | fatal(File->getName() + ": unsupported table index"); |
| 611 | if (Segment.Offset.Value.Int32 != 0) |
| 612 | fatal(File->getName() + ": unsupported segment offset"); |
| 613 | NumElements += Segment.Functions.size(); |
Sam Clegg | c94d393 | 2017-11-17 18:14:09 +0000 | [diff] [blame] | 614 | } |
| 615 | } |
| 616 | } |
| 617 | |
| 618 | void Writer::calculateImports() { |
| 619 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 620 | for (Symbol *Sym : File->getSymbols()) { |
| 621 | if (Sym->hasOutputIndex() || Sym->isDefined() || Sym->isWeak()) |
| 622 | continue; |
| 623 | |
| 624 | if (Sym->isFunction()) { |
| 625 | Sym->setOutputIndex(FunctionImports.size()); |
| 626 | FunctionImports.push_back(Sym); |
| 627 | } else { |
| 628 | Sym->setOutputIndex(GlobalImports.size()); |
| 629 | GlobalImports.push_back(Sym); |
| 630 | } |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | void Writer::calculateTypes() { |
| 636 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 637 | File->TypeMap.reserve(File->getWasmObj()->types().size()); |
| 638 | for (const WasmSignature &Sig : File->getWasmObj()->types()) { |
| 639 | auto Pair = TypeIndices.insert(std::make_pair(Sig, Types.size())); |
| 640 | if (Pair.second) |
| 641 | Types.push_back(&Sig); |
| 642 | |
| 643 | // Now we map the input files index to the index in the linked output |
| 644 | File->TypeMap.push_back(Pair.first->second); |
| 645 | } |
| 646 | } |
| 647 | } |
| 648 | |
| 649 | void Writer::assignSymbolIndexes() { |
| 650 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 651 | DEBUG(dbgs() << "assignSymbolIndexes: " << File->getName() << "\n"); |
| 652 | for (Symbol *Sym : File->getSymbols()) { |
| 653 | if (Sym->hasOutputIndex() || !Sym->isDefined()) |
| 654 | continue; |
| 655 | |
| 656 | if (Sym->getFile() && isa<ObjFile>(Sym->getFile())) { |
| 657 | auto *Obj = cast<ObjFile>(Sym->getFile()); |
| 658 | if (Sym->isFunction()) |
| 659 | Sym->setOutputIndex(Obj->FunctionIndexOffset + |
| 660 | Sym->getFunctionIndex()); |
| 661 | else |
| 662 | Sym->setOutputIndex(Obj->GlobalIndexOffset + Sym->getGlobalIndex()); |
| 663 | } |
| 664 | } |
| 665 | } |
| 666 | } |
| 667 | |
| 668 | static StringRef getOutputDataSegmentName(StringRef Name) { |
| 669 | if (Config->Relocatable) |
| 670 | return Name; |
| 671 | |
| 672 | for (StringRef V : |
| 673 | {".text.", ".rodata.", ".data.rel.ro.", ".data.", ".bss.rel.ro.", |
| 674 | ".bss.", ".init_array.", ".fini_array.", ".ctors.", ".dtors.", ".tbss.", |
| 675 | ".gcc_except_table.", ".tdata.", ".ARM.exidx.", ".ARM.extab."}) { |
| 676 | StringRef Prefix = V.drop_back(); |
| 677 | if (Name.startswith(V) || Name == Prefix) |
| 678 | return Prefix; |
| 679 | } |
| 680 | |
| 681 | return Name; |
| 682 | } |
| 683 | |
| 684 | void Writer::createOutputSegments() { |
| 685 | for (ObjFile *File : Symtab->ObjectFiles) { |
| 686 | for (InputSegment *Segment : File->Segments) { |
| 687 | StringRef Name = getOutputDataSegmentName(Segment->getName()); |
| 688 | OutputSegment *&S = SegmentMap[Name]; |
| 689 | if (S == nullptr) { |
| 690 | DEBUG(dbgs() << "new segment: " << Name << "\n"); |
| 691 | S = make<OutputSegment>(Name); |
| 692 | Segments.push_back(S); |
| 693 | } |
| 694 | S->addInputSegment(Segment); |
| 695 | DEBUG(dbgs() << "added data: " << Name << ": " << S->Size << "\n"); |
| 696 | for (const WasmRelocation &R : File->DataSection->Relocations) { |
| 697 | if (R.Offset >= Segment->getInputSectionOffset() && |
| 698 | R.Offset < Segment->getInputSectionOffset() + Segment->getSize()) { |
| 699 | Segment->Relocations.push_back(R); |
| 700 | } |
| 701 | } |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | |
| 706 | void Writer::run() { |
| 707 | if (!Config->Relocatable) |
| 708 | InitialTableOffset = 1; |
| 709 | |
| 710 | log("-- calculateTypes"); |
| 711 | calculateTypes(); |
| 712 | log("-- calculateImports"); |
| 713 | calculateImports(); |
| 714 | log("-- calculateOffsets"); |
| 715 | calculateOffsets(); |
| 716 | |
| 717 | if (errorHandler().Verbose) { |
| 718 | log("NumFunctions : " + Twine(NumFunctions)); |
| 719 | log("NumGlobals : " + Twine(NumGlobals)); |
| 720 | log("NumImports : " + |
| 721 | Twine(FunctionImports.size() + GlobalImports.size())); |
| 722 | log("FunctionImports : " + Twine(FunctionImports.size())); |
| 723 | log("GlobalImports : " + Twine(GlobalImports.size())); |
| 724 | for (ObjFile *File : Symtab->ObjectFiles) |
| 725 | File->dumpInfo(); |
| 726 | } |
| 727 | |
| 728 | log("-- assignSymbolIndexes"); |
| 729 | assignSymbolIndexes(); |
| 730 | log("-- layoutMemory"); |
| 731 | layoutMemory(); |
| 732 | |
| 733 | createHeader(); |
| 734 | log("-- createSections"); |
| 735 | createSections(); |
| 736 | |
| 737 | log("-- openFile"); |
| 738 | openFile(); |
| 739 | if (errorCount()) |
| 740 | return; |
| 741 | |
| 742 | writeHeader(); |
| 743 | |
| 744 | log("-- writeSections"); |
| 745 | writeSections(); |
| 746 | if (errorCount()) |
| 747 | return; |
| 748 | |
| 749 | if (Error E = Buffer->commit()) |
| 750 | fatal("failed to write the output file: " + toString(std::move(E))); |
| 751 | } |
| 752 | |
| 753 | // Open a result file. |
| 754 | void Writer::openFile() { |
| 755 | log("writing: " + Config->OutputFile); |
| 756 | ::remove(Config->OutputFile.str().c_str()); |
| 757 | |
| 758 | Expected<std::unique_ptr<FileOutputBuffer>> BufferOrErr = |
| 759 | FileOutputBuffer::create(Config->OutputFile, FileSize, |
| 760 | FileOutputBuffer::F_executable); |
| 761 | |
| 762 | if (!BufferOrErr) |
| 763 | error("failed to open " + Config->OutputFile + ": " + |
| 764 | toString(BufferOrErr.takeError())); |
| 765 | else |
| 766 | Buffer = std::move(*BufferOrErr); |
| 767 | } |
| 768 | |
| 769 | void Writer::createHeader() { |
| 770 | raw_string_ostream OS(Header); |
| 771 | writeBytes(OS, WasmMagic, sizeof(WasmMagic), "wasm magic"); |
| 772 | writeU32(OS, WasmVersion, "wasm version"); |
| 773 | OS.flush(); |
| 774 | FileSize += Header.size(); |
| 775 | } |
| 776 | |
| 777 | void lld::wasm::writeResult() { Writer().run(); } |