-
Notifications
You must be signed in to change notification settings - Fork 745
/
wasm-binary.cpp
6953 lines (6583 loc) · 214 KB
/
wasm-binary.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
/*
* Copyright 2016 WebAssembly Community Group participants
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <algorithm>
#include <fstream>
#include "ir/eh-utils.h"
#include "ir/module-utils.h"
#include "ir/table-utils.h"
#include "ir/type-updating.h"
#include "support/bits.h"
#include "support/debug.h"
#include "wasm-binary.h"
#include "wasm-debug.h"
#include "wasm-stack.h"
#define DEBUG_TYPE "binary"
namespace wasm {
void WasmBinaryWriter::prepare() {
// Collect function types and their frequencies. Collect information in each
// function in parallel, then merge.
indexedTypes = ModuleUtils::getOptimizedIndexedHeapTypes(*wasm);
importInfo = wasm::make_unique<ImportInfo>(*wasm);
}
void WasmBinaryWriter::write() {
writeHeader();
writeDylinkSection();
initializeDebugInfo();
if (sourceMap) {
writeSourceMapProlog();
}
writeTypes();
writeImports();
writeFunctionSignatures();
writeTableDeclarations();
writeMemory();
writeTags();
writeGlobals();
writeExports();
writeStart();
writeElementSegments();
writeDataCount();
writeFunctions();
writeDataSegments();
if (debugInfo || emitModuleName) {
writeNames();
}
if (sourceMap && !sourceMapUrl.empty()) {
writeSourceMapUrl();
}
if (symbolMap.size() > 0) {
writeSymbolMap();
}
if (sourceMap) {
writeSourceMapEpilog();
}
#ifdef BUILD_LLVM_DWARF
// Update DWARF user sections after writing the data they refer to
// (function bodies), and before writing the user sections themselves.
if (Debug::hasDWARFSections(*wasm)) {
Debug::writeDWARFSections(*wasm, binaryLocations);
}
#endif
writeLateUserSections();
writeFeaturesSection();
}
void WasmBinaryWriter::writeHeader() {
BYN_TRACE("== writeHeader\n");
o << int32_t(BinaryConsts::Magic); // magic number \0asm
o << int32_t(BinaryConsts::Version);
}
int32_t WasmBinaryWriter::writeU32LEBPlaceholder() {
int32_t ret = o.size();
o << int32_t(0);
o << int8_t(0);
return ret;
}
void WasmBinaryWriter::writeResizableLimits(
Address initial, Address maximum, bool hasMaximum, bool shared, bool is64) {
uint32_t flags = (hasMaximum ? (uint32_t)BinaryConsts::HasMaximum : 0U) |
(shared ? (uint32_t)BinaryConsts::IsShared : 0U) |
(is64 ? (uint32_t)BinaryConsts::Is64 : 0U);
o << U32LEB(flags);
if (is64) {
o << U64LEB(initial);
if (hasMaximum) {
o << U64LEB(maximum);
}
} else {
o << U32LEB(initial);
if (hasMaximum) {
o << U32LEB(maximum);
}
}
}
template<typename T> int32_t WasmBinaryWriter::startSection(T code) {
o << uint8_t(code);
if (sourceMap) {
sourceMapLocationsSizeAtSectionStart = sourceMapLocations.size();
}
binaryLocationsSizeAtSectionStart = binaryLocations.expressions.size();
return writeU32LEBPlaceholder(); // section size to be filled in later
}
void WasmBinaryWriter::finishSection(int32_t start) {
// section size does not include the reserved bytes of the size field itself
int32_t size = o.size() - start - MaxLEB32Bytes;
auto sizeFieldSize = o.writeAt(start, U32LEB(size));
// We can move things back if the actual LEB for the size doesn't use the
// maximum 5 bytes. In that case we need to adjust offsets after we move
// things backwards.
auto adjustmentForLEBShrinking = MaxLEB32Bytes - sizeFieldSize;
if (adjustmentForLEBShrinking) {
// we can save some room, nice
assert(sizeFieldSize < MaxLEB32Bytes);
std::move(&o[start] + MaxLEB32Bytes,
&o[start] + MaxLEB32Bytes + size,
&o[start] + sizeFieldSize);
o.resize(o.size() - adjustmentForLEBShrinking);
if (sourceMap) {
for (auto i = sourceMapLocationsSizeAtSectionStart;
i < sourceMapLocations.size();
++i) {
sourceMapLocations[i].first -= adjustmentForLEBShrinking;
}
}
}
if (binaryLocationsSizeAtSectionStart != binaryLocations.expressions.size()) {
// We added the binary locations, adjust them: they must be relative
// to the code section.
assert(binaryLocationsSizeAtSectionStart == 0);
// The section type byte is right before the LEB for the size; we want
// offsets that are relative to the body, which is after that section type
// byte and the the size LEB.
auto body = start + sizeFieldSize;
// Offsets are relative to the body of the code section: after the
// section type byte and the size.
// Everything was moved by the adjustment, track that. After this,
// we are at the right absolute address.
// We are relative to the section start.
auto totalAdjustment = adjustmentForLEBShrinking + body;
for (auto& [_, locations] : binaryLocations.expressions) {
locations.start -= totalAdjustment;
locations.end -= totalAdjustment;
}
for (auto& [_, locations] : binaryLocations.functions) {
locations.start -= totalAdjustment;
locations.declarations -= totalAdjustment;
locations.end -= totalAdjustment;
}
for (auto& [_, locations] : binaryLocations.delimiters) {
for (auto& item : locations) {
item -= totalAdjustment;
}
}
}
}
int32_t
WasmBinaryWriter::startSubsection(BinaryConsts::UserSections::Subsection code) {
return startSection(code);
}
void WasmBinaryWriter::finishSubsection(int32_t start) { finishSection(start); }
void WasmBinaryWriter::writeStart() {
if (!wasm->start.is()) {
return;
}
BYN_TRACE("== writeStart\n");
auto start = startSection(BinaryConsts::Section::Start);
o << U32LEB(getFunctionIndex(wasm->start.str));
finishSection(start);
}
void WasmBinaryWriter::writeMemory() {
if (!wasm->memory.exists || wasm->memory.imported()) {
return;
}
BYN_TRACE("== writeMemory\n");
auto start = startSection(BinaryConsts::Section::Memory);
o << U32LEB(1); // Define 1 memory
writeResizableLimits(wasm->memory.initial,
wasm->memory.max,
wasm->memory.hasMax(),
wasm->memory.shared,
wasm->memory.is64());
finishSection(start);
}
void WasmBinaryWriter::writeTypes() {
if (indexedTypes.types.size() == 0) {
return;
}
BYN_TRACE("== writeTypes\n");
auto start = startSection(BinaryConsts::Section::Type);
o << U32LEB(indexedTypes.types.size());
for (Index i = 0; i < indexedTypes.types.size(); ++i) {
auto type = indexedTypes.types[i];
bool nominal = getTypeSystem() == TypeSystem::Nominal;
BYN_TRACE("write " << type << std::endl);
if (type.isSignature()) {
o << S32LEB(nominal ? BinaryConsts::EncodedType::FuncExtending
: BinaryConsts::EncodedType::Func);
auto sig = type.getSignature();
for (auto& sigType : {sig.params, sig.results}) {
o << U32LEB(sigType.size());
for (const auto& type : sigType) {
writeType(type);
}
}
} else if (type.isStruct()) {
o << S32LEB(nominal ? BinaryConsts::EncodedType::StructExtending
: BinaryConsts::EncodedType::Struct);
auto fields = type.getStruct().fields;
o << U32LEB(fields.size());
for (const auto& field : fields) {
writeField(field);
}
} else if (type.isArray()) {
o << S32LEB(nominal ? BinaryConsts::EncodedType::ArrayExtending
: BinaryConsts::EncodedType::Array);
writeField(type.getArray().element);
} else {
WASM_UNREACHABLE("TODO GC type writing");
}
if (nominal) {
auto super = type.getSuperType();
if (!super) {
super = type.isFunction() ? HeapType::func : HeapType::data;
}
writeHeapType(*super);
}
}
finishSection(start);
}
void WasmBinaryWriter::writeImports() {
auto num = importInfo->getNumImports();
if (num == 0) {
return;
}
BYN_TRACE("== writeImports\n");
auto start = startSection(BinaryConsts::Section::Import);
o << U32LEB(num);
auto writeImportHeader = [&](Importable* import) {
writeInlineString(import->module.str);
writeInlineString(import->base.str);
};
ModuleUtils::iterImportedFunctions(*wasm, [&](Function* func) {
BYN_TRACE("write one function\n");
writeImportHeader(func);
o << U32LEB(int32_t(ExternalKind::Function));
o << U32LEB(getTypeIndex(func->type));
});
ModuleUtils::iterImportedGlobals(*wasm, [&](Global* global) {
BYN_TRACE("write one global\n");
writeImportHeader(global);
o << U32LEB(int32_t(ExternalKind::Global));
writeType(global->type);
o << U32LEB(global->mutable_);
});
ModuleUtils::iterImportedTags(*wasm, [&](Tag* tag) {
BYN_TRACE("write one tag\n");
writeImportHeader(tag);
o << U32LEB(int32_t(ExternalKind::Tag));
o << uint8_t(0); // Reserved 'attribute' field. Always 0.
o << U32LEB(getTypeIndex(tag->sig));
});
if (wasm->memory.imported()) {
BYN_TRACE("write one memory\n");
writeImportHeader(&wasm->memory);
o << U32LEB(int32_t(ExternalKind::Memory));
writeResizableLimits(wasm->memory.initial,
wasm->memory.max,
wasm->memory.hasMax(),
wasm->memory.shared,
wasm->memory.is64());
}
ModuleUtils::iterImportedTables(*wasm, [&](Table* table) {
BYN_TRACE("write one table\n");
writeImportHeader(table);
o << U32LEB(int32_t(ExternalKind::Table));
writeType(table->type);
writeResizableLimits(table->initial,
table->max,
table->hasMax(),
/*shared=*/false,
/*is64*/ false);
});
finishSection(start);
}
void WasmBinaryWriter::writeFunctionSignatures() {
if (importInfo->getNumDefinedFunctions() == 0) {
return;
}
BYN_TRACE("== writeFunctionSignatures\n");
auto start = startSection(BinaryConsts::Section::Function);
o << U32LEB(importInfo->getNumDefinedFunctions());
ModuleUtils::iterDefinedFunctions(*wasm, [&](Function* func) {
BYN_TRACE("write one\n");
o << U32LEB(getTypeIndex(func->type));
});
finishSection(start);
}
void WasmBinaryWriter::writeExpression(Expression* curr) {
BinaryenIRToBinaryWriter(*this, o).visit(curr);
}
void WasmBinaryWriter::writeFunctions() {
if (importInfo->getNumDefinedFunctions() == 0) {
return;
}
BYN_TRACE("== writeFunctions\n");
auto sectionStart = startSection(BinaryConsts::Section::Code);
o << U32LEB(importInfo->getNumDefinedFunctions());
bool DWARF = Debug::hasDWARFSections(*getModule());
ModuleUtils::iterDefinedFunctions(*wasm, [&](Function* func) {
assert(binaryLocationTrackedExpressionsForFunc.empty());
size_t sourceMapLocationsSizeAtFunctionStart = sourceMapLocations.size();
BYN_TRACE("write one at" << o.size() << std::endl);
size_t sizePos = writeU32LEBPlaceholder();
size_t start = o.size();
BYN_TRACE("writing" << func->name << std::endl);
// Emit Stack IR if present, and if we can
if (func->stackIR && !sourceMap && !DWARF) {
BYN_TRACE("write Stack IR\n");
StackIRToBinaryWriter writer(*this, o, func);
writer.write();
if (debugInfo) {
funcMappedLocals[func->name] = std::move(writer.getMappedLocals());
}
} else {
BYN_TRACE("write Binaryen IR\n");
BinaryenIRToBinaryWriter writer(*this, o, func, sourceMap, DWARF);
writer.write();
if (debugInfo) {
funcMappedLocals[func->name] = std::move(writer.getMappedLocals());
}
}
size_t size = o.size() - start;
assert(size <= std::numeric_limits<uint32_t>::max());
BYN_TRACE("body size: " << size << ", writing at " << sizePos
<< ", next starts at " << o.size() << "\n");
auto sizeFieldSize = o.writeAt(sizePos, U32LEB(size));
// We can move things back if the actual LEB for the size doesn't use the
// maximum 5 bytes. In that case we need to adjust offsets after we move
// things backwards.
auto adjustmentForLEBShrinking = MaxLEB32Bytes - sizeFieldSize;
if (adjustmentForLEBShrinking) {
// we can save some room, nice
assert(sizeFieldSize < MaxLEB32Bytes);
std::move(&o[start], &o[start] + size, &o[sizePos] + sizeFieldSize);
o.resize(o.size() - adjustmentForLEBShrinking);
if (sourceMap) {
for (auto i = sourceMapLocationsSizeAtFunctionStart;
i < sourceMapLocations.size();
++i) {
sourceMapLocations[i].first -= adjustmentForLEBShrinking;
}
}
for (auto* curr : binaryLocationTrackedExpressionsForFunc) {
// We added the binary locations, adjust them: they must be relative
// to the code section.
auto& span = binaryLocations.expressions[curr];
span.start -= adjustmentForLEBShrinking;
span.end -= adjustmentForLEBShrinking;
auto iter = binaryLocations.delimiters.find(curr);
if (iter != binaryLocations.delimiters.end()) {
for (auto& item : iter->second) {
item -= adjustmentForLEBShrinking;
}
}
}
}
if (!binaryLocationTrackedExpressionsForFunc.empty()) {
binaryLocations.functions[func] = BinaryLocations::FunctionLocations{
BinaryLocation(sizePos),
BinaryLocation(start - adjustmentForLEBShrinking),
BinaryLocation(o.size())};
}
tableOfContents.functionBodies.emplace_back(
func->name, sizePos + sizeFieldSize, size);
binaryLocationTrackedExpressionsForFunc.clear();
});
finishSection(sectionStart);
}
void WasmBinaryWriter::writeGlobals() {
if (importInfo->getNumDefinedGlobals() == 0) {
return;
}
BYN_TRACE("== writeglobals\n");
auto start = startSection(BinaryConsts::Section::Global);
// Count and emit the total number of globals after tuple globals have been
// expanded into their constituent parts.
Index num = 0;
ModuleUtils::iterDefinedGlobals(
*wasm, [&num](Global* global) { num += global->type.size(); });
o << U32LEB(num);
ModuleUtils::iterDefinedGlobals(*wasm, [&](Global* global) {
BYN_TRACE("write one\n");
size_t i = 0;
for (const auto& t : global->type) {
writeType(t);
o << U32LEB(global->mutable_);
if (global->type.size() == 1) {
writeExpression(global->init);
} else {
writeExpression(global->init->cast<TupleMake>()->operands[i]);
}
o << int8_t(BinaryConsts::End);
++i;
}
});
finishSection(start);
}
void WasmBinaryWriter::writeExports() {
if (wasm->exports.size() == 0) {
return;
}
BYN_TRACE("== writeexports\n");
auto start = startSection(BinaryConsts::Section::Export);
o << U32LEB(wasm->exports.size());
for (auto& curr : wasm->exports) {
BYN_TRACE("write one\n");
writeInlineString(curr->name.str);
o << U32LEB(int32_t(curr->kind));
switch (curr->kind) {
case ExternalKind::Function:
o << U32LEB(getFunctionIndex(curr->value));
break;
case ExternalKind::Table:
o << U32LEB(0);
break;
case ExternalKind::Memory:
o << U32LEB(0);
break;
case ExternalKind::Global:
o << U32LEB(getGlobalIndex(curr->value));
break;
case ExternalKind::Tag:
o << U32LEB(getTagIndex(curr->value));
break;
default:
WASM_UNREACHABLE("unexpected extern kind");
}
}
finishSection(start);
}
void WasmBinaryWriter::writeDataCount() {
if (!wasm->features.hasBulkMemory() || !wasm->memory.segments.size()) {
return;
}
auto start = startSection(BinaryConsts::Section::DataCount);
o << U32LEB(wasm->memory.segments.size());
finishSection(start);
}
void WasmBinaryWriter::writeDataSegments() {
if (wasm->memory.segments.size() == 0) {
return;
}
if (wasm->memory.segments.size() > WebLimitations::MaxDataSegments) {
std::cerr << "Some VMs may not accept this binary because it has a large "
<< "number of data segments. Run the limit-segments pass to "
<< "merge segments.\n";
}
auto start = startSection(BinaryConsts::Section::Data);
o << U32LEB(wasm->memory.segments.size());
for (auto& segment : wasm->memory.segments) {
uint32_t flags = 0;
if (segment.isPassive) {
flags |= BinaryConsts::IsPassive;
}
o << U32LEB(flags);
if (!segment.isPassive) {
writeExpression(segment.offset);
o << int8_t(BinaryConsts::End);
}
writeInlineBuffer(segment.data.data(), segment.data.size());
}
finishSection(start);
}
uint32_t WasmBinaryWriter::getFunctionIndex(Name name) const {
auto it = indexes.functionIndexes.find(name);
assert(it != indexes.functionIndexes.end());
return it->second;
}
uint32_t WasmBinaryWriter::getTableIndex(Name name) const {
auto it = indexes.tableIndexes.find(name);
assert(it != indexes.tableIndexes.end());
return it->second;
}
uint32_t WasmBinaryWriter::getGlobalIndex(Name name) const {
auto it = indexes.globalIndexes.find(name);
assert(it != indexes.globalIndexes.end());
return it->second;
}
uint32_t WasmBinaryWriter::getTagIndex(Name name) const {
auto it = indexes.tagIndexes.find(name);
assert(it != indexes.tagIndexes.end());
return it->second;
}
uint32_t WasmBinaryWriter::getTypeIndex(HeapType type) const {
auto it = indexedTypes.indices.find(type);
#ifndef NDEBUG
if (it == indexedTypes.indices.end()) {
std::cout << "Missing type: " << type << '\n';
assert(0);
}
#endif
return it->second;
}
void WasmBinaryWriter::writeTableDeclarations() {
if (importInfo->getNumDefinedTables() == 0) {
// std::cerr << std::endl << "(WasmBinaryWriter::writeTableDeclarations) No
// defined tables found. skipping" << std::endl;
return;
}
BYN_TRACE("== writeTableDeclarations\n");
auto start = startSection(BinaryConsts::Section::Table);
auto num = importInfo->getNumDefinedTables();
o << U32LEB(num);
ModuleUtils::iterDefinedTables(*wasm, [&](Table* table) {
writeType(table->type);
writeResizableLimits(table->initial,
table->max,
table->hasMax(),
/*shared=*/false,
/*is64*/ false);
});
finishSection(start);
}
void WasmBinaryWriter::writeElementSegments() {
size_t elemCount = wasm->elementSegments.size();
auto needingElemDecl = TableUtils::getFunctionsNeedingElemDeclare(*wasm);
if (!needingElemDecl.empty()) {
elemCount++;
}
if (elemCount == 0) {
return;
}
BYN_TRACE("== writeElementSegments\n");
auto start = startSection(BinaryConsts::Section::Element);
o << U32LEB(elemCount);
for (auto& segment : wasm->elementSegments) {
Index tableIdx = 0;
bool isPassive = segment->table.isNull();
// If the segment is MVP, we can use the shorter form.
bool usesExpressions = TableUtils::usesExpressions(segment.get(), wasm);
// The table index can and should be elided for active segments of table 0
// when table 0 has type funcref. This was the only type of segment
// supported by the MVP, which also did not support table indices in the
// segment encoding.
bool hasTableIndex = false;
if (!isPassive) {
tableIdx = getTableIndex(segment->table);
hasTableIndex =
tableIdx > 0 || wasm->getTable(segment->table)->type != Type::funcref;
}
uint32_t flags = 0;
if (usesExpressions) {
flags |= BinaryConsts::UsesExpressions;
}
if (isPassive) {
flags |= BinaryConsts::IsPassive;
} else if (hasTableIndex) {
flags |= BinaryConsts::HasIndex;
}
o << U32LEB(flags);
if (!isPassive) {
if (hasTableIndex) {
o << U32LEB(tableIdx);
}
writeExpression(segment->offset);
o << int8_t(BinaryConsts::End);
}
if (isPassive || hasTableIndex) {
if (usesExpressions) {
// elemType
writeType(segment->type);
} else {
// MVP elemKind of funcref
o << U32LEB(0);
}
}
o << U32LEB(segment->data.size());
if (usesExpressions) {
for (auto* item : segment->data) {
writeExpression(item);
o << int8_t(BinaryConsts::End);
}
} else {
for (auto& item : segment->data) {
// We've ensured that all items are ref.func.
auto& name = item->cast<RefFunc>()->func;
o << U32LEB(getFunctionIndex(name));
}
}
}
if (!needingElemDecl.empty()) {
o << U32LEB(BinaryConsts::IsPassive | BinaryConsts::IsDeclarative);
o << U32LEB(0); // type (indicating funcref)
o << U32LEB(needingElemDecl.size());
for (auto name : needingElemDecl) {
o << U32LEB(indexes.functionIndexes[name]);
}
}
finishSection(start);
}
void WasmBinaryWriter::writeTags() {
if (importInfo->getNumDefinedTags() == 0) {
return;
}
BYN_TRACE("== writeTags\n");
auto start = startSection(BinaryConsts::Section::Tag);
auto num = importInfo->getNumDefinedTags();
o << U32LEB(num);
ModuleUtils::iterDefinedTags(*wasm, [&](Tag* tag) {
BYN_TRACE("write one\n");
o << uint8_t(0); // Reserved 'attribute' field. Always 0.
o << U32LEB(getTypeIndex(tag->sig));
});
finishSection(start);
}
void WasmBinaryWriter::writeNames() {
BYN_TRACE("== writeNames\n");
auto start = startSection(BinaryConsts::Section::User);
writeInlineString(BinaryConsts::UserSections::Name);
// module name
if (emitModuleName && wasm->name.is()) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameModule);
writeEscapedName(wasm->name.str);
finishSubsection(substart);
}
if (!debugInfo) {
// We were only writing the module name.
finishSection(start);
return;
}
// function names
{
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameFunction);
o << U32LEB(indexes.functionIndexes.size());
Index emitted = 0;
auto add = [&](Function* curr) {
o << U32LEB(emitted);
writeEscapedName(curr->name.str);
emitted++;
};
ModuleUtils::iterImportedFunctions(*wasm, add);
ModuleUtils::iterDefinedFunctions(*wasm, add);
assert(emitted == indexes.functionIndexes.size());
finishSubsection(substart);
}
// local names
{
// Find all functions with at least one local name and only emit the
// subsection if there is at least one.
std::vector<std::pair<Index, Function*>> functionsWithLocalNames;
Index checked = 0;
auto check = [&](Function* curr) {
auto numLocals = curr->getNumLocals();
for (Index i = 0; i < numLocals; ++i) {
if (curr->hasLocalName(i)) {
functionsWithLocalNames.push_back({checked, curr});
break;
}
}
checked++;
};
ModuleUtils::iterImportedFunctions(*wasm, check);
ModuleUtils::iterDefinedFunctions(*wasm, check);
assert(checked == indexes.functionIndexes.size());
if (functionsWithLocalNames.size() > 0) {
// Otherwise emit those functions but only include locals with a name.
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameLocal);
o << U32LEB(functionsWithLocalNames.size());
Index emitted = 0;
for (auto& [index, func] : functionsWithLocalNames) {
// Pairs of (local index in IR, name).
std::vector<std::pair<Index, Name>> localsWithNames;
auto numLocals = func->getNumLocals();
for (Index i = 0; i < numLocals; ++i) {
if (func->hasLocalName(i)) {
localsWithNames.push_back({i, func->getLocalName(i)});
}
}
assert(localsWithNames.size());
o << U32LEB(index);
o << U32LEB(localsWithNames.size());
for (auto& [indexInFunc, name] : localsWithNames) {
// TODO: handle multivalue
Index indexInBinary;
auto iter = funcMappedLocals.find(func->name);
if (iter != funcMappedLocals.end()) {
indexInBinary = iter->second[{indexInFunc, 0}];
} else {
// No data on funcMappedLocals. That is only possible if we are an
// imported function, where there are no locals to map, and in that
// case the index is unchanged anyhow: parameters always have the
// same index, they are not mapped in any way.
assert(func->imported());
indexInBinary = indexInFunc;
}
o << U32LEB(indexInBinary);
writeEscapedName(name.str);
}
emitted++;
}
assert(emitted == functionsWithLocalNames.size());
finishSubsection(substart);
}
}
// type names
{
std::vector<HeapType> namedTypes;
for (auto& [type, _] : indexedTypes.indices) {
if (wasm->typeNames.count(type) && wasm->typeNames[type].name.is()) {
namedTypes.push_back(type);
}
}
if (!namedTypes.empty()) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameType);
o << U32LEB(namedTypes.size());
for (auto type : namedTypes) {
o << U32LEB(indexedTypes.indices[type]);
writeEscapedName(wasm->typeNames[type].name.str);
}
finishSubsection(substart);
}
}
// table names
{
std::vector<std::pair<Index, Table*>> tablesWithNames;
Index checked = 0;
auto check = [&](Table* curr) {
if (curr->hasExplicitName) {
tablesWithNames.push_back({checked, curr});
}
checked++;
};
ModuleUtils::iterImportedTables(*wasm, check);
ModuleUtils::iterDefinedTables(*wasm, check);
assert(checked == indexes.tableIndexes.size());
if (tablesWithNames.size() > 0) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameTable);
o << U32LEB(tablesWithNames.size());
for (auto& [index, table] : tablesWithNames) {
o << U32LEB(index);
writeEscapedName(table->name.str);
}
finishSubsection(substart);
}
}
// memory names
if (wasm->memory.exists && wasm->memory.hasExplicitName) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameMemory);
o << U32LEB(1) << U32LEB(0); // currently exactly 1 memory at index 0
writeEscapedName(wasm->memory.name.str);
finishSubsection(substart);
}
// global names
{
std::vector<std::pair<Index, Global*>> globalsWithNames;
Index checked = 0;
auto check = [&](Global* curr) {
if (curr->hasExplicitName) {
globalsWithNames.push_back({checked, curr});
}
checked++;
};
ModuleUtils::iterImportedGlobals(*wasm, check);
ModuleUtils::iterDefinedGlobals(*wasm, check);
assert(checked == indexes.globalIndexes.size());
if (globalsWithNames.size() > 0) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameGlobal);
o << U32LEB(globalsWithNames.size());
for (auto& [index, global] : globalsWithNames) {
o << U32LEB(index);
writeEscapedName(global->name.str);
}
finishSubsection(substart);
}
}
// elem segment names
{
std::vector<std::pair<Index, ElementSegment*>> elemsWithNames;
Index checked = 0;
for (auto& curr : wasm->elementSegments) {
if (curr->hasExplicitName) {
elemsWithNames.push_back({checked, curr.get()});
}
checked++;
}
assert(checked == indexes.elemIndexes.size());
if (elemsWithNames.size() > 0) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameElem);
o << U32LEB(elemsWithNames.size());
for (auto& [index, elem] : elemsWithNames) {
o << U32LEB(index);
writeEscapedName(elem->name.str);
}
finishSubsection(substart);
}
}
// data segment names
if (wasm->memory.exists) {
Index count = 0;
for (auto& seg : wasm->memory.segments) {
if (seg.name.is()) {
count++;
}
}
if (count) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameData);
o << U32LEB(count);
for (Index i = 0; i < wasm->memory.segments.size(); i++) {
auto& seg = wasm->memory.segments[i];
if (seg.name.is()) {
o << U32LEB(i);
writeEscapedName(seg.name.str);
}
}
finishSubsection(substart);
}
}
// TODO: label, type, and element names
// see: https://github.com/WebAssembly/extended-name-section
// GC field names
if (wasm->features.hasGC()) {
std::vector<HeapType> relevantTypes;
for (auto& type : indexedTypes.types) {
if (type.isStruct() && wasm->typeNames.count(type) &&
!wasm->typeNames[type].fieldNames.empty()) {
relevantTypes.push_back(type);
}
}
if (!relevantTypes.empty()) {
auto substart =
startSubsection(BinaryConsts::UserSections::Subsection::NameField);
o << U32LEB(relevantTypes.size());
for (Index i = 0; i < relevantTypes.size(); i++) {
auto type = relevantTypes[i];
o << U32LEB(indexedTypes.indices[type]);
std::unordered_map<Index, Name>& fieldNames =
wasm->typeNames.at(type).fieldNames;
o << U32LEB(fieldNames.size());
for (auto& [index, name] : fieldNames) {
o << U32LEB(index);
writeEscapedName(name.str);
}
}
finishSubsection(substart);
}
}
finishSection(start);
}
void WasmBinaryWriter::writeSourceMapUrl() {
BYN_TRACE("== writeSourceMapUrl\n");
auto start = startSection(BinaryConsts::Section::User);
writeInlineString(BinaryConsts::UserSections::SourceMapUrl);
writeInlineString(sourceMapUrl.c_str());
finishSection(start);
}
void WasmBinaryWriter::writeSymbolMap() {
std::ofstream file(symbolMap);
auto write = [&](Function* func) {
file << getFunctionIndex(func->name) << ":" << func->name.str << std::endl;
};
ModuleUtils::iterImportedFunctions(*wasm, write);
ModuleUtils::iterDefinedFunctions(*wasm, write);
file.close();
}
void WasmBinaryWriter::initializeDebugInfo() {
lastDebugLocation = {0, /* lineNumber = */ 1, 0};
}
void WasmBinaryWriter::writeSourceMapProlog() {
*sourceMap << "{\"version\":3,\"sources\":[";
for (size_t i = 0; i < wasm->debugInfoFileNames.size(); i++) {
if (i > 0) {
*sourceMap << ",";
}
// TODO respect JSON string encoding, e.g. quotes and control chars.
*sourceMap << "\"" << wasm->debugInfoFileNames[i] << "\"";
}
*sourceMap << "],\"names\":[],\"mappings\":\"";
}
static void writeBase64VLQ(std::ostream& out, int32_t n) {
uint32_t value = n >= 0 ? n << 1 : ((-n) << 1) | 1;
while (1) {
uint32_t digit = value & 0x1F;
value >>= 5;
if (!value) {
// last VLQ digit -- base64 codes 'A'..'Z', 'a'..'f'
out << char(digit < 26 ? 'A' + digit : 'a' + digit - 26);
break;
}
// more VLG digit will follow -- add continuation bit (0x20),
// base64 codes 'g'..'z', '0'..'9', '+', '/'
out << char(digit < 20
? 'g' + digit
: digit < 30 ? '0' + digit - 20 : digit == 30 ? '+' : '/');
}
}
void WasmBinaryWriter::writeSourceMapEpilog() {
// write source map entries
size_t lastOffset = 0;
Function::DebugLocation lastLoc = {0, /* lineNumber = */ 1, 0};
for (const auto& [offset, loc] : sourceMapLocations) {
if (lastOffset > 0) {
*sourceMap << ",";
}
writeBase64VLQ(*sourceMap, int32_t(offset - lastOffset));