Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/lib/MC/WasmObjectWriter.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
2
//
3
// 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
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// This file implements Wasm object file writer information.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "llvm/ADT/STLExtras.h"
14
#include "llvm/ADT/SmallPtrSet.h"
15
#include "llvm/BinaryFormat/Wasm.h"
16
#include "llvm/Config/llvm-config.h"
17
#include "llvm/MC/MCAsmBackend.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/MCObjectWriter.h"
24
#include "llvm/MC/MCSectionWasm.h"
25
#include "llvm/MC/MCSymbolWasm.h"
26
#include "llvm/MC/MCValue.h"
27
#include "llvm/MC/MCWasmObjectWriter.h"
28
#include "llvm/Support/Casting.h"
29
#include "llvm/Support/Debug.h"
30
#include "llvm/Support/ErrorHandling.h"
31
#include "llvm/Support/LEB128.h"
32
#include "llvm/Support/StringSaver.h"
33
#include <vector>
34
35
using namespace llvm;
36
37
#define DEBUG_TYPE "mc"
38
39
namespace {
40
41
// Went we ceate the indirect function table we start at 1, so that there is
42
// and emtpy slot at 0 and therefore calling a null function pointer will trap.
43
static const uint32_t InitialTableOffset = 1;
44
45
// For patching purposes, we need to remember where each section starts, both
46
// for patching up the section size field, and for patching up references to
47
// locations within the section.
48
struct SectionBookkeeping {
49
  // Where the size of the section is written.
50
  uint64_t SizeOffset;
51
  // Where the section header ends (without custom section name).
52
  uint64_t PayloadOffset;
53
  // Where the contents of the section starts.
54
  uint64_t ContentsOffset;
55
  uint32_t Index;
56
};
57
58
// The signature of a wasm function or event, in a struct capable of being used
59
// as a DenseMap key.
60
// TODO: Consider using wasm::WasmSignature directly instead.
61
struct WasmSignature {
62
  // Support empty and tombstone instances, needed by DenseMap.
63
  enum { Plain, Empty, Tombstone } State = Plain;
64
65
  // The return types of the function.
66
  SmallVector<wasm::ValType, 1> Returns;
67
68
  // The parameter types of the function.
69
  SmallVector<wasm::ValType, 4> Params;
70
71
23.7k
  bool operator==(const WasmSignature &Other) const {
72
23.7k
    return State == Other.State && 
Returns == Other.Returns22.9k
&&
73
23.7k
           
Params == Other.Params22.9k
;
74
23.7k
  }
75
};
76
77
// Traits for using WasmSignature in a DenseMap.
78
struct WasmSignatureDenseMapInfo {
79
1.38k
  static WasmSignature getEmptyKey() {
80
1.38k
    WasmSignature Sig;
81
1.38k
    Sig.State = WasmSignature::Empty;
82
1.38k
    return Sig;
83
1.38k
  }
84
945
  static WasmSignature getTombstoneKey() {
85
945
    WasmSignature Sig;
86
945
    Sig.State = WasmSignature::Tombstone;
87
945
    return Sig;
88
945
  }
89
597
  static unsigned getHashValue(const WasmSignature &Sig) {
90
597
    uintptr_t Value = Sig.State;
91
597
    for (wasm::ValType Ret : Sig.Returns)
92
389
      Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Ret));
93
597
    for (wasm::ValType Param : Sig.Params)
94
127
      Value += DenseMapInfo<uint32_t>::getHashValue(uint32_t(Param));
95
597
    return Value;
96
597
  }
97
23.7k
  static bool isEqual(const WasmSignature &LHS, const WasmSignature &RHS) {
98
23.7k
    return LHS == RHS;
99
23.7k
  }
100
};
101
102
// A wasm data segment.  A wasm binary contains only a single data section
103
// but that can contain many segments, each with their own virtual location
104
// in memory.  Each MCSection data created by llvm is modeled as its own
105
// wasm data segment.
106
struct WasmDataSegment {
107
  MCSectionWasm *Section;
108
  StringRef Name;
109
  uint32_t InitFlags;
110
  uint32_t Offset;
111
  uint32_t Alignment;
112
  uint32_t LinkerFlags;
113
  SmallVector<char, 4> Data;
114
};
115
116
// A wasm function to be written into the function section.
117
struct WasmFunction {
118
  uint32_t SigIndex;
119
  const MCSymbolWasm *Sym;
120
};
121
122
// A wasm global to be written into the global section.
123
struct WasmGlobal {
124
  wasm::WasmGlobalType Type;
125
  uint64_t InitialValue;
126
};
127
128
// Information about a single item which is part of a COMDAT.  For each data
129
// segment or function which is in the COMDAT, there is a corresponding
130
// WasmComdatEntry.
131
struct WasmComdatEntry {
132
  unsigned Kind;
133
  uint32_t Index;
134
};
135
136
// Information about a single relocation.
137
struct WasmRelocationEntry {
138
  uint64_t Offset;                   // Where is the relocation.
139
  const MCSymbolWasm *Symbol;        // The symbol to relocate with.
140
  int64_t Addend;                    // A value to add to the symbol.
141
  unsigned Type;                     // The type of the relocation.
142
  const MCSectionWasm *FixupSection; // The section the relocation is targeting.
143
144
  WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
145
                      int64_t Addend, unsigned Type,
146
                      const MCSectionWasm *FixupSection)
147
      : Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
148
531
        FixupSection(FixupSection) {}
149
150
531
  bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
151
152
0
  void print(raw_ostream &Out) const {
153
0
    Out << wasm::relocTypetoString(Type) << " Off=" << Offset
154
0
        << ", Sym=" << *Symbol << ", Addend=" << Addend
155
0
        << ", FixupSection=" << FixupSection->getSectionName();
156
0
  }
157
158
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
159
  LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
160
#endif
161
};
162
163
static const uint32_t InvalidIndex = -1;
164
165
struct WasmCustomSection {
166
167
  StringRef Name;
168
  MCSectionWasm *Section;
169
170
  uint32_t OutputContentsOffset;
171
  uint32_t OutputIndex;
172
173
  WasmCustomSection(StringRef Name, MCSectionWasm *Section)
174
      : Name(Name), Section(Section), OutputContentsOffset(0),
175
65
        OutputIndex(InvalidIndex) {}
176
};
177
178
#if !defined(NDEBUG)
179
raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
180
  Rel.print(OS);
181
  return OS;
182
}
183
#endif
184
185
// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
186
// to allow patching.
187
static void writePatchableLEB(raw_pwrite_stream &Stream, uint32_t X,
188
1.91k
                              uint64_t Offset) {
189
1.91k
  uint8_t Buffer[5];
190
1.91k
  unsigned SizeLen = encodeULEB128(X, Buffer, 5);
191
1.91k
  assert(SizeLen == 5);
192
1.91k
  Stream.pwrite((char *)Buffer, SizeLen, Offset);
193
1.91k
}
194
195
// Write X as an signed LEB value at offset Offset in Stream, padded
196
// to allow patching.
197
static void writePatchableSLEB(raw_pwrite_stream &Stream, int32_t X,
198
66
                               uint64_t Offset) {
199
66
  uint8_t Buffer[5];
200
66
  unsigned SizeLen = encodeSLEB128(X, Buffer, 5);
201
66
  assert(SizeLen == 5);
202
66
  Stream.pwrite((char *)Buffer, SizeLen, Offset);
203
66
}
204
205
// Write X as a plain integer value at offset Offset in Stream.
206
131
static void writeI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
207
131
  uint8_t Buffer[4];
208
131
  support::endian::write32le(Buffer, X);
209
131
  Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
210
131
}
211
212
class WasmObjectWriter : public MCObjectWriter {
213
  support::endian::Writer W;
214
215
  /// The target specific Wasm writer instance.
216
  std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
217
218
  // Relocations for fixing up references in the code section.
219
  std::vector<WasmRelocationEntry> CodeRelocations;
220
  uint32_t CodeSectionIndex;
221
222
  // Relocations for fixing up references in the data section.
223
  std::vector<WasmRelocationEntry> DataRelocations;
224
  uint32_t DataSectionIndex;
225
226
  // Index values to use for fixing up call_indirect type indices.
227
  // Maps function symbols to the index of the type of the function
228
  DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
229
  // Maps function symbols to the table element index space. Used
230
  // for TABLE_INDEX relocation types (i.e. address taken functions).
231
  DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
232
  // Maps function/global symbols to the function/global/event/section index
233
  // space.
234
  DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
235
  DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
236
  // Maps data symbols to the Wasm segment and offset/size with the segment.
237
  DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
238
239
  // Stores output data (index, relocations, content offset) for custom
240
  // section.
241
  std::vector<WasmCustomSection> CustomSections;
242
  std::unique_ptr<WasmCustomSection> ProducersSection;
243
  std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
244
  // Relocations for fixing up references in the custom sections.
245
  DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
246
      CustomSectionsRelocations;
247
248
  // Map from section to defining function symbol.
249
  DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
250
251
  DenseMap<WasmSignature, uint32_t, WasmSignatureDenseMapInfo> SignatureIndices;
252
  SmallVector<WasmSignature, 4> Signatures;
253
  SmallVector<WasmDataSegment, 4> DataSegments;
254
  unsigned NumFunctionImports = 0;
255
  unsigned NumGlobalImports = 0;
256
  unsigned NumEventImports = 0;
257
  uint32_t SectionCount = 0;
258
259
  // TargetObjectWriter wrappers.
260
12
  bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
261
262
  void startSection(SectionBookkeeping &Section, unsigned SectionId);
263
  void startCustomSection(SectionBookkeeping &Section, StringRef Name);
264
  void endSection(SectionBookkeeping &Section);
265
266
public:
267
  WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
268
                   raw_pwrite_stream &OS)
