forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWasmObjectWriter.cpp
1958 lines (1693 loc) · 69.4 KB
/
WasmObjectWriter.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===- lib/MC/WasmObjectWriter.cpp - Wasm File Writer ---------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements Wasm object file writer information.
//
//===----------------------------------------------------------------------===//
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/BinaryFormat/Wasm.h"
#include "llvm/BinaryFormat/WasmTraits.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/MC/MCAsmBackend.h"
#include "llvm/MC/MCAsmLayout.h"
#include "llvm/MC/MCAssembler.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCExpr.h"
#include "llvm/MC/MCFixupKindInfo.h"
#include "llvm/MC/MCObjectWriter.h"
#include "llvm/MC/MCSectionWasm.h"
#include "llvm/MC/MCSymbolWasm.h"
#include "llvm/MC/MCValue.h"
#include "llvm/MC/MCWasmObjectWriter.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/EndianStream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/LEB128.h"
#include "llvm/Support/StringSaver.h"
#include <vector>
using namespace llvm;
#define DEBUG_TYPE "mc"
namespace {
// When we create the indirect function table we start at 1, so that there is
// and empty slot at 0 and therefore calling a null function pointer will trap.
static const uint32_t InitialTableOffset = 1;
// For patching purposes, we need to remember where each section starts, both
// for patching up the section size field, and for patching up references to
// locations within the section.
struct SectionBookkeeping {
// Where the size of the section is written.
uint64_t SizeOffset;
// Where the section header ends (without custom section name).
uint64_t PayloadOffset;
// Where the contents of the section starts.
uint64_t ContentsOffset;
uint32_t Index;
};
// A wasm data segment. A wasm binary contains only a single data section
// but that can contain many segments, each with their own virtual location
// in memory. Each MCSection data created by llvm is modeled as its own
// wasm data segment.
struct WasmDataSegment {
MCSectionWasm *Section;
StringRef Name;
uint32_t InitFlags;
uint64_t Offset;
uint32_t Alignment;
uint32_t LinkingFlags;
SmallVector<char, 4> Data;
};
// A wasm function to be written into the function section.
struct WasmFunction {
uint32_t SigIndex;
const MCSymbolWasm *Sym;
};
// A wasm global to be written into the global section.
struct WasmGlobal {
wasm::WasmGlobalType Type;
uint64_t InitialValue;
};
// Information about a single item which is part of a COMDAT. For each data
// segment or function which is in the COMDAT, there is a corresponding
// WasmComdatEntry.
struct WasmComdatEntry {
unsigned Kind;
uint32_t Index;
};
// Information about a single relocation.
struct WasmRelocationEntry {
uint64_t Offset; // Where is the relocation.
const MCSymbolWasm *Symbol; // The symbol to relocate with.
int64_t Addend; // A value to add to the symbol.
unsigned Type; // The type of the relocation.
const MCSectionWasm *FixupSection; // The section the relocation is targeting.
WasmRelocationEntry(uint64_t Offset, const MCSymbolWasm *Symbol,
int64_t Addend, unsigned Type,
const MCSectionWasm *FixupSection)
: Offset(Offset), Symbol(Symbol), Addend(Addend), Type(Type),
FixupSection(FixupSection) {}
bool hasAddend() const { return wasm::relocTypeHasAddend(Type); }
void print(raw_ostream &Out) const {
Out << wasm::relocTypetoString(Type) << " Off=" << Offset
<< ", Sym=" << *Symbol << ", Addend=" << Addend
<< ", FixupSection=" << FixupSection->getName();
}
#if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
#endif
};
static const uint32_t InvalidIndex = -1;
struct WasmCustomSection {
StringRef Name;
MCSectionWasm *Section;
uint32_t OutputContentsOffset = 0;
uint32_t OutputIndex = InvalidIndex;
WasmCustomSection(StringRef Name, MCSectionWasm *Section)
: Name(Name), Section(Section) {}
};
#if !defined(NDEBUG)
raw_ostream &operator<<(raw_ostream &OS, const WasmRelocationEntry &Rel) {
Rel.print(OS);
return OS;
}
#endif
// Write X as an (unsigned) LEB value at offset Offset in Stream, padded
// to allow patching.
template <int W>
void writePatchableLEB(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
uint8_t Buffer[W];
unsigned SizeLen = encodeULEB128(X, Buffer, W);
assert(SizeLen == W);
Stream.pwrite((char *)Buffer, SizeLen, Offset);
}
// Write X as an signed LEB value at offset Offset in Stream, padded
// to allow patching.
template <int W>
void writePatchableSLEB(raw_pwrite_stream &Stream, int64_t X, uint64_t Offset) {
uint8_t Buffer[W];
unsigned SizeLen = encodeSLEB128(X, Buffer, W);
assert(SizeLen == W);
Stream.pwrite((char *)Buffer, SizeLen, Offset);
}
// Write X as a plain integer value at offset Offset in Stream.
static void patchI32(raw_pwrite_stream &Stream, uint32_t X, uint64_t Offset) {
uint8_t Buffer[4];
support::endian::write32le(Buffer, X);
Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
}
static void patchI64(raw_pwrite_stream &Stream, uint64_t X, uint64_t Offset) {
uint8_t Buffer[8];
support::endian::write64le(Buffer, X);
Stream.pwrite((char *)Buffer, sizeof(Buffer), Offset);
}
bool isDwoSection(const MCSection &Sec) {
return Sec.getName().endswith(".dwo");
}
class WasmObjectWriter : public MCObjectWriter {
support::endian::Writer *W;
/// The target specific Wasm writer instance.
std::unique_ptr<MCWasmObjectTargetWriter> TargetObjectWriter;
// Relocations for fixing up references in the code section.
std::vector<WasmRelocationEntry> CodeRelocations;
// Relocations for fixing up references in the data section.
std::vector<WasmRelocationEntry> DataRelocations;
// Index values to use for fixing up call_indirect type indices.
// Maps function symbols to the index of the type of the function
DenseMap<const MCSymbolWasm *, uint32_t> TypeIndices;
// Maps function symbols to the table element index space. Used
// for TABLE_INDEX relocation types (i.e. address taken functions).
DenseMap<const MCSymbolWasm *, uint32_t> TableIndices;
// Maps function/global/table symbols to the
// function/global/table/tag/section index space.
DenseMap<const MCSymbolWasm *, uint32_t> WasmIndices;
DenseMap<const MCSymbolWasm *, uint32_t> GOTIndices;
// Maps data symbols to the Wasm segment and offset/size with the segment.
DenseMap<const MCSymbolWasm *, wasm::WasmDataReference> DataLocations;
// Stores output data (index, relocations, content offset) for custom
// section.
std::vector<WasmCustomSection> CustomSections;
std::unique_ptr<WasmCustomSection> ProducersSection;
std::unique_ptr<WasmCustomSection> TargetFeaturesSection;
// Relocations for fixing up references in the custom sections.
DenseMap<const MCSectionWasm *, std::vector<WasmRelocationEntry>>
CustomSectionsRelocations;
// Map from section to defining function symbol.
DenseMap<const MCSection *, const MCSymbol *> SectionFunctions;
DenseMap<wasm::WasmSignature, uint32_t> SignatureIndices;
SmallVector<wasm::WasmSignature, 4> Signatures;
SmallVector<WasmDataSegment, 4> DataSegments;
unsigned NumFunctionImports = 0;
unsigned NumGlobalImports = 0;
unsigned NumTableImports = 0;
unsigned NumTagImports = 0;
uint32_t SectionCount = 0;
enum class DwoMode {
AllSections,
NonDwoOnly,
DwoOnly,
};
bool IsSplitDwarf = false;
raw_pwrite_stream *OS = nullptr;
raw_pwrite_stream *DwoOS = nullptr;
// TargetObjectWriter wranppers.
bool is64Bit() const { return TargetObjectWriter->is64Bit(); }
bool isEmscripten() const { return TargetObjectWriter->isEmscripten(); }
void startSection(SectionBookkeeping &Section, unsigned SectionId);
void startCustomSection(SectionBookkeeping &Section, StringRef Name);
void endSection(SectionBookkeeping &Section);
public:
WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
raw_pwrite_stream &OS_)
: TargetObjectWriter(std::move(MOTW)), OS(&OS_) {}
WasmObjectWriter(std::unique_ptr<MCWasmObjectTargetWriter> MOTW,
raw_pwrite_stream &OS_, raw_pwrite_stream &DwoOS_)
: TargetObjectWriter(std::move(MOTW)), IsSplitDwarf(true), OS(&OS_),
DwoOS(&DwoOS_) {}
private:
void reset() override {
CodeRelocations.clear();
DataRelocations.clear();
TypeIndices.clear();
WasmIndices.clear();
GOTIndices.clear();
TableIndices.clear();
DataLocations.clear();
CustomSections.clear();
ProducersSection.reset();
TargetFeaturesSection.reset();
CustomSectionsRelocations.clear();
SignatureIndices.clear();
Signatures.clear();
DataSegments.clear();
SectionFunctions.clear();
NumFunctionImports = 0;
NumGlobalImports = 0;
NumTableImports = 0;
MCObjectWriter::reset();
}
void writeHeader(const MCAssembler &Asm);
void recordRelocation(MCAssembler &Asm, const MCAsmLayout &Layout,
const MCFragment *Fragment, const MCFixup &Fixup,
MCValue Target, uint64_t &FixedValue) override;
void executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) override;
void prepareImports(SmallVectorImpl<wasm::WasmImport> &Imports,
MCAssembler &Asm, const MCAsmLayout &Layout);
uint64_t writeObject(MCAssembler &Asm, const MCAsmLayout &Layout) override;
uint64_t writeOneObject(MCAssembler &Asm, const MCAsmLayout &Layout,
DwoMode Mode);
void writeString(const StringRef Str) {
encodeULEB128(Str.size(), W->OS);
W->OS << Str;
}
void writeStringWithAlignment(const StringRef Str, unsigned Alignment);
void writeI32(int32_t val) {
char Buffer[4];
support::endian::write32le(Buffer, val);
W->OS.write(Buffer, sizeof(Buffer));
}
void writeI64(int64_t val) {
char Buffer[8];
support::endian::write64le(Buffer, val);
W->OS.write(Buffer, sizeof(Buffer));
}
void writeValueType(wasm::ValType Ty) { W->OS << static_cast<char>(Ty); }
void writeTypeSection(ArrayRef<wasm::WasmSignature> Signatures);
void writeImportSection(ArrayRef<wasm::WasmImport> Imports, uint64_t DataSize,
uint32_t NumElements);
void writeFunctionSection(ArrayRef<WasmFunction> Functions);
void writeExportSection(ArrayRef<wasm::WasmExport> Exports);
void writeElemSection(const MCSymbolWasm *IndirectFunctionTable,
ArrayRef<uint32_t> TableElems);
void writeDataCountSection();
uint32_t writeCodeSection(const MCAssembler &Asm, const MCAsmLayout &Layout,
ArrayRef<WasmFunction> Functions);
uint32_t writeDataSection(const MCAsmLayout &Layout);
void writeTagSection(ArrayRef<uint32_t> TagTypes);
void writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals);
void writeTableSection(ArrayRef<wasm::WasmTable> Tables);
void writeRelocSection(uint32_t SectionIndex, StringRef Name,
std::vector<WasmRelocationEntry> &Relocations);
void writeLinkingMetaDataSection(
ArrayRef<wasm::WasmSymbolInfo> SymbolInfos,
ArrayRef<std::pair<uint16_t, uint32_t>> InitFuncs,
const std::map<StringRef, std::vector<WasmComdatEntry>> &Comdats);
void writeCustomSection(WasmCustomSection &CustomSection,
const MCAssembler &Asm, const MCAsmLayout &Layout);
void writeCustomRelocSections();
uint64_t getProvisionalValue(const WasmRelocationEntry &RelEntry,
const MCAsmLayout &Layout);
void applyRelocations(ArrayRef<WasmRelocationEntry> Relocations,
uint64_t ContentsOffset, const MCAsmLayout &Layout);
uint32_t getRelocationIndexValue(const WasmRelocationEntry &RelEntry);
uint32_t getFunctionType(const MCSymbolWasm &Symbol);
uint32_t getTagType(const MCSymbolWasm &Symbol);
void registerFunctionType(const MCSymbolWasm &Symbol);
void registerTagType(const MCSymbolWasm &Symbol);
};
} // end anonymous namespace
// Write out a section header and a patchable section size field.
void WasmObjectWriter::startSection(SectionBookkeeping &Section,
unsigned SectionId) {
LLVM_DEBUG(dbgs() << "startSection " << SectionId << "\n");
W->OS << char(SectionId);
Section.SizeOffset = W->OS.tell();
// The section size. We don't know the size yet, so reserve enough space
// for any 32-bit value; we'll patch it later.
encodeULEB128(0, W->OS, 5);
// The position where the section starts, for measuring its size.
Section.ContentsOffset = W->OS.tell();
Section.PayloadOffset = W->OS.tell();
Section.Index = SectionCount++;
}
// Write a string with extra paddings for trailing alignment
// TODO: support alignment at asm and llvm level?
void WasmObjectWriter::writeStringWithAlignment(const StringRef Str,
unsigned Alignment) {
// Calculate the encoded size of str length and add pads based on it and
// alignment.
raw_null_ostream NullOS;
uint64_t StrSizeLength = encodeULEB128(Str.size(), NullOS);
uint64_t Offset = W->OS.tell() + StrSizeLength + Str.size();
uint64_t Paddings = offsetToAlignment(Offset, Align(Alignment));
Offset += Paddings;
// LEB128 greater than 5 bytes is invalid
assert((StrSizeLength + Paddings) <= 5 && "too long string to align");
encodeSLEB128(Str.size(), W->OS, StrSizeLength + Paddings);
W->OS << Str;
assert(W->OS.tell() == Offset && "invalid padding");
}
void WasmObjectWriter::startCustomSection(SectionBookkeeping &Section,
StringRef Name) {
LLVM_DEBUG(dbgs() << "startCustomSection " << Name << "\n");
startSection(Section, wasm::WASM_SEC_CUSTOM);
// The position where the section header ends, for measuring its size.
Section.PayloadOffset = W->OS.tell();
// Custom sections in wasm also have a string identifier.
if (Name != "__clangast") {
writeString(Name);
} else {
// The on-disk hashtable in clangast needs to be aligned by 4 bytes.
writeStringWithAlignment(Name, 4);
}
// The position where the custom section starts.
Section.ContentsOffset = W->OS.tell();
}
// Now that the section is complete and we know how big it is, patch up the
// section size field at the start of the section.
void WasmObjectWriter::endSection(SectionBookkeeping &Section) {
uint64_t Size = W->OS.tell();
// /dev/null doesn't support seek/tell and can report offset of 0.
// Simply skip this patching in that case.
if (!Size)
return;
Size -= Section.PayloadOffset;
if (uint32_t(Size) != Size)
report_fatal_error("section size does not fit in a uint32_t");
LLVM_DEBUG(dbgs() << "endSection size=" << Size << "\n");
// Write the final section size to the payload_len field, which follows
// the section id byte.
writePatchableLEB<5>(static_cast<raw_pwrite_stream &>(W->OS), Size,
Section.SizeOffset);
}
// Emit the Wasm header.
void WasmObjectWriter::writeHeader(const MCAssembler &Asm) {
W->OS.write(wasm::WasmMagic, sizeof(wasm::WasmMagic));
W->write<uint32_t>(wasm::WasmVersion);
}
void WasmObjectWriter::executePostLayoutBinding(MCAssembler &Asm,
const MCAsmLayout &Layout) {
// Some compilation units require the indirect function table to be present
// but don't explicitly reference it. This is the case for call_indirect
// without the reference-types feature, and also function bitcasts in all
// cases. In those cases the __indirect_function_table has the
// WASM_SYMBOL_NO_STRIP attribute. Here we make sure this symbol makes it to
// the assembler, if needed.
if (auto *Sym = Asm.getContext().lookupSymbol("__indirect_function_table")) {
const auto *WasmSym = static_cast<const MCSymbolWasm *>(Sym);
if (WasmSym->isNoStrip())
Asm.registerSymbol(*Sym);
}
// Build a map of sections to the function that defines them, for use
// in recordRelocation.
for (const MCSymbol &S : Asm.symbols()) {
const auto &WS = static_cast<const MCSymbolWasm &>(S);
if (WS.isDefined() && WS.isFunction() && !WS.isVariable()) {
const auto &Sec = static_cast<const MCSectionWasm &>(S.getSection());
auto Pair = SectionFunctions.insert(std::make_pair(&Sec, &S));
if (!Pair.second)
report_fatal_error("section already has a defining function: " +
Sec.getName());
}
}
}
void WasmObjectWriter::recordRelocation(MCAssembler &Asm,
const MCAsmLayout &Layout,
const MCFragment *Fragment,
const MCFixup &Fixup, MCValue Target,
uint64_t &FixedValue) {
// The WebAssembly backend should never generate FKF_IsPCRel fixups
assert(!(Asm.getBackend().getFixupKindInfo(Fixup.getKind()).Flags &
MCFixupKindInfo::FKF_IsPCRel));
const auto &FixupSection = cast<MCSectionWasm>(*Fragment->getParent());
uint64_t C = Target.getConstant();
uint64_t FixupOffset = Layout.getFragmentOffset(Fragment) + Fixup.getOffset();
MCContext &Ctx = Asm.getContext();
bool IsLocRel = false;
if (const MCSymbolRefExpr *RefB = Target.getSymB()) {
const auto &SymB = cast<MCSymbolWasm>(RefB->getSymbol());
if (FixupSection.getKind().isText()) {
Ctx.reportError(Fixup.getLoc(),
Twine("symbol '") + SymB.getName() +
"' unsupported subtraction expression used in "
"relocation in code section.");
return;
}
if (SymB.isUndefined()) {
Ctx.reportError(Fixup.getLoc(),
Twine("symbol '") + SymB.getName() +
"' can not be undefined in a subtraction expression");
return;
}
const MCSection &SecB = SymB.getSection();
if (&SecB != &FixupSection) {
Ctx.reportError(Fixup.getLoc(),
Twine("symbol '") + SymB.getName() +
"' can not be placed in a different section");
return;
}
IsLocRel = true;
C += FixupOffset - Layout.getSymbolOffset(SymB);
}
// We either rejected the fixup or folded B into C at this point.
const MCSymbolRefExpr *RefA = Target.getSymA();
const auto *SymA = cast<MCSymbolWasm>(&RefA->getSymbol());
// The .init_array isn't translated as data, so don't do relocations in it.
if (FixupSection.getName().startswith(".init_array")) {
SymA->setUsedInInitArray();
return;
}
if (SymA->isVariable()) {
const MCExpr *Expr = SymA->getVariableValue();
if (const auto *Inner = dyn_cast<MCSymbolRefExpr>(Expr))
if (Inner->getKind() == MCSymbolRefExpr::VK_WEAKREF)
llvm_unreachable("weakref used in reloc not yet implemented");
}
// Put any constant offset in an addend. Offsets can be negative, and
// LLVM expects wrapping, in contrast to wasm's immediates which can't
// be negative and don't wrap.
FixedValue = 0;
unsigned Type =
TargetObjectWriter->getRelocType(Target, Fixup, FixupSection, IsLocRel);
// Absolute offset within a section or a function.
// Currently only supported for for metadata sections.
// See: test/MC/WebAssembly/blockaddress.ll
if ((Type == wasm::R_WASM_FUNCTION_OFFSET_I32 ||
Type == wasm::R_WASM_FUNCTION_OFFSET_I64 ||
Type == wasm::R_WASM_SECTION_OFFSET_I32) &&
SymA->isDefined()) {
// SymA can be a temp data symbol that represents a function (in which case
// it needs to be replaced by the section symbol), [XXX and it apparently
// later gets changed again to a func symbol?] or it can be a real
// function symbol, in which case it can be left as-is.
if (!FixupSection.getKind().isMetadata())
report_fatal_error("relocations for function or section offsets are "
"only supported in metadata sections");
const MCSymbol *SectionSymbol = nullptr;
const MCSection &SecA = SymA->getSection();
if (SecA.getKind().isText()) {
auto SecSymIt = SectionFunctions.find(&SecA);
if (SecSymIt == SectionFunctions.end())
report_fatal_error("section doesn\'t have defining symbol");
SectionSymbol = SecSymIt->second;
} else {
SectionSymbol = SecA.getBeginSymbol();
}
if (!SectionSymbol)
report_fatal_error("section symbol is required for relocation");
C += Layout.getSymbolOffset(*SymA);
SymA = cast<MCSymbolWasm>(SectionSymbol);
}
if (Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64 ||
Type == wasm::R_WASM_TABLE_INDEX_SLEB ||
Type == wasm::R_WASM_TABLE_INDEX_SLEB64 ||
Type == wasm::R_WASM_TABLE_INDEX_I32 ||
Type == wasm::R_WASM_TABLE_INDEX_I64) {
// TABLE_INDEX relocs implicitly use the default indirect function table.
// We require the function table to have already been defined.
auto TableName = "__indirect_function_table";
MCSymbolWasm *Sym = cast_or_null<MCSymbolWasm>(Ctx.lookupSymbol(TableName));
if (!Sym) {
report_fatal_error("missing indirect function table symbol");
} else {
if (!Sym->isFunctionTable())
report_fatal_error("__indirect_function_table symbol has wrong type");
// Ensure that __indirect_function_table reaches the output.
Sym->setNoStrip();
Asm.registerSymbol(*Sym);
}
}
// Relocation other than R_WASM_TYPE_INDEX_LEB are required to be
// against a named symbol.
if (Type != wasm::R_WASM_TYPE_INDEX_LEB) {
if (SymA->getName().empty())
report_fatal_error("relocations against un-named temporaries are not yet "
"supported by wasm");
SymA->setUsedInReloc();
}
switch (RefA->getKind()) {
case MCSymbolRefExpr::VK_GOT:
case MCSymbolRefExpr::VK_WASM_GOT_TLS:
SymA->setUsedInGOT();
break;
default:
break;
}
WasmRelocationEntry Rec(FixupOffset, SymA, C, Type, &FixupSection);
LLVM_DEBUG(dbgs() << "WasmReloc: " << Rec << "\n");
if (FixupSection.isWasmData()) {
DataRelocations.push_back(Rec);
} else if (FixupSection.getKind().isText()) {
CodeRelocations.push_back(Rec);
} else if (FixupSection.getKind().isMetadata()) {
CustomSectionsRelocations[&FixupSection].push_back(Rec);
} else {
llvm_unreachable("unexpected section type");
}
}
// Compute a value to write into the code at the location covered
// by RelEntry. This value isn't used by the static linker; it just serves
// to make the object format more readable and more likely to be directly
// useable.
uint64_t
WasmObjectWriter::getProvisionalValue(const WasmRelocationEntry &RelEntry,
const MCAsmLayout &Layout) {
if ((RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_LEB ||
RelEntry.Type == wasm::R_WASM_GLOBAL_INDEX_I32) &&
!RelEntry.Symbol->isGlobal()) {
assert(GOTIndices.count(RelEntry.Symbol) > 0 && "symbol not found in GOT index space");
return GOTIndices[RelEntry.Symbol];
}
switch (RelEntry.Type) {
case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
case wasm::R_WASM_TABLE_INDEX_SLEB:
case wasm::R_WASM_TABLE_INDEX_SLEB64:
case wasm::R_WASM_TABLE_INDEX_I32:
case wasm::R_WASM_TABLE_INDEX_I64: {
// Provisional value is table address of the resolved symbol itself
const MCSymbolWasm *Base =
cast<MCSymbolWasm>(Layout.getBaseSymbol(*RelEntry.Symbol));
assert(Base->isFunction());
if (RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB ||
RelEntry.Type == wasm::R_WASM_TABLE_INDEX_REL_SLEB64)
return TableIndices[Base] - InitialTableOffset;
else
return TableIndices[Base];
}
case wasm::R_WASM_TYPE_INDEX_LEB:
// Provisional value is same as the index
return getRelocationIndexValue(RelEntry);
case wasm::R_WASM_FUNCTION_INDEX_LEB:
case wasm::R_WASM_GLOBAL_INDEX_LEB:
case wasm::R_WASM_GLOBAL_INDEX_I32:
case wasm::R_WASM_TAG_INDEX_LEB:
case wasm::R_WASM_TABLE_NUMBER_LEB:
// Provisional value is function/global/tag Wasm index
assert(WasmIndices.count(RelEntry.Symbol) > 0 && "symbol not found in wasm index space");
return WasmIndices[RelEntry.Symbol];
case wasm::R_WASM_FUNCTION_OFFSET_I32:
case wasm::R_WASM_FUNCTION_OFFSET_I64:
case wasm::R_WASM_SECTION_OFFSET_I32: {
if (!RelEntry.Symbol->isDefined())
return 0;
const auto &Section =
static_cast<const MCSectionWasm &>(RelEntry.Symbol->getSection());
return Section.getSectionOffset() + RelEntry.Addend;
}
case wasm::R_WASM_MEMORY_ADDR_LEB:
case wasm::R_WASM_MEMORY_ADDR_LEB64:
case wasm::R_WASM_MEMORY_ADDR_SLEB:
case wasm::R_WASM_MEMORY_ADDR_SLEB64:
case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
case wasm::R_WASM_MEMORY_ADDR_I32:
case wasm::R_WASM_MEMORY_ADDR_I64:
case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32: {
// Provisional value is address of the global plus the offset
// For undefined symbols, use zero
if (!RelEntry.Symbol->isDefined())
return 0;
const wasm::WasmDataReference &SymRef = DataLocations[RelEntry.Symbol];
const WasmDataSegment &Segment = DataSegments[SymRef.Segment];
// Ignore overflow. LLVM allows address arithmetic to silently wrap.
return Segment.Offset + SymRef.Offset + RelEntry.Addend;
}
default:
llvm_unreachable("invalid relocation type");
}
}
static void addData(SmallVectorImpl<char> &DataBytes,
MCSectionWasm &DataSection) {
LLVM_DEBUG(errs() << "addData: " << DataSection.getName() << "\n");
DataBytes.resize(alignTo(DataBytes.size(), DataSection.getAlignment()));
for (const MCFragment &Frag : DataSection) {
if (Frag.hasInstructions())
report_fatal_error("only data supported in data sections");
if (auto *Align = dyn_cast<MCAlignFragment>(&Frag)) {
if (Align->getValueSize() != 1)
report_fatal_error("only byte values supported for alignment");
// If nops are requested, use zeros, as this is the data section.
uint8_t Value = Align->hasEmitNops() ? 0 : Align->getValue();
uint64_t Size =
std::min<uint64_t>(alignTo(DataBytes.size(), Align->getAlignment()),
DataBytes.size() + Align->getMaxBytesToEmit());
DataBytes.resize(Size, Value);
} else if (auto *Fill = dyn_cast<MCFillFragment>(&Frag)) {
int64_t NumValues;
if (!Fill->getNumValues().evaluateAsAbsolute(NumValues))
llvm_unreachable("The fill should be an assembler constant");
DataBytes.insert(DataBytes.end(), Fill->getValueSize() * NumValues,
Fill->getValue());
} else if (auto *LEB = dyn_cast<MCLEBFragment>(&Frag)) {
const SmallVectorImpl<char> &Contents = LEB->getContents();
llvm::append_range(DataBytes, Contents);
} else {
const auto &DataFrag = cast<MCDataFragment>(Frag);
const SmallVectorImpl<char> &Contents = DataFrag.getContents();
llvm::append_range(DataBytes, Contents);
}
}
LLVM_DEBUG(dbgs() << "addData -> " << DataBytes.size() << "\n");
}
uint32_t
WasmObjectWriter::getRelocationIndexValue(const WasmRelocationEntry &RelEntry) {
if (RelEntry.Type == wasm::R_WASM_TYPE_INDEX_LEB) {
if (!TypeIndices.count(RelEntry.Symbol))
report_fatal_error("symbol not found in type index space: " +
RelEntry.Symbol->getName());
return TypeIndices[RelEntry.Symbol];
}
return RelEntry.Symbol->getIndex();
}
// Apply the portions of the relocation records that we can handle ourselves
// directly.
void WasmObjectWriter::applyRelocations(
ArrayRef<WasmRelocationEntry> Relocations, uint64_t ContentsOffset,
const MCAsmLayout &Layout) {
auto &Stream = static_cast<raw_pwrite_stream &>(W->OS);
for (const WasmRelocationEntry &RelEntry : Relocations) {
uint64_t Offset = ContentsOffset +
RelEntry.FixupSection->getSectionOffset() +
RelEntry.Offset;
LLVM_DEBUG(dbgs() << "applyRelocation: " << RelEntry << "\n");
auto Value = getProvisionalValue(RelEntry, Layout);
switch (RelEntry.Type) {
case wasm::R_WASM_FUNCTION_INDEX_LEB:
case wasm::R_WASM_TYPE_INDEX_LEB:
case wasm::R_WASM_GLOBAL_INDEX_LEB:
case wasm::R_WASM_MEMORY_ADDR_LEB:
case wasm::R_WASM_TAG_INDEX_LEB:
case wasm::R_WASM_TABLE_NUMBER_LEB:
writePatchableLEB<5>(Stream, Value, Offset);
break;
case wasm::R_WASM_MEMORY_ADDR_LEB64:
writePatchableLEB<10>(Stream, Value, Offset);
break;
case wasm::R_WASM_TABLE_INDEX_I32:
case wasm::R_WASM_MEMORY_ADDR_I32:
case wasm::R_WASM_FUNCTION_OFFSET_I32:
case wasm::R_WASM_SECTION_OFFSET_I32:
case wasm::R_WASM_GLOBAL_INDEX_I32:
case wasm::R_WASM_MEMORY_ADDR_LOCREL_I32:
patchI32(Stream, Value, Offset);
break;
case wasm::R_WASM_TABLE_INDEX_I64:
case wasm::R_WASM_MEMORY_ADDR_I64:
case wasm::R_WASM_FUNCTION_OFFSET_I64:
patchI64(Stream, Value, Offset);
break;
case wasm::R_WASM_TABLE_INDEX_SLEB:
case wasm::R_WASM_TABLE_INDEX_REL_SLEB:
case wasm::R_WASM_MEMORY_ADDR_SLEB:
case wasm::R_WASM_MEMORY_ADDR_REL_SLEB:
case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB:
writePatchableSLEB<5>(Stream, Value, Offset);
break;
case wasm::R_WASM_TABLE_INDEX_SLEB64:
case wasm::R_WASM_TABLE_INDEX_REL_SLEB64:
case wasm::R_WASM_MEMORY_ADDR_SLEB64:
case wasm::R_WASM_MEMORY_ADDR_REL_SLEB64:
case wasm::R_WASM_MEMORY_ADDR_TLS_SLEB64:
writePatchableSLEB<10>(Stream, Value, Offset);
break;
default:
llvm_unreachable("invalid relocation type");
}
}
}
void WasmObjectWriter::writeTypeSection(
ArrayRef<wasm::WasmSignature> Signatures) {
if (Signatures.empty())
return;
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_TYPE);
encodeULEB128(Signatures.size(), W->OS);
for (const wasm::WasmSignature &Sig : Signatures) {
W->OS << char(wasm::WASM_TYPE_FUNC);
encodeULEB128(Sig.Params.size(), W->OS);
for (wasm::ValType Ty : Sig.Params)
writeValueType(Ty);
encodeULEB128(Sig.Returns.size(), W->OS);
for (wasm::ValType Ty : Sig.Returns)
writeValueType(Ty);
}
endSection(Section);
}
void WasmObjectWriter::writeImportSection(ArrayRef<wasm::WasmImport> Imports,
uint64_t DataSize,
uint32_t NumElements) {
if (Imports.empty())
return;
uint64_t NumPages = (DataSize + wasm::WasmPageSize - 1) / wasm::WasmPageSize;
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_IMPORT);
encodeULEB128(Imports.size(), W->OS);
for (const wasm::WasmImport &Import : Imports) {
writeString(Import.Module);
writeString(Import.Field);
W->OS << char(Import.Kind);
switch (Import.Kind) {
case wasm::WASM_EXTERNAL_FUNCTION:
encodeULEB128(Import.SigIndex, W->OS);
break;
case wasm::WASM_EXTERNAL_GLOBAL:
W->OS << char(Import.Global.Type);
W->OS << char(Import.Global.Mutable ? 1 : 0);
break;
case wasm::WASM_EXTERNAL_MEMORY:
encodeULEB128(Import.Memory.Flags, W->OS);
encodeULEB128(NumPages, W->OS); // initial
break;
case wasm::WASM_EXTERNAL_TABLE:
W->OS << char(Import.Table.ElemType);
encodeULEB128(0, W->OS); // flags
encodeULEB128(NumElements, W->OS); // initial
break;
case wasm::WASM_EXTERNAL_TAG:
W->OS << char(0); // Reserved 'attribute' field
encodeULEB128(Import.SigIndex, W->OS);
break;
default:
llvm_unreachable("unsupported import kind");
}
}
endSection(Section);
}
void WasmObjectWriter::writeFunctionSection(ArrayRef<WasmFunction> Functions) {
if (Functions.empty())
return;
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_FUNCTION);
encodeULEB128(Functions.size(), W->OS);
for (const WasmFunction &Func : Functions)
encodeULEB128(Func.SigIndex, W->OS);
endSection(Section);
}
void WasmObjectWriter::writeTagSection(ArrayRef<uint32_t> TagTypes) {
if (TagTypes.empty())
return;
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_TAG);
encodeULEB128(TagTypes.size(), W->OS);
for (uint32_t Index : TagTypes) {
W->OS << char(0); // Reserved 'attribute' field
encodeULEB128(Index, W->OS);
}
endSection(Section);
}
void WasmObjectWriter::writeGlobalSection(ArrayRef<wasm::WasmGlobal> Globals) {
if (Globals.empty())
return;
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_GLOBAL);
encodeULEB128(Globals.size(), W->OS);
for (const wasm::WasmGlobal &Global : Globals) {
encodeULEB128(Global.Type.Type, W->OS);
W->OS << char(Global.Type.Mutable);
W->OS << char(Global.InitExpr.Opcode);
switch (Global.Type.Type) {
case wasm::WASM_TYPE_I32:
encodeSLEB128(0, W->OS);
break;
case wasm::WASM_TYPE_I64:
encodeSLEB128(0, W->OS);
break;
case wasm::WASM_TYPE_F32:
writeI32(0);
break;
case wasm::WASM_TYPE_F64:
writeI64(0);
break;
case wasm::WASM_TYPE_EXTERNREF:
writeValueType(wasm::ValType::EXTERNREF);
break;
default:
llvm_unreachable("unexpected type");
}
W->OS << char(wasm::WASM_OPCODE_END);
}
endSection(Section);
}
void WasmObjectWriter::writeTableSection(ArrayRef<wasm::WasmTable> Tables) {
if (Tables.empty())
return;
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_TABLE);
encodeULEB128(Tables.size(), W->OS);
for (const wasm::WasmTable &Table : Tables) {
encodeULEB128(Table.Type.ElemType, W->OS);
encodeULEB128(Table.Type.Limits.Flags, W->OS);
encodeULEB128(Table.Type.Limits.Minimum, W->OS);
if (Table.Type.Limits.Flags & wasm::WASM_LIMITS_FLAG_HAS_MAX)
encodeULEB128(Table.Type.Limits.Maximum, W->OS);
}
endSection(Section);
}
void WasmObjectWriter::writeExportSection(ArrayRef<wasm::WasmExport> Exports) {
if (Exports.empty())
return;
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_EXPORT);
encodeULEB128(Exports.size(), W->OS);
for (const wasm::WasmExport &Export : Exports) {
writeString(Export.Name);
W->OS << char(Export.Kind);
encodeULEB128(Export.Index, W->OS);
}
endSection(Section);
}
void WasmObjectWriter::writeElemSection(
const MCSymbolWasm *IndirectFunctionTable, ArrayRef<uint32_t> TableElems) {
if (TableElems.empty())
return;
assert(IndirectFunctionTable);
SectionBookkeeping Section;
startSection(Section, wasm::WASM_SEC_ELEM);
encodeULEB128(1, W->OS); // number of "segments"
assert(WasmIndices.count(IndirectFunctionTable));
uint32_t TableNumber = WasmIndices.find(IndirectFunctionTable)->second;
uint32_t Flags = 0;
if (TableNumber)
Flags |= wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER;
encodeULEB128(Flags, W->OS);
if (Flags & wasm::WASM_ELEM_SEGMENT_HAS_TABLE_NUMBER)
encodeULEB128(TableNumber, W->OS); // the table number
// init expr for starting offset
W->OS << char(wasm::WASM_OPCODE_I32_CONST);
encodeSLEB128(InitialTableOffset, W->OS);
W->OS << char(wasm::WASM_OPCODE_END);