269
443
      : W(OS, support::little), TargetObjectWriter(std::move(MOTW)) {}
270
271
private:
272
202
  void reset() override {
273
202
    CodeRelocations.clear();
274
202
    DataRelocations.clear();
275
202
    TypeIndices.clear();
276
202
    WasmIndices.clear();
277
202
    GOTIndices.clear();
278
202
    TableIndices.clear();
279
202
    DataLocations.clear();
280
202
    CustomSections.clear();
281
202
    ProducersSection.reset();
282
202
    TargetFeaturesSection.reset();
283
202
    CustomSectionsRelocations.clear();
284
202
    SignatureIndices.clear();
285
202
    Signatures.clear();
286
202
    DataSegments.clear();
287
202
    SectionFunctions.clear();
288
202
    NumFunctionImports = 0;
289
202
    NumGlobalImports = 0;
290
202
    MCObjectWriter::reset();
291
202
  }
292
293
  void writeHeader(const MCAssembler &Asm);
294
295
  void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
296
                        const MCFragment *Fragment, const MCFixup &Fixup,
297
                        MCValue Target, uint64_t &FixedValue) override;
298
299
  void executePostLayoutBinding(MCAssembler &Asm,
300
                                const MCAsmLayout &Layout) override;
301
302
  uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
303
304
2.21k
  void writeString(const StringRef Str) {
305
2.21k
    encodeULEB128(Str.size(), W.OS);
306
2.21k
    W.OS << Str;
307
2.21k
  }
308
309
219
  void writeValueType(wasm::ValType Ty) { W.OS << static_cast<char>(Ty); }
310
311
  void writeTypeSection(ArrayRef<WasmSignature> Signatures);
312
  void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint32_t DataSize,
313
                          uint32_t NumElements);
314
  void writeFunctionSection(ArrayRef<WasmFunction> Functions);
315
  void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
316
  void writeElemSection(ArrayRef<uint32_t> TableElems);
317
  void writeDataCountSection();
318
  void writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
319
                        ArrayRef<WasmFunction> Functions);
320
  void writeDataSection();
321
  void writeEventSection(ArrayRef<wasm::WasmEventType> Events);
322
  void writeRelocSection(uint32_t SectionIndex, StringRef Name,
323
                         std::vector<WasmRelocationEntry> &Relocations);
324
  void writeLinkingMetaDataSection(
325
      ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
326
      ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
327
      const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
328
  void writeCustomSection(WasmCustomSection &CustomSection,
329
                          const MCAssembler &Asm, const MCAsmLayout &Layout);
330
  void writeCustomRelocSections();
331
  void
332
  updateCustomSectionRelocations(const SmallVector<WasmFunction, 4> &Functions,
333
                                 const MCAsmLayout &Layout);
334
335
  uint32_t getProvisionalValue(const WasmRelocationEntry &RelEntry);
336
  void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
337
                        uint64_t ContentsOffset);
338
339
  uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
340
  uint32_t getFunctionType(const MCSymbolWasm &Symbol);
341
  uint32_t getEventType(const MCSymbolWasm &Symbol);
342
  void registerFunctionType(const MCSymbolWasm &Symbol);
343
  void registerEventType(const MCSymbolWasm &Symbol);
344
};
345
346
} // end anonymous namespace
347
348
// Write out a section header and a patchable section size field.
349
void WasmObjectWriter::startSection(SectionBookkeeping &Section,
350
1.58k
                                    unsigned SectionId) {
351
1.58k
  LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
352
1.58k
  W.OS << char(SectionId);
353
1.58k
354
1.58k
  Section.SizeOffset = W.OS.tell();
355
1.58k
356
1.58k
  // The section size. We don't know the size yet, so reserve enough space
357
1.58k
  // for any 32-bit value; we'll patch it later.
358
1.58k
  encodeULEB128(0, W.OS, 5);
359
1.58k
360
1.58k
  // The position where the section starts, for measuring its size.
361
1.58k
  Section.ContentsOffset = W.OS.tell();
362
1.58k
  Section.PayloadOffset = W.OS.tell();
363
1.58k
  Section.Index = SectionCount++;
364
1.58k
}
365
366
void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
367
412
                                          StringRef Name) {
368
412
  LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
369
412
  startSection(Section, wasm::WASM_SEC_CUSTOM);
370
412
371
412
  // The position where the section header ends, for measuring its size.
372
412
  Section.PayloadOffset = W.OS.tell();
373
412
374
412
  // Custom sections in wasm also have a string identifier.
375
412
  writeString(Name);
376
412
377
412
  // The position where the custom section starts.
378
412
  Section.ContentsOffset = W.OS.tell();
379
412
}
380
381
// Now that the section is complete and we know how big it is, patch up the
382
// section size field at the start of the section.
383
1.57k
void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
384
1.57k
  uint64_t Size = W.OS.tell();
385
1.57k
  // /dev/null doesn't support seek/tell and can report offset of 0.
386
1.57k
  // Simply skip this patching in that case.
387
1.57k
  if (!Size)
388
0
    return;
389
1.57k
390
1.57k
  Size -= Section.PayloadOffset;
391
1.57k
  if (uint32_t(Size) != Size)
392
0
    report_fatal_error("section size does not fit in a uint32_t");
393
1.57k
394
1.57k
  LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
395
1.57k
396
1.57k
  // Write the final section size to the payload_len field, which follows
397
1.57k
  // the section id byte.
398
1.57k
  writePatchableLEB(static_cast<raw_pwrite_stream &>(W.OS), Size,
399
1.57k
                    Section.SizeOffset);
400
1.57k
}
401
402
// Emit the Wasm header.
403
207
void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
404
207
  W.OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
405
207
  W.write<uint32_t>(wasm::WasmVersion);
406
207
}
407
408
void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
409
208
                                                const MCAsmLayout &Layout) {
410
208
  // Build a map of sections to the function that defines them, for use
411
208
  // in recordRelocation.
412
2.16k
  for (const MCSymbol &S : Asm.symbols()) {
413
2.16k
    const auto &WS = static_cast<const MCSymbolWasm &>(S);
414
2.16k
    if (WS.isDefined() && 
WS.isFunction()2.00k
&&
!WS.isVariable()437
) {
415
430
      const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
416
430
      auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
417
430
      if (!Pair.second)
418
0
        report_fatal_error("section already has a defining function: " +
419
0
                           Sec.getSectionName());
420
430
    }
421
2.16k
  }
422
208
}
423
424
void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
425
                                        const MCAsmLayout &Layout,
426
                                        const MCFragment *Fragment,
427
                                        const MCFixup &Fixup, MCValue Target,
428
554
                                        uint64_t &FixedValue) {
429
554
  MCAsmBackend &Backend = Asm.getBackend();
430
554
  bool IsPCRel = Backend.getFixupKindInfo(Fixup.getKind()).Flags &
431
554
                 MCFixupKindInfo::FKF_IsPCRel;
432
554
  const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
433
554
  uint64_t C = Target.getConstant();
434
554
  uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
435
554
  MCContext &Ctx = Asm.getContext();
436
554
437
554
  // The .init_array isn't translated as data, so don't do relocations in it.
438
554
  if (FixupSection.getSectionName().startswith(".init_array"))
439
22
    return;
440
532
441
532
  if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
442
0
    assert(RefB->getKind() == MCSymbolRefExpr::VK_None &&
443
0
           "Should not have constructed this");
444
0
445
0
    // Let A, B and C being the components of Target and R be the location of
446
0
    // the fixup. If the fixup is not pcrel, we want to compute (A - B + C).
447
0
    // If it is pcrel, we want to compute (A - B + C - R).
448
0
449
0
    // In general, Wasm has no relocations for -B. It can only represent (A + C)
450
0
    // or (A + C - R). If B = R + K and the relocation is not pcrel, we can
451
0
    // replace B to implement it: (A - R - K + C)
452
0
    if (IsPCRel) {
453
0
      Ctx.reportError(
454
0
          Fixup.getLoc(),
455
0
          "No relocation available to represent this relative expression");
456
0
      return;
457
0
    }
458
0
459
0
    const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
460
0
461
0
    if (SymB.isUndefined()) {
462
0
      Ctx.reportError(Fixup.getLoc(),
463
0
                      Twine("symbol '") + SymB.getName() +
464
0
                          "' can not be undefined in a subtraction expression");
465
0
      return;
466
0
    }
467
0
468
0
    assert(!SymB.isAbsolute() && "Should have been folded");
469
0
    const MCSection &SecB = SymB.getSection();
470
0
    if (&SecB != &FixupSection) {
471
0
      Ctx.reportError(Fixup.getLoc(),
472
0
                      "Cannot represent a difference across sections");
473
0
      return;
474
0
    }
475
0
476
0
    uint64_t SymBOffset = Layout.getSymbolOffset(SymB);
477
0
    uint64_t K = SymBOffset - FixupOffset;
478
0
    IsPCRel = true;
479
0
    C -= K;
480
0
  }
481
532
482
532
  // We either rejected the fixup or folded B into C at this point.
483
532
  const MCSymbolRefExpr *RefA = Target.getSymA();
484
532
  const auto *SymA = RefA ? cast<MCSymbolWasm>(&RefA->getSymbol()) : 
nullptr0
;
485
532
486
532
  if (SymA && SymA->isVariable()) {
487
10
    const MCExpr *Expr = SymA->getVariableValue();
488
10
    const auto *Inner = cast<MCSymbolRefExpr>(Expr);
489
10
    if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
490
10
      
llvm_unreachable0
("weakref used in reloc not yet implemented");
491
10
  }
492
532
493
532
  // Put any constant offset in an addend. Offsets can be negative, and
494
532
  // LLVM expects wrapping, in contrast to wasm's immediates which can't
495
532
  // be negative and don't wrap.
496
532
  FixedValue = 0;
497
532
498
532
  unsigned Type = TargetObjectWriter->getRelocType(Target, Fixup);
499
532
  assert(!IsPCRel);
500
532
  assert(SymA);
501
532
502
532
  // Absolute offset within a section or a function.
503
532
  // Currently only supported for for metadata sections.
504
532
  // See: test/MC/WebAssembly/blockaddress.ll
505
532
  if (Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
506
532
      
Type == wasm::R_WASM_SECTION_OFFSET_I32506
) {
507
84
    if (!FixupSection.getKind().isMetadata())
508
1
      report_fatal_error("relocations for function or section offsets are "
509
1
                         "only supported in metadata sections");
510
83
511
83
    const MCSymbol *SectionSymbol = nullptr;
512
83
    const MCSection &SecA = SymA->getSection();
513
83
    if (SecA.getKind().isText())
514
25
      SectionSymbol = SectionFunctions.find(&SecA)->second;
515
58
    else
516
58
      SectionSymbol = SecA.getBeginSymbol();
517
83
    if (!SectionSymbol)
518
0
      report_fatal_error("section symbol is required for relocation");
519
83
520
83
    C += Layout.getSymbolOffset(*SymA);
521
83
    SymA = cast<MCSymbolWasm>(SectionSymbol);
522
83
  }
523
532
524
532
  // Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
525
532
  // against a named symbol.
526
532
  
if (531
Type != wasm::R_WASM_TYPE_INDEX_LEB531
) {
527
515
    if (SymA->getName().empty())
528
0
      report_fatal_error("relocations against un-named temporaries are not yet "
529
0
                         "supported by wasm");
530
515
531
515
    SymA->setUsedInReloc();
532
515
  }
533
531
534
531
  if (RefA->getKind() == MCSymbolRefExpr::VK_GOT)
535
8
    SymA->setUsedInGOT();
536
531
537
531
  WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
538
531
  LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
539
531
540
531
  if (FixupSection.isWasmData()) {
541
42
    DataRelocations.push_back(Rec);
542
489
  } else if (FixupSection.getKind().isText()) {
543
400
    CodeRelocations.push_back(Rec);
544
400
  } else 
if (89
FixupSection.getKind().isMetadata()89
) {
545
89
    CustomSectionsRelocations[&FixupSection].push_back(Rec);
546
89
  } else {
547
0
    llvm_unreachable("unexpected section type");
548
0
  }
549
531
}
550
551
918
static const MCSymbolWasm *resolveSymbol(const MCSymbolWasm &Symbol) {
552
918
  const MCSymbolWasm* Ret = &Symbol;
553
943
  while (Ret->isVariable()) {
554
25
    const MCExpr *Expr = Ret->getVariableValue();
555
25
    auto *Inner = cast<MCSymbolRefExpr>(Expr);
556
25
    Ret = cast<MCSymbolWasm>(&Inner->getSymbol());
557
25
  }
558
918
  return Ret;
559
918
}
560
561
// Compute a value to write into the code at the location covered
562
// by RelEntry. This value isn't used by the static linker; it just serves
563
// to make the object format more readable and more likely to be directly
564
// useable.
565
uint32_t
566
531
WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry) {
567
531
  if (RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB && 
!RelEntry.Symbol->isGlobal()42
) {
568
8
    assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
569
8
    return GOTIndices[RelEntry.Symbol];
570
8
  }
571
523
572
523
  switch (RelEntry.Type) {
573
523
  case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
574
53
  case wasm::R_WASM_TABLE_INDEX_SLEB:
575
53
  case wasm::R_WASM_TABLE_INDEX_I32: {
576
53
    // Provisional value is table address of the resolved symbol itself
577
53
    const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
578
53
    assert(Sym->isFunction());
579
53
    return TableIndices[Sym];
580
53
  }
581
53
  case wasm::R_WASM_TYPE_INDEX_LEB:
582
16
    // Provisional value is same as the index
583
16
    return getRelocationIndexValue(RelEntry);
584
156
  case wasm::R_WASM_FUNCTION_INDEX_LEB:
585
156
  case wasm::R_WASM_GLOBAL_INDEX_LEB:
586
156
  case wasm::R_WASM_EVENT_INDEX_LEB:
587
156
    // Provisional value is function/global/event Wasm index
588
156
    assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
589
156
    return WasmIndices[RelEntry.Symbol];
590
156
  case wasm::R_WASM_FUNCTION_OFFSET_I32:
591
83
  case wasm::R_WASM_SECTION_OFFSET_I32: {
592
83
    const auto &Section =
593
83
        static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
594
83
    return Section.getSectionOffset() + RelEntry.Addend;
595
83
  }
596
215
  case wasm::R_WASM_MEMORY_ADDR_LEB:
597
215
  case wasm::R_WASM_MEMORY_ADDR_I32:
598
215
  case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
599
215
  case wasm::R_WASM_MEMORY_ADDR_SLEB: {
600
215
    // Provisional value is address of the global
601
215
    const MCSymbolWasm *Sym = resolveSymbol(*RelEntry.Symbol);
602
215
    // For undefined symbols, use zero
603
215
    if (!Sym->isDefined())
604
33
      return 0;
605
182
    const wasm::WasmDataReference &Ref = DataLocations[Sym];
606
182
    const WasmDataSegment &Segment = DataSegments[Ref.Segment];
607
182
    // Ignore overflow. LLVM allows address arithmetic to silently wrap.
608
182
    return Segment.Offset + Ref.Offset + RelEntry.Addend;
609
182
  }
610
182
  default:
611
0
    llvm_unreachable("invalid relocation type");
612
523
  }
613
523
}
614
615
static void addData(SmallVectorImpl<char> &DataBytes,
616
130
                    MCSectionWasm &DataSection) {
617
130
  LLVM_DEBUG(errs() << "addData: " << DataSection.getSectionName() << "\n");
618
130
619
130
  DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
620
130
621
343
  for (const MCFragment &Frag : DataSection) {
622
343
    if (Frag.hasInstructions())
623
0
      report_fatal_error("only data supported in data sections");
624
343
625
343
    if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
626
101
      if (Align->getValueSize() != 1)
627
0
        report_fatal_error("only byte values supported for alignment");
628
101
      // If nops are requested, use zeros, as this is the data section.
629
101
      uint8_t Value = Align->hasEmitNops() ? 
00
: Align->getValue();
630
101
      uint64_t Size =
631
101
          std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
632
101
                             DataBytes.size() + Align->getMaxBytesToEmit());
633
101
      DataBytes.resize(Size, Value);
634
242
    } else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
635
9
      int64_t NumValues;
636
9
      if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
637
9
        
llvm_unreachable0
("The fill should be an assembler constant");
638
9
      DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
639
9
                       Fill->getValue());
640
233
    } else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
641
0
      const SmallVectorImpl<char> &Contents = LEB->getContents();
642
0
      DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
643
233
    } else {
644
233
      const auto &DataFrag = cast<MCDataFragment>(Frag);
645
233
      const SmallVectorImpl<char> &Contents = DataFrag.getContents();
646
233
      DataBytes.insert(DataBytes.end(), Contents.begin(), Contents.end());
647
233
    }
648
343
  }
649
130
650
130
  LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
651
130
}
652
653
uint32_t
654
547
WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
655
547
  if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
656
32
    if (!TypeIndices.count(RelEntry.Symbol))
657
0
      report_fatal_error("symbol not found in type index space: " +
658
0
                         RelEntry.Symbol->getName());
659
32
    return TypeIndices[RelEntry.Symbol];
660
32
  }
661
515
662
515
  return RelEntry.Symbol->getIndex();
663
515
}
664
665
// Apply the portions of the relocation records that we can handle ourselves
666
// directly.
667
void WasmObjectWriter::applyRelocations(
668
304
    ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset) {
669
304
  auto &Stream = static_cast<raw_pwrite_stream &>(W.OS);
670
531
  for (const WasmRelocationEntry &RelEntry : Relocations) {
671
531
    uint64_t Offset = ContentsOffset +
672
531
                      RelEntry.FixupSection->getSectionOffset() +
673
531
                      RelEntry.Offset;
674
531
675
531
    LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
676
531
    uint32_t Value = getProvisionalValue(RelEntry);
677
531
678
531
    switch (RelEntry.Type) {
679
531
    case wasm::R_WASM_FUNCTION_INDEX_LEB:
680
334
    case wasm::R_WASM_TYPE_INDEX_LEB:
681
334
    case wasm::R_WASM_GLOBAL_INDEX_LEB:
682
334
    case wasm::R_WASM_MEMORY_ADDR_LEB:
683
334
    case wasm::R_WASM_EVENT_INDEX_LEB:
684
334
      writePatchableLEB(Stream, Value, Offset);
685
334
      break;
686
334
    case wasm::R_WASM_TABLE_INDEX_I32:
687
131
    case wasm::R_WASM_MEMORY_ADDR_I32:
688
131
    case wasm::R_WASM_FUNCTION_OFFSET_I32:
689
131
    case wasm::R_WASM_SECTION_OFFSET_I32:
690
131
      writeI32(Stream, Value, Offset);
691
131
      break;
692
131
    case wasm::R_WASM_TABLE_INDEX_SLEB:
693
66
    case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
694
66
    case wasm::R_WASM_MEMORY_ADDR_SLEB:
695
66
    case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
696
66
      writePatchableSLEB(Stream, Value, Offset);
697
66
      break;
698
66
    default:
699
0
      llvm_unreachable("invalid relocation type");
700
531
    }
701
531
  }
702
304
}
703
704
208
void WasmObjectWriter::writeTypeSection(ArrayRef<WasmSignature> Signatures) {
705
208
  if (Signatures.empty())
706
30
    return;
707
178
708
178
  SectionBookkeeping Section;
709
178
  startSection(Section, wasm::WASM_SEC_TYPE);
710
178
711
178
  encodeULEB128(Signatures.size(), W.OS);
712
178
713
263
  for (const WasmSignature &Sig : Signatures) {
714
263
    W.OS << char(wasm::WASM_TYPE_FUNC);
715
263
    encodeULEB128(Sig.Params.size(), W.OS);
716
263
    for (wasm::ValType Ty : Sig.Params)
717
94
      writeValueType(Ty);
718
263
    encodeULEB128(Sig.Returns.size(), W.OS);
719
263
    for (wasm::ValType Ty : Sig.Returns)
720
125
      writeValueType(Ty);
721
263
  }
722
178
723
178
  endSection(Section);
724
178
}
725
726
void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
727
                                          uint32_t DataSize,
728
208
                                          uint32_t NumElements) {
729
208
  if (Imports.empty())
730
0
    return;
731
208
732
208
  uint32_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
733
208
734
208
  SectionBookkeeping Section;
735
208
  startSection(Section, wasm::WASM_SEC_IMPORT);
736
208
737
208
  encodeULEB128(Imports.size(), W.OS);
738
534
  for (const wasm::WasmImport &Import : Imports) {
739
534
    writeString(Import.Module);
740
534
    writeString(Import.Field);
741
534
    W.OS << char(Import.Kind);
742
534
743
534
    switch (Import.Kind) {
744
534
    case wasm::WASM_EXTERNAL_FUNCTION:
745
91
      encodeULEB128(Import.SigIndex, W.OS);
746
91
      break;
747
534
    case wasm::WASM_EXTERNAL_GLOBAL:
748
24
      W.OS << char(Import.Global.Type);
749
24
      W.OS << char(Import.Global.Mutable ? 
121
:
03
);
750
24
      break;
751
534
    case wasm::WASM_EXTERNAL_MEMORY:
752
207
      encodeULEB128(0, W.OS);        // flags
753
207
      encodeULEB128(NumPages, W.OS); // initial
754
207
      break;
755
534
    case wasm::WASM_EXTERNAL_TABLE:
756
209
      W.OS << char(Import.Table.ElemType);
757
209
      encodeULEB128(0, W.OS);           // flags
758
209
      encodeULEB128(NumElements, W.OS); // initial
759
209
      break;
760
534
    case wasm::WASM_EXTERNAL_EVENT:
761
1
      encodeULEB128(Import.Event.Attribute, W.OS);
762
1
      encodeULEB128(Import.Event.SigIndex, W.OS);
763
1
      break;
764
534
    default:
765
0
      llvm_unreachable("unsupported import kind");
766
534
    }
767
534
  }
768
208
769
208
  endSection(Section);
770
208
}
771
772
208
void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
773
208
  if (Functions.empty())
774
30
    return;
775
178
776
178
  SectionBookkeeping Section;
777
178
  startSection(Section, wasm::WASM_SEC_FUNCTION);
778
178
779
178
  encodeULEB128(Functions.size(), W.OS);
780
178
  for (const WasmFunction &Func : Functions)
781
430
    encodeULEB128(Func.SigIndex, W.OS);
782
178
783
178
  endSection(Section);
784
178
}
785
786
209
void WasmObjectWriter::writeEventSection(ArrayRef<wasm::WasmEventType> Events) {
787
209
  if (Events.empty())
788
204
    return;
789
5
790
5
  SectionBookkeeping Section;
791
5
  startSection(Section, wasm::WASM_SEC_EVENT);
792
5
793
5
  encodeULEB128(Events.size(), W.OS);
794
5
  for (const wasm::WasmEventType &Event : Events) {
795
4
    encodeULEB128(Event.Attribute, W.OS);
796
4
    encodeULEB128(Event.SigIndex, W.OS);
797
4
  }
798
5
799
5
  endSection(Section);
800
5
}
801
802
208
void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
803
208
  if (Exports.empty())
804
208
    return;
805
0
806
0
  SectionBookkeeping Section;
807
0
  startSection(Section, wasm::WASM_SEC_EXPORT);
808
0
809
0
  encodeULEB128(Exports.size(), W.OS);
810
0
  for (const wasm::WasmExport &Export : Exports) {
811
0
    writeString(Export.Name);
812
0
    W.OS << char(Export.Kind);
813
0
    encodeULEB128(Export.Index, W.OS);
814
0
  }
815
0
816
0
  endSection(Section);
817
0
}
818
819
208
void WasmObjectWriter::writeElemSection(ArrayRef<uint32_t> TableElems) {
820
208
  if (TableElems.empty())
821
176
    return;
822
32
823
32
  SectionBookkeeping Section;
824
32
  startSection(Section, wasm::WASM_SEC_ELEM);
825
32
826
32
  encodeULEB128(1, W.OS); // number of "segments"
827
32
  encodeULEB128(0, W.OS); // the table index
828
32
829
32
  // init expr for starting offset
830
32
  W.OS << char(wasm::WASM_OPCODE_I32_CONST);
831
32
  encodeSLEB128(InitialTableOffset, W.OS);
832
32
  W.OS << char(wasm::WASM_OPCODE_END);
833
32
834
32
  encodeULEB128(TableElems.size(), W.OS);
835
32
  for (uint32_t Elem : TableElems)
836
48
    encodeULEB128(Elem, W.OS);
837
32
838
32
  endSection(Section);
839
32
}
840
841
208
void WasmObjectWriter::writeDataCountSection() {
842
208
  if (DataSegments.empty())
843
149
    return;
844
59
845
59
  SectionBookkeeping Section;
846
59
  startSection(Section, wasm::WASM_SEC_DATACOUNT);
847
59
  encodeULEB128(DataSegments.size(), W.OS);
848
59
  endSection(Section);
849
59
}
850
851
void WasmObjectWriter::writeCodeSection(const MCAssembler &Asm,
852
                                        const MCAsmLayout &Layout,
853
209
                                        ArrayRef<WasmFunction> Functions) {
854
209
  if (Functions.empty())
855
30
    return;
856
179
857
179
  SectionBookkeeping Section;
858
179
  startSection(Section, wasm::WASM_SEC_CODE);
859
179
  CodeSectionIndex = Section.Index;
860
179
861
179
  encodeULEB128(Functions.size(), W.OS);
862
179
863
430
  for (const WasmFunction &Func : Functions) {
864
430
    auto &FuncSection = static_cast<MCSectionWasm &>(Func.Sym->getSection());
865
430
866
430
    int64_t Size = 0;
867
430
    if (!Func.Sym->getSize()->evaluateAsAbsolute(Size, Layout))
868
0
      report_fatal_error(".size expression must be evaluatable");
869
430
870
430
    encodeULEB128(Size, W.OS);
871
430
    FuncSection.setSectionOffset(W.OS.tell() - Section.ContentsOffset);
872
430
    Asm.writeSectionData(W.OS, &FuncSection, Layout);
873
430
  }
874
179
875
179
  // Apply fixups.
876
179
  applyRelocations(CodeRelocations, Section.ContentsOffset);
877
179
878
179
  endSection(Section);
879
179
}
880
881
209
void WasmObjectWriter::writeDataSection() {
882
209
  if (DataSegments.empty())
883
148
    return;
884
61
885
61
  SectionBookkeeping Section;
886
61
  startSection(Section, wasm::WASM_SEC_DATA);
887
61
  DataSectionIndex = Section.Index;
888
61
889
61
  encodeULEB128(DataSegments.size(), W.OS); // count
890
61
891
130
  for (const WasmDataSegment &Segment : DataSegments) {
892
130
    encodeULEB128(Segment.InitFlags, W.OS); // flags
893
130
    if (Segment.InitFlags & wasm::WASM_SEGMENT_HAS_MEMINDEX)
894
0
      encodeULEB128(0, W.OS); // memory index
895
130
    if ((Segment.InitFlags & wasm::WASM_SEGMENT_IS_PASSIVE) == 0) {
896
130
      W.OS << char(wasm::WASM_OPCODE_I32_CONST);
897
130
      encodeSLEB128(Segment.Offset, W.OS); // offset
898
130
      W.OS << char(wasm::WASM_OPCODE_END);
899
130
    }
900
130
    encodeULEB128(Segment.Data.size(), W.OS); // size
901
130
    Segment.Section->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
902
130
    W.OS << Segment.Data; // data
903
130
  }
904
61
905
61
  // Apply fixups.
906
61
  applyRelocations(DataRelocations, Section.ContentsOffset);
907
61
908
61
  endSection(Section);
909
61
}
910
911
void WasmObjectWriter::writeRelocSection(
912
    uint32_t SectionIndex, StringRef Name,
913
461
    std::vector<WasmRelocationEntry> &Relocs) {
914
461
  // See: https://github.com/WebAssembly/tool-conventions/blob/master/Linking.md
915
461
  // for descriptions of the reloc sections.
916
461
917
461
  if (Relocs.empty())
918
322
    return;
919
139
920
139
  // First, ensure the relocations are sorted in offset order.  In general they
921
139
  // should already be sorted since `recordRelocation` is called in offset
922
139
  // order, but for the code section we combine many MC sections into single
923
139
  // wasm section, and this order is determined by the order of Asm.Symbols()
924
139
  // not the sections order.
925
139
  llvm::stable_sort(
926
518
      Relocs, [](const WasmRelocationEntry &A, const WasmRelocationEntry &B) {
927
518
        return (A.Offset + A.FixupSection->getSectionOffset()) <
928
518
               (B.Offset + B.FixupSection->getSectionOffset());
929
518
      });
930
139
931
139
  SectionBookkeeping Section;
932
139
  startCustomSection(Section, std::string("reloc.") + Name.str());
933
139
934
139
  encodeULEB128(SectionIndex, W.OS);
935
139
  encodeULEB128(Relocs.size(), W.OS);
936
531
  for (const WasmRelocationEntry &RelEntry : Relocs) {
937
531
    uint64_t Offset =
938
531
        RelEntry.Offset + RelEntry.FixupSection->getSectionOffset();
939
531
    uint32_t Index = getRelocationIndexValue(RelEntry);
940
531
941
531
    W.OS << char(RelEntry.Type);
942
531
    encodeULEB128(Offset, W.OS);
943
531
    encodeULEB128(Index, W.OS);
944
531
    if (RelEntry.hasAddend())
945
298
      encodeSLEB128(RelEntry.Addend, W.OS);
946
531
  }
947
139
948
139
  endSection(Section);
949
139
}
950
951
209
void WasmObjectWriter::writeCustomRelocSections() {
952
209
  for (const auto &Sec : CustomSections) {
953
44
    auto &Relocations = CustomSectionsRelocations[Sec.Section];
954
44
    writeRelocSection(Sec.OutputIndex, Sec.Name, Relocations);
955
44
  }
956
209
}
957
958
void WasmObjectWriter::writeLinkingMetaDataSection(
959
    ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
960
    ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
961
209
    const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats) {
962
209
  SectionBookkeeping Section;
963
209
  startCustomSection(Section, "linking");
964
209
  encodeULEB128(wasm::WasmMetadataVersion, W.OS);
965
209
966
209
  SectionBookkeeping SubSection;
967
209
  if (SymbolInfos.size() != 0) {
968
196
    startSection(SubSection, wasm::WASM_SYMBOL_TABLE);
969
196
    encodeULEB128(SymbolInfos.size(), W.OS);
970
732
    for (const wasm::WasmSymbolInfo &Sym : SymbolInfos) {
971
732
      encodeULEB128(Sym.Kind, W.OS);
972
732
      encodeULEB128(Sym.Flags, W.OS);
973
732
      switch (Sym.Kind) {
974
732
      case wasm::WASM_SYMBOL_TYPE_FUNCTION:
975
549
      case wasm::WASM_SYMBOL_TYPE_GLOBAL:
976
549
      case wasm::WASM_SYMBOL_TYPE_EVENT:
977
549
        encodeULEB128(Sym.ElementIndex, W.OS);
978
549
        if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0 ||
979
549
            
(Sym.Flags & wasm::WASM_SYMBOL_EXPLICIT_NAME) != 0108
)
980
441
          writeString(Sym.Name);
981
549
        break;
982
549
      case wasm::WASM_SYMBOL_TYPE_DATA:
983
161
        writeString(Sym.Name);
984
161
        if ((Sym.Flags & wasm::WASM_SYMBOL_UNDEFINED) == 0) {
985
134
          encodeULEB128(Sym.DataRef.Segment, W.OS);
986
134
          encodeULEB128(Sym.DataRef.Offset, W.OS);
987
134
          encodeULEB128(Sym.DataRef.Size, W.OS);
988
134
        }
989
161
        break;
990
549
      case wasm::WASM_SYMBOL_TYPE_SECTION: {
991
22
        const uint32_t SectionIndex =
992
22
            CustomSections[Sym.ElementIndex].OutputIndex;
993
22
        encodeULEB128(SectionIndex, W.OS);
994
22
        break;
995
549
      }
996
549
      default:
997
0
        llvm_unreachable("unexpected kind");
998
732
      }
999
732
    }
1000
196
    endSection(SubSection);
1001
196
  }
1002
209
1003
209
  if (DataSegments.size()) {
1004
60
    startSection(SubSection, wasm::WASM_SEGMENT_INFO);
1005
60
    encodeULEB128(DataSegments.size(), W.OS);
1006
130
    for (const WasmDataSegment &Segment : DataSegments) {
1007
130
      writeString(Segment.Name);
1008
130
      encodeULEB128(Segment.Alignment, W.OS);
1009
130
      encodeULEB128(Segment.LinkerFlags, W.OS);
1010
130
    }
1011
60
    endSection(SubSection);
1012
60
  }
1013
209
1014
209
  if (!InitFuncs.empty()) {
1015
7
    startSection(SubSection, wasm::WASM_INIT_FUNCS);
1016
7
    encodeULEB128(InitFuncs.size(), W.OS);
1017
22
    for (auto &StartFunc : InitFuncs) {
1018
22
      encodeULEB128(StartFunc.first, W.OS);  // priority
1019
22
      encodeULEB128(StartFunc.second, W.OS); // function index
1020
22
    }
1021
7
    endSection(SubSection);
1022
7
  }
1023
209
1024
209
  if (Comdats.size()) {
1025
6
    startSection(SubSection, wasm::WASM_COMDAT_INFO);
1026
6
    encodeULEB128(Comdats.size(), W.OS);
1027
7
    for (const auto &C : Comdats) {
1028
7
      writeString(C.first);
1029
7
      encodeULEB128(0, W.OS); // flags for future use
1030
7
      encodeULEB128(C.second.size(), W.OS);
1031
13
      for (const WasmComdatEntry &Entry : C.second) {
1032
13
        encodeULEB128(Entry.Kind, W.OS);
1033
13
        encodeULEB128(Entry.Index, W.OS);
1034
13
      }
1035
7
    }
1036
6
    endSection(SubSection);
1037
6
  }
1038
209
1039
209
  endSection(Section);
1040
209
}
1041
1042
void WasmObjectWriter::writeCustomSection(WasmCustomSection &CustomSection,
1043
                                          const MCAssembler &Asm,
1044
65
                                          const MCAsmLayout &Layout) {
1045
65
  SectionBookkeeping Section;
1046
65
  auto *Sec = CustomSection.Section;
1047
65
  startCustomSection(Section, CustomSection.Name);
1048
65
1049
65
  Sec->setSectionOffset(W.OS.tell() - Section.ContentsOffset);
1050
65
  Asm.writeSectionData(W.OS, Sec, Layout);
1051
65
1052
65
  CustomSection.OutputContentsOffset = Section.ContentsOffset;
1053
65
  CustomSection.OutputIndex = Section.Index;
1054
65
1055
65
  endSection(Section);
1056
65
1057
65
  // Apply fixups.
1058
65
  auto &Relocations = CustomSectionsRelocations[CustomSection.Section];
1059
65
  applyRelocations(Relocations, CustomSection.OutputContentsOffset);
1060
65
}
1061
1062
520
uint32_t WasmObjectWriter::getFunctionType(const MCSymbolWasm &Symbol) {
1063
520
  assert(Symbol.isFunction());
1064
520
  assert(TypeIndices.count(&Symbol));
1065
520
  return TypeIndices[&Symbol];
1066
520
}
1067
1068
5
uint32_t WasmObjectWriter::getEventType(const MCSymbolWasm &Symbol) {
1069
5
  assert(Symbol.isEvent());
1070
5
  assert(TypeIndices.count(&Symbol));
1071
5
  return TypeIndices[&Symbol];
1072
5
}
1073
1074
592
void WasmObjectWriter::registerFunctionType(const MCSymbolWasm &Symbol) {
1075
592
  assert(Symbol.isFunction());
1076
592
1077
592
  WasmSignature S;
1078
592
  const MCSymbolWasm *ResolvedSym = resolveSymbol(Symbol);
1079
592
  if (auto *Sig = ResolvedSym->getSignature()) {
1080
592
    S.Returns = Sig->Returns;
1081
592
    S.Params = Sig->Params;
1082
592
  }
1083
592
1084
592
  auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1085
592
  if (Pair.second)
1086
260
    Signatures.push_back(S);
1087
592
  TypeIndices[&Symbol] = Pair.first->second;
1088
592
1089
592
  LLVM_DEBUG(dbgs() << "registerFunctionType: " << Symbol
1090
592
                    << " new:" << Pair.second << "\n");
1091
592
  LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1092
592
}
1093
1094
5
void WasmObjectWriter::registerEventType(const MCSymbolWasm &Symbol) {
1095
5
  assert(Symbol.isEvent());
1096
5
1097
5
  // TODO Currently we don't generate imported exceptions, but if we do, we
1098
5
  // should have a way of infering types of imported exceptions.
1099
5
  WasmSignature S;
1100
5
  if (auto *Sig = Symbol.getSignature()) {
1101
5
    S.Returns = Sig->Returns;
1102
5
    S.Params = Sig->Params;
1103
5
  }
1104
5
1105
5
  auto Pair = SignatureIndices.insert(std::make_pair(S, Signatures.size()));
1106
5
  if (Pair.second)
1107
3
    Signatures.push_back(S);
1108
5
  TypeIndices[&Symbol] = Pair.first->second;
1109
5
1110
5
  LLVM_DEBUG(dbgs() << "registerEventType: " << Symbol << " new:" << Pair.second
1111
5
                    << "\n");
1112
5
  LLVM_DEBUG(dbgs() << "  -> type index: " << Pair.first->second << "\n");
1113
5
}
1114
1115
2.34k
static bool isInSymtab(const MCSymbolWasm &Sym) {
1116
2.34k
  if (Sym.isUsedInReloc())
1117
354
    return true;
1118
1.99k
1119
1.99k
  if (Sym.isComdat() && 
!Sym.isDefined()7
)
1120
5
    return false;
1121
1.99k
1122
1.99k
  if (Sym.isTemporary() && 
Sym.getName().empty()655
)
1123
560
    return false;
1124
1.43k
1125
1.43k
  if (Sym.isTemporary() && 
Sym.isData()95
&&
!Sym.getSize()86
)
1126
70
    return false;
1127
1.36k
1128
1.36k
  if (Sym.isSection())
1129
823
    return false;
1130
537
1131
537
  return true;
1132
537
}
1133
1134
uint64_t WasmObjectWriter::writeObject(MCAssembler &Asm,
1135
207
                                       const MCAsmLayout &Layout) {
1136
207
  uint64_t StartOffset = W.OS.tell();
1137
207
1138
207
  LLVM_DEBUG(dbgs() << "WasmObjectWriter::writeObject\n");
1139
207
1140
207
  // Collect information from the available symbols.
1141
207
  SmallVector<WasmFunction, 4> Functions;
1142
207
  SmallVector<uint32_t, 4> TableElems;
1143
207
  SmallVector<wasm::WasmImport, 4> Imports;
1144
207
  SmallVector<wasm::WasmExport, 4> Exports;
1145
207
  SmallVector<wasm::WasmEventType, 1> Events;
1146
207
  SmallVector<wasm::WasmSymbolInfo, 4> SymbolInfos;
1147
207
  SmallVector<std::pair<uint16_t, uint32_t>, 2> InitFuncs;
1148
207
  std::map<StringRef, std::vector<WasmComdatEntry>> Comdats;
1149
207
  uint32_t DataSize = 0;
1150
207
1151
207
  // For now, always emit the memory import, since loads and stores are not
1152
207
  // valid without it. In the future, we could perhaps be more clever and omit
1153
207
  // it if there are no loads or stores.
1154
207
  wasm::WasmImport MemImport;
1155
207
  MemImport.Module = "env";
1156
207
  MemImport.Field = "__linear_memory";
1157
207
  MemImport.Kind = wasm::WASM_EXTERNAL_MEMORY;
1158
207
  Imports.push_back(MemImport);
1159
207
1160
207
  // For now, always emit the table section, since indirect calls are not
1161
207
  // valid without it. In the future, we could perhaps be more clever and omit
1162
207
  // it if there are no indirect calls.
1163
207
  wasm::WasmImport TableImport;
1164
207
  TableImport.Module = "env";
1165
207
  TableImport.Field = "__indirect_function_table";
1166
207
  TableImport.Kind = wasm::WASM_EXTERNAL_TABLE;
1167
207
  TableImport.Table.ElemType = wasm::WASM_TYPE_FUNCREF;
1168
207
  Imports.push_back(TableImport);
1169
207
1170
207
  // Populate SignatureIndices, and Imports and WasmIndices for undefined
1171
207
  // symbols.  This must be done before populating WasmIndices for defined
1172
207
  // symbols.
1173
2.15k
  for (const MCSymbol &S : Asm.symbols()) {
1174
2.15k
    const auto &WS = static_cast<const MCSymbolWasm &>(S);
1175
2.15k
1176
2.15k
    // Register types for all functions, including those with private linkage
1177
2.15k
    // (because wasm always needs a type signature).
1178
2.15k
    if (WS.isFunction())
1179
543
      registerFunctionType(WS);
1180
2.15k
1181
2.15k
    if (WS.isEvent())
1182
5
      registerEventType(WS);
1183
2.15k
1184
2.15k
    if (WS.isTemporary())
1185
627
      continue;
1186
1.52k
1187
1.52k
    // If the symbol is not defined in this translation unit, import it.
1188
1.52k
    if (!WS.isDefined() && 
!WS.isComdat()140
) {
1189
135
      if (WS.isFunction()) {
1190
91
        wasm::WasmImport Import;
1191
91
        Import.Module = WS.getImportModule();
1192
91
        Import.Field = WS.getImportName();
1193
91
        Import.Kind = wasm::WASM_EXTERNAL_FUNCTION;
1194
91
        Import.SigIndex = getFunctionType(WS);
1195
91
        Imports.push_back(Import);
1196
91
        assert(WasmIndices.count(&WS) == 0);
1197
91
        WasmIndices[&WS] = NumFunctionImports++;
1198
91
      } else 
if (44
WS.isGlobal()44
) {
1199
16
        if (WS.isWeak())
1200
0
          report_fatal_error("undefined global symbol cannot be weak");
1201
16
1202
16
        wasm::WasmImport Import;
1203
16
        Import.Field = WS.getImportName();
1204
16
        Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1205
16
        Import.Module = WS.getImportModule();
1206
16
        Import.Global = WS.getGlobalType();
1207
16
        Imports.push_back(Import);
1208
16
        assert(WasmIndices.count(&WS) == 0);
1209
16
        WasmIndices[&WS] = NumGlobalImports++;
1210
28
      } else if (WS.isEvent()) {
1211
1
        if (WS.isWeak())
1212
0
          report_fatal_error("undefined event symbol cannot be weak");
1213
1
1214
1
        wasm::WasmImport Import;
1215
1
        Import.Module = WS.getImportModule();
1216
1
        Import.Field = WS.getImportName();
1217
1
        Import.Kind = wasm::WASM_EXTERNAL_EVENT;
1218
1
        Import.Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1219
1
        Import.Event.SigIndex = getEventType(WS);
1220
1
        Imports.push_back(Import);
1221
1
        assert(WasmIndices.count(&WS) == 0);
1222
1
        WasmIndices[&WS] = NumEventImports++;
1223
1
      }
1224
135
    }
1225
1.52k
  }
1226
207
1227
207
  // Add imports for GOT globals
1228
2.15k
  
for (const MCSymbol &S : Asm.symbols())207
{
1229
2.15k
    const auto &WS = static_cast<const MCSymbolWasm &>(S);
1230
2.15k
    if (WS.isUsedInGOT()) {
1231
8
      wasm::WasmImport Import;
1232
8
      if (WS.isFunction())
1233
2
        Import.Module = "GOT.func";
1234
6
      else
1235
6
        Import.Module = "GOT.mem";
1236
8
      Import.Field = WS.getName();
1237
8
      Import.Kind = wasm::WASM_EXTERNAL_GLOBAL;
1238
8
      Import.Global = {wasm::WASM_TYPE_I32, true};
1239
8
      Imports.push_back(Import);
1240
8
      assert(GOTIndices.count(&WS) == 0);
1241
8
      GOTIndices[&WS] = NumGlobalImports++;
1242
8
    }
1243
2.15k
  }
1244
207
1245
207
  // Populate DataSegments and CustomSections, which must be done before
1246
207
  // populating DataLocations.
1247
843
  for (MCSection &Sec : Asm) {
1248
843
    auto &Section = static_cast<MCSectionWasm &>(Sec);
1249
843
    StringRef SectionName = Section.getSectionName();
1250
843
1251
843
    // .init_array sections are handled specially elsewhere.
1252
843
    if (SectionName.startswith(".init_array"))
1253
12
      continue;
1254
831
1255
831
    // Code is handled separately
1256
831
    if (Section.getKind().isText())
1257
636
      continue;
1258
195
1259
195
    if (Section.isWasmData()) {
1260
130
      uint32_t SegmentIndex = DataSegments.size();
1261
130
      DataSize = alignTo(DataSize, Section.getAlignment());
1262
130
      DataSegments.emplace_back();
1263
130
      WasmDataSegment &Segment = DataSegments.back();
1264
130
      Segment.Name = SectionName;
1265
130
      Segment.InitFlags =
1266
130
          Section.getPassive() ? 
(uint32_t)wasm::WASM_SEGMENT_IS_PASSIVE0
: 0;
1267
130
      Segment.Offset = DataSize;
1268
130
      Segment.Section = &Section;
1269
130
      addData(Segment.Data, Section);
1270
130
      Segment.Alignment = Log2_32(Section.getAlignment());
1271
130
      Segment.LinkerFlags = 0;
1272
130
      DataSize += Segment.Data.size();
1273
130
      Section.setSegmentIndex(SegmentIndex);
1274
130
1275
130
      if (const MCSymbolWasm *C = Section.getGroup()) {
1276
4
        Comdats[C->getName()].emplace_back(
1277
4
            WasmComdatEntry{wasm::WASM_COMDAT_DATA, SegmentIndex});
1278
4
      }
1279
130
    } else {
1280
65
      // Create custom sections
1281
65
      assert(Sec.getKind().isMetadata());
1282
65
1283
65
      StringRef Name = SectionName;
1284
65
1285
65
      // For user-defined custom sections, strip the prefix
1286
65
      if (Name.startswith(".custom_section."))
1287
28
        Name = Name.substr(strlen(".custom_section."));
1288
65
1289
65
      MCSymbol *Begin = Sec.getBeginSymbol();
1290
65
      if (Begin) {
1291
65
        WasmIndices[cast<MCSymbolWasm>(Begin)] = CustomSections.size();
1292
65
        if (SectionName != Begin->getName())
1293
0
          report_fatal_error("section name and begin symbol should match: " +
1294
0
                             Twine(SectionName));
1295
65
      }
1296
65
1297
65
      // Separate out the producers and target features sections
1298
65
      if (Name == "producers") {
1299
8
        ProducersSection = llvm::make_unique<WasmCustomSection>(Name, &Section);
1300
8
        continue;
1301
8
      }
1302
57
      if (Name == "target_features") {
1303
13
        TargetFeaturesSection =
1304
13
            llvm::make_unique<WasmCustomSection>(Name, &Section);
1305
13
        continue;
1306
13
      }
1307
44
1308
44
      CustomSections.emplace_back(Name, &Section);
1309
44
    }
1310
195
  }
1311
207
1312
207
  // Populate WasmIndices and DataLocations for defined symbols.
1313
2.15k
  
for (const MCSymbol &S : Asm.symbols())207
{
1314
2.15k
    // Ignore unnamed temporary symbols, which aren't ever exported, imported,
1315
2.15k
    // or used in relocations.
1316
2.15k
    if (S.isTemporary() && 
S.getName().empty()627
)
1317
559
      continue;
1318
1.59k
1319
1.59k
    const auto &WS = static_cast<const MCSymbolWasm &>(S);
1320
1.59k
    LLVM_DEBUG(
1321
1.59k
        dbgs() << "MCSymbol: " << toString(WS.getType()) << " '" << S << "'"
1322
1.59k
               << " isDefined=" << S.isDefined() << " isExternal="
1323
1.59k
               << S.isExternal() << " isTemporary=" << S.isTemporary()
1324
1.59k
               << " isWeak=" << WS.isWeak() << " isHidden=" << WS.isHidden()
1325
1.59k
               << " isVariable=" << WS.isVariable() << "\n");
1326
1.59k
1327
1.59k
    if (WS.isVariable())
1328
8
      continue;
1329
1.58k
    if (WS.isComdat() && 
!WS.isDefined()7
)
1330
5
      continue;
1331
1.58k
1332
1.58k
    if (WS.isFunction()) {
1333
519
      unsigned Index;
1334
519
      if (WS.isDefined()) {
1335
430
        if (WS.getOffset() != 0)
1336
0
          report_fatal_error(
1337
0
              "function sections must contain one function each");
1338
430
1339
430
        if (WS.getSize() == nullptr)
1340
0
          report_fatal_error(
1341
0
              "function symbols must have a size set with .size");
1342
430
1343
430
        // A definition. Write out the function body.
1344
430
        Index = NumFunctionImports + Functions.size();
1345
430
        WasmFunction Func;
1346
430
        Func.SigIndex = getFunctionType(WS);
1347
430
        Func.Sym = &WS;
1348
430
        WasmIndices[&WS] = Index;
1349
430
        Functions.push_back(Func);
1350
430
1351
430
        auto &Section = static_cast<MCSectionWasm &>(WS.getSection());
1352
430
        if (const MCSymbolWasm *C = Section.getGroup()) {
1353
9
          Comdats[C->getName()].emplace_back(
1354
9
              WasmComdatEntry{wasm::WASM_COMDAT_FUNCTION, Index});
1355
9
        }
1356
430
      } else {
1357
89
        // An import; the index was assigned above.
1358
89
        Index = WasmIndices.find(&WS)->second;
1359
89
      }
1360
519
1361
519
      LLVM_DEBUG(dbgs() << "  -> function index: " << Index << "\n");
1362
519
1363
1.06k
    } else if (WS.isData()) {
1364
195
      if (!isInSymtab(WS))
1365
35
        continue;
1366
160
1367
160
      if (!WS.isDefined()) {
1368
27
        LLVM_DEBUG(dbgs() << "  -> segment index: -1"
1369
27
                          << "\n");
1370
27
        continue;
1371
27
      }
1372
133
1373
133
      if (!WS.getSize())
1374
0
        report_fatal_error("data symbols must have a size set with .size: " +
1375
0
                           WS.getName());
1376
133
1377
133
      int64_t Size = 0;
1378
133
      if (!WS.getSize()->evaluateAsAbsolute(Size, Layout))
1379
0
        report_fatal_error(".size expression must be evaluatable");
1380
133
1381
133
      auto &DataSection = static_cast<MCSectionWasm &>(WS.getSection());
1382
133
      assert(DataSection.isWasmData());
1383
133
1384
133
      // For each data symbol, export it in the symtab as a reference to the
1385
133
      // corresponding Wasm data segment.
1386
133
      wasm::WasmDataReference Ref = wasm::WasmDataReference{
1387
133
          DataSection.getSegmentIndex(),
1388
133
          static_cast<uint32_t>(Layout.getSymbolOffset(WS)),
1389
133
          static_cast<uint32_t>(Size)};
1390
133
      DataLocations[&WS] = Ref;
1391
133
      LLVM_DEBUG(dbgs() << "  -> segment index: " << Ref.Segment << "\n");
1392
133
1393
868
    } else if (WS.isGlobal()) {
1394
16
      // A "true" Wasm global (currently just __stack_pointer)
1395
16
      if (WS.isDefined())
1396
0
        report_fatal_error("don't yet support defined globals");
1397
16
1398
16
      // An import; the index was assigned above
1399
16
      LLVM_DEBUG(dbgs() << "  -> global index: "
1400
16
                        << WasmIndices.find(&WS)->second << "\n");
1401
16
1402
852
    } else if (WS.isEvent()) {
1403
5
      // C++ exception symbol (__cpp_exception)
1404
5
      unsigned Index;
1405
5
      if (WS.isDefined()) {
1406
4
        Index = NumEventImports + Events.size();
1407
4
        wasm::WasmEventType Event;
1408
4
        Event.SigIndex = getEventType(WS);
1409
4
        Event.Attribute = wasm::WASM_EVENT_ATTRIBUTE_EXCEPTION;
1410
4
        assert(WasmIndices.count(&WS) == 0);
1411
4
        WasmIndices[&WS] = Index;
1412
4
        Events.push_back(Event);
1413
4
      } else {
1414
1
        // An import; the index was assigned above.
1415
1
        assert(WasmIndices.count(&WS) > 0);
1416
1
      }
1417
5
      LLVM_DEBUG(dbgs() << "  -> event index: " << WasmIndices.find(&WS)->second
1418
5
                        << "\n");
1419
5
1420
847
    } else {
1421
847
      assert(WS.isSection());
1422
847
    }
1423
1.58k
  }
1424
207
1425
207
  // Populate WasmIndices and DataLocations for aliased symbols.  We need to
1426
207
  // process these in a separate pass because we need to have processed the
1427
207
  // target of the alias before the alias itself and the symbols are not
1428
207
  // necessarily ordered in this way.
1429
2.15k
  
for (const MCSymbol &S : Asm.symbols())207
{
1430
2.15k
    if (!S.isVariable())
1431
2.14k
      continue;
1432
8
1433
8
    assert(S.isDefined());
1434
8
1435
8
    // Find the target symbol of this weak alias and export that index
1436
8
    const auto &WS = static_cast<const MCSymbolWasm &>(S);
1437
8
    const MCSymbolWasm *ResolvedSym = resolveSymbol(WS);
1438
8
    LLVM_DEBUG(dbgs() << WS.getName() << ": weak alias of '" << *ResolvedSym
1439
8
                      << "'\n");
1440
8
1441
8
    if (ResolvedSym->isFunction()) {
1442
7
      assert(WasmIndices.count(ResolvedSym) > 0);
1443
7
      uint32_t WasmIndex = WasmIndices.find(ResolvedSym)->second;
1444
7
      assert(WasmIndices.count(&WS) == 0);
1445
7
      WasmIndices[&WS] = WasmIndex;
1446
7
      LLVM_DEBUG(dbgs() << "  -> index:" << WasmIndex << "\n");
1447
7
    } else 
if (1
ResolvedSym->isData()1
) {
1448
1
      assert(DataLocations.count(ResolvedSym) > 0);
1449
1
      const wasm::WasmDataReference &Ref =
1450
1
          DataLocations.find(ResolvedSym)->second;
1451
1
      DataLocations[&WS] = Ref;
1452
1
      LLVM_DEBUG(dbgs() << "  -> index:" << Ref.Segment << "\n");
1453
1
    } else {
1454
0
      report_fatal_error("don't yet support global/event aliases");
1455
0
    }
1456
8
  }
1457
207
1458
207
  // Finally, populate the symbol table itself, in its "natural" order.
1459
2.15k
  
for (const MCSymbol &S : Asm.symbols())207
{
1460
2.15k
    const auto &WS = static_cast<const MCSymbolWasm &>(S);
1461
2.15k
    if (!isInSymtab(WS)) {
1462
1.42k
      WS.setIndex(InvalidIndex);
1463
1.42k
      continue;
1464
1.42k
    }
1465
729
    LLVM_DEBUG(dbgs() << "adding to symtab: " << WS << "\n");
1466
729
1467
729
    uint32_t Flags = 0;
1468
729
    if (WS.isWeak())
1469
37
      Flags |= wasm::WASM_SYMBOL_BINDING_WEAK;
1470
729
    if (WS.isHidden())
1471
136
      Flags |= wasm::WASM_SYMBOL_VISIBILITY_HIDDEN;
1472
729
    if (!WS.isExternal() && 
WS.isDefined()206
)
1473
87
      Flags |= wasm::WASM_SYMBOL_BINDING_LOCAL;
1474
729
    if (WS.isUndefined())
1475
135
      Flags |= wasm::WASM_SYMBOL_UNDEFINED;
1476
729
    if (WS.isExported())
1477
4
      Flags |= wasm::WASM_SYMBOL_EXPORTED;
1478
729
    if (WS.getName() != WS.getImportName())
1479
3
      Flags |= wasm::WASM_SYMBOL_EXPLICIT_NAME;
1480
729
1481
729
    wasm::WasmSymbolInfo Info;
1482
729
    Info.Name = WS.getName();
1483
729
    Info.Kind = WS.getType();
1484
729
    Info.Flags = Flags;
1485
729
    if (!WS.isData()) {
1486
569
      assert(WasmIndices.count(&WS) > 0);
1487
569
      Info.ElementIndex = WasmIndices.find(&WS)->second;
1488
569
    } else 
if (160
WS.isDefined()160
) {
1489
134
      assert(DataLocations.count(&WS) > 0);
1490
134
      Info.DataRef = DataLocations.find(&WS)->second;
1491
134
    }
1492
729
    WS.setIndex(SymbolInfos.size());
1493
729
    SymbolInfos.emplace_back(Info);
1494
729
  }
1495
207
1496
207
  {
1497
442
    auto HandleReloc = [&](const WasmRelocationEntry &Rel) {
1498
442
      // Functions referenced by a relocation need to put in the table.  This is
1499
442
      // purely to make the object file's provisional values readable, and is
1500
442
      // ignored by the linker, which re-calculates the relocations itself.
1501
442
      if (Rel.Type != wasm::R_WASM_TABLE_INDEX_I32 &&
1502
442
          
Rel.Type != wasm::R_WASM_TABLE_INDEX_SLEB420
)
1503
391
        return;
1504
51
      assert(Rel.Symbol->isFunction());
1505
51
      const MCSymbolWasm &WS = *resolveSymbol(*Rel.Symbol);
1506
51
      uint32_t FunctionIndex = WasmIndices.find(&WS)->second;
1507
51
      uint32_t TableIndex = TableElems.size() + InitialTableOffset;
1508
51
      if (TableIndices.try_emplace(&WS, TableIndex).second) {
1509
48
        LLVM_DEBUG(dbgs() << "  -> adding " << WS.getName()
1510
48
                          << " to table: " << TableIndex << "\n");
1511
48
        TableElems.push_back(FunctionIndex);
1512
48
        registerFunctionType(WS);
1513
48
      }
1514
51
    };
1515
207
1516
207
    for (const WasmRelocationEntry &RelEntry : CodeRelocations)
1517
400
      HandleReloc(RelEntry);
1518
207
    for (const WasmRelocationEntry &RelEntry : DataRelocations)
1519
42
      HandleReloc(RelEntry);
1520
207
  }
1521
207
1522
207
  // Translate .init_array section contents into start functions.
1523
843
  for (const MCSection &S : Asm) {
1524
843
    const auto &WS = static_cast<const MCSectionWasm &>(S);
1525
843
    if (WS.getSectionName().startswith(".fini_array"))
1526
0
      report_fatal_error(".fini_array sections are unsupported");
1527
843
    if (!WS.getSectionName().startswith(".init_array"))
1528
833
      continue;
1529
10
    if (WS.getFragmentList().empty())
1530
0
      continue;
1531
10
1532
10
    // init_array is expected to contain a single non-empty data fragment
1533
10
    if (WS.getFragmentList().size() != 3)
1534
0
      report_fatal_error("only one .init_array section fragment supported");
1535
10
1536
10
    auto IT = WS.begin();
1537
10
    const MCFragment &EmptyFrag = *IT;
1538
10
    if (EmptyFrag.getKind() != MCFragment::FT_Data)
1539
0
      report_fatal_error(".init_array section should be aligned");
1540
10
1541
10
    IT = std::next(IT);
1542
10
    const MCFragment &AlignFrag = *IT;
1543
10
    if (AlignFrag.getKind() != MCFragment::FT_Align)
1544
0
      report_fatal_error(".init_array section should be aligned");
1545
10
    if (cast<MCAlignFragment>(AlignFrag).getAlignment() != (is64Bit() ? 
80
: 4))
1546
0
      report_fatal_error(".init_array section should be aligned for pointers");
1547
10
1548
10
    const MCFragment &Frag = *std::next(IT);
1549
12
    if (
Frag.hasInstructions()10
|| Frag.getKind() != MCFragment::FT_Data)
1550
0
      report_fatal_error("only data supported in .init_array section");
1551
10
1552
10
    uint16_t Priority = UINT16_MAX;
1553
10
    unsigned PrefixLength = strlen(".init_array");
1554
10
    if (WS.getSectionName().size() > PrefixLength) {
1555
9
      if (WS.getSectionName()[PrefixLength] != '.')
1556
0
        report_fatal_error(
1557
0
            ".init_array section priority should start with '.'");
1558
9
      if (WS.getSectionName()
1559
9
              .substr(PrefixLength + 1)
1560
9
              .getAsInteger(10, Priority))
1561
0
        report_fatal_error("invalid .init_array section priority");
1562
10
    }
1563
10
    const auto &DataFrag = cast<MCDataFragment>(Frag);
1564
10
    const SmallVectorImpl<char> &Contents = DataFrag.getContents();
1565
10
    for (const uint8_t *
1566
10
             P = (const uint8_t *)Contents.data(),
1567
10
            *End = (const uint8_t *)Contents.data() + Contents.size();
1568
98
         P != End; 
++P88
) {
1569
88
      if (*P != 0)
1570
0
        report_fatal_error("non-symbolic data in .init_array section");
1571
88
    }
1572
22
    
for (const MCFixup &Fixup : DataFrag.getFixups())10
{
1573
22
      assert(Fixup.getKind() ==
1574
22
             MCFixup::getKindForSize(is64Bit() ? 8 : 4, false));
1575
22
      const MCExpr *Expr = Fixup.getValue();
1576
22
      auto *SymRef = dyn_cast<MCSymbolRefExpr>(Expr);
1577
22
      if (!SymRef)
1578
0
        report_fatal_error("fixups in .init_array should be symbol references");
1579
22
      const auto &TargetSym = cast<const MCSymbolWasm>(SymRef->getSymbol());
1580
22
      if (TargetSym.getIndex() == InvalidIndex)
1581
0
        report_fatal_error("symbols in .init_array should exist in symbtab");
1582
22
      if (!TargetSym.isFunction())
1583
0
        report_fatal_error("symbols in .init_array should be for functions");
1584
22
      InitFuncs.push_back(
1585
22
          std::make_pair(Priority, TargetSym.getIndex()));
1586
22
    }
1587
10
  }
1588
207
1589
207
  // Write out the Wasm header.
1590
207
  writeHeader(Asm);
1591
207
1592
207
  writeTypeSection(Signatures);
1593
207
  writeImportSection(Imports, DataSize, TableElems.size());
1594
207
  writeFunctionSection(Functions);
1595
207
  // Skip the "table" section; we import the table instead.
1596
207
  // Skip the "memory" section; we import the memory instead.
1597
207
  writeEventSection(Events);
1598
207
  writeExportSection(Exports);
1599
207
  writeElemSection(TableElems);
1600
207
  writeDataCountSection();
1601
207
  writeCodeSection(Asm, Layout, Functions);
1602
207
  writeDataSection();
1603
207
  for (auto &CustomSection : CustomSections)
1604
44
    writeCustomSection(CustomSection, Asm, Layout);
1605
207
  writeLinkingMetaDataSection(SymbolInfos, InitFuncs, Comdats);
1606
207
  writeRelocSection(CodeSectionIndex, "CODE", CodeRelocations);
1607
207
  writeRelocSection(DataSectionIndex, "DATA", DataRelocations);
1608
207
  writeCustomRelocSections();
1609
207
  if (ProducersSection)
1610
8
    writeCustomSection(*ProducersSection, Asm, Layout);
1611
207
  if (TargetFeaturesSection)
1612
13
    writeCustomSection(*TargetFeaturesSection, Asm, Layout);
1613
207
1614
207
  // TODO: Translate the .comment section to the output.
1615
207
  return W.OS.tell() - StartOffset;
1616
207
}
1617
1618
std::unique_ptr<MCObjectWriter>
1619
llvm::createWasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
1620
443
                             raw_pwrite_stream &OS) {
1621
443
  return llvm::make_unique<WasmObjectWriter>(std::move(MOTW), OS);
1622
443
}