forked from bytecodealliance/wasm-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinking.rs
More file actions
2134 lines (1906 loc) · 73.1 KB
/
Copy pathlinking.rs
File metadata and controls
2134 lines (1906 loc) · 73.1 KB
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
//! Support for "pseudo-dynamic", shared-everything linking of Wasm modules into a component.
//!
//! This implements [shared-everything
//! linking](https://github.com/WebAssembly/component-model/blob/main/design/mvp/examples/SharedEverythingDynamicLinking.md),
//! taking as input one or more [dynamic
//! library](https://github.com/WebAssembly/tool-conventions/blob/main/DynamicLinking.md) modules and producing a
//! component whose type is the union of any `component-type*` custom sections found in the input modules.
//!
//! The entry point into this process is `Linker::encode`, which analyzes and topologically sorts the input
//! modules, then synthesizes two additional modules:
//!
//! - `main` AKA `env`: hosts the component's single memory and function table and exports any functions needed to
//! break dependency cycles discovered in the input modules. Those functions use `call.indirect` to invoke the real
//! functions, references to which are placed in the table by the `init` module.
//!
//! - `init`: populates the function table as described above, initializes global variables per the dynamic linking
//! tool convention, and calls any static constructors and/or link-time fixup functions
//!
//! `Linker` also supports synthesizing `dlopen`/`dlsym` lookup tables which allow symbols to be resolved at
//! runtime. Note that this is not true dynamic linking, since all the code is baked into the component ahead of
//! time -- we simply allow runtime resolution of already-resident definitions. This is sufficient to support
//! dynamic language FFI features such as Python native extensions, provided the required libraries are linked
//! ahead-of-time.
use {
crate::SemverCompat,
crate::encoding::{ComponentEncoder, Instance, Item, LibraryInfo, MainOrAdapter},
anyhow::{Context, Result, anyhow, bail},
indexmap::{IndexMap, IndexSet, map::Entry},
metadata::{Export, ExportKey, FunctionType, GlobalType, Metadata, Type, ValueType},
std::{
cmp,
collections::{BTreeMap, HashMap, HashSet},
fmt::Debug,
hash::Hash,
iter,
},
wasm_encoder::{
CodeSection, ConstExpr, DataSection, ElementSection, Elements, EntityType, ExportKind,
ExportSection, Function, FunctionSection, GlobalSection, ImportSection, MemArg,
MemorySection, MemoryType, Module, RawCustomSection, RefType, StartSection, TableSection,
TableType, TypeSection, ValType,
},
wasmparser::SymbolFlags,
};
mod metadata;
const PAGE_SIZE_BYTES: u32 = 65536;
// This matches the default stack size LLVM produces:
pub const DEFAULT_STACK_SIZE_BYTES: u32 = 16 * PAGE_SIZE_BYTES;
const HEAP_ALIGNMENT_BYTES: u32 = 16;
const STUB_LIBRARY_NAME: &str = "wit-component:stubs";
const CABI_REALLOC: &str = "cabi_realloc";
static EMPTY_FUNCTION_TYPE: FunctionType = FunctionType {
parameters: Vec::new(),
results: Vec::new(),
};
/// Symbols to re-export from the `env` module regardless of whether any
/// libraries import them, since
/// `EncodingState::create_export_task_initialization_wrappers` needs to be able
/// to call them.
static ENV_REEXPORTS: &[&str] = &[metadata::INIT_TASK, metadata::INIT_ASYNC_TASK];
enum Address<'a> {
Function(u32),
Global(&'a str),
}
/// Represents a `dlopen`/`dlsym` lookup table enabling runtime symbol resolution
///
/// The top level of this table is a sorted list of library names and offsets, each pointing to a sorted list of
/// symbol names and offsets. See ../dl/src/lib.rs for how this is used at runtime.
struct DlOpenables<'a> {
/// Offset into the main module's table where function references will be stored
table_base: u32,
/// Offset into the main module's memory where the lookup table will be stored
memory_base: u32,
/// The lookup table itself
buffer: Vec<u8>,
/// Linear memory addresses where global variable addresses will live
///
/// The init module will fill in the correct values at instantiation time.
global_addresses: Vec<(&'a str, &'a str, u32)>,
/// Number of function references to be stored in the main module's table
function_count: u32,
/// Linear memory address where the root of the lookup table will reside
///
/// This can be different from `memory_base` depending on how the tree of libraries and symbols is laid out in
/// memory.
libraries_address: u32,
}
impl<'a> DlOpenables<'a> {
/// Construct a lookup table containing all "dlopen-able" libraries and their symbols using the specified table
/// and memory offsets.
fn new(table_base: u32, memory_base: u32, metadata: &'a [Metadata<'a>]) -> Self {
let mut function_count = 0;
let mut buffer = Vec::new();
let mut global_addresses = Vec::new();
let mut libraries = metadata
.iter()
.filter(|metadata| metadata.dl_openable)
.map(|metadata| {
let name_address = memory_base + u32::try_from(buffer.len()).unwrap();
write_bytes_padded(&mut buffer, metadata.name.as_bytes());
let mut symbols = metadata
.exports
.iter()
.filter_map(|export| {
let name_address = memory_base + u32::try_from(buffer.len()).unwrap();
write_bytes_padded(&mut buffer, export.key.name.as_bytes());
let address = match &export.key.ty {
Type::Function(_) => Address::Function(
table_base + get_and_increment(&mut function_count),
),
Type::Global(_) => Address::Global(export.key.name),
Type::Tag(_) => return None,
};
Some((export.key.name, name_address, address))
})
.collect::<Vec<_>>();
symbols.sort_by_key(|(name, ..)| *name);
let start = buffer.len();
for (name, name_address, address) in symbols {
write_u32(&mut buffer, u32::try_from(name.len()).unwrap());
write_u32(&mut buffer, name_address);
match address {
Address::Function(address) => write_u32(&mut buffer, address),
Address::Global(name) => {
global_addresses.push((
metadata.name,
name,
memory_base + u32::try_from(buffer.len()).unwrap(),
));
write_u32(&mut buffer, 0);
}
}
}
(
metadata.name,
name_address,
metadata.exports.len(),
memory_base + u32::try_from(start).unwrap(),
)
})
.collect::<Vec<_>>();
libraries.sort_by_key(|(name, ..)| *name);
let start = buffer.len();
for (name, name_address, count, symbols) in &libraries {
write_u32(&mut buffer, u32::try_from(name.len()).unwrap());
write_u32(&mut buffer, *name_address);
write_u32(&mut buffer, u32::try_from(*count).unwrap());
write_u32(&mut buffer, *symbols);
}
let libraries_address = memory_base + u32::try_from(buffer.len()).unwrap();
write_u32(&mut buffer, u32::try_from(libraries.len()).unwrap());
write_u32(&mut buffer, memory_base + u32::try_from(start).unwrap());
Self {
table_base,
memory_base,
buffer,
global_addresses,
function_count,
libraries_address,
}
}
}
/// The layout of the whole program's thread-local storage bookkeeping.
///
/// This generates a C structure that matches this layout:
///
/// ```c
/// struct {
/// size_t num_libraries;
/// struct {
/// size_t __tls_size;
/// size_t __tls_align;
/// void (*__wasm_init_tls)(void*);
/// } *library_info;
/// void **main_thread_tls_base;
/// } __wasm_program_tls_info;
/// ```
///
/// where `main_thread_tls_base` is placed first, then `library_info`, then this
/// structure itself.
#[derive(Default)]
struct TlsLayout {
/// Address of the `main_thread_tls_base` array.
///
/// This is left zero-initialized; no data segment covers it.
main_thread_tls_base: u32,
/// Address of the `library_info` array.
library_info: u32,
/// Address of the `__wasm_program_tls_info` struct itself.
program_info: u32,
/// The libraries which have thread-local storage, in the order they appear
/// in `library_info`, paired with the table index reserved for each one's
/// `__wasm_init_tls`.
init_tls_functions: Vec<(usize, u32)>,
/// For each library, the slot it uses in the array of TLS base pointers, or
/// `None` if it has no thread-local storage of its own.
slots: Vec<Option<u32>>,
/// Static contents of the `library_info` array and the
/// `__wasm_program_tls_info` struct, which live contiguously starting at
/// `library_info`.
buffer: Vec<u8>,
}
impl TlsLayout {
/// Reserve linear memory and table space for the layout described above,
/// advancing `memory_offset` and `table_offset` past what's used.
///
/// Nothing is reserved for a program which doesn't use thread-local storage
/// at all, and the `__wasm_program_tls_info` half is skipped unless some
/// library actually asks for it, which is only the case when the program
/// might spawn a thread.
fn new(metadata: &[Metadata], memory_offset: &mut u32, table_offset: &mut u32) -> Self {
let needs_tls_base = metadata
.iter()
.any(|m| m.needs_get_tls_base || m.needs_set_tls_base);
let needs_program_info = metadata.iter().any(|m| m.needs_program_tls_info);
if !needs_tls_base && !needs_program_info {
return Self::default();
}
// Filter out libraries that don't have TLS, and then sort this by
// biggest alignment first to help minimize the size of TLS blocks
// allocated.
let mut libraries = metadata
.iter()
.enumerate()
.filter(|(_, metadata)| metadata.has_tls_info)
.map(|(index, _)| index)
.collect::<Vec<_>>();
libraries.sort_by_key(|&index| cmp::Reverse(metadata[index].tls_align));
let mut slots = vec![None; metadata.len()];
for (slot, index) in libraries.iter().enumerate() {
slots[*index] = Some(u32::try_from(slot).unwrap());
}
let count = u32::try_from(libraries.len()).unwrap();
// Allocate space for `main_thread_tls_base`
*memory_offset = align(*memory_offset, 4);
let main_thread_tls_base = *memory_offset;
*memory_offset += count * 4;
let mut library_info = 0;
let mut program_info = 0;
let mut init_tls_functions = Vec::new();
let mut buffer = Vec::new();
if needs_program_info {
// Allocate space for `library_info`
library_info = *memory_offset;
*memory_offset += count * 12;
// Allocate space for `__wasm_program_tls_info`
program_info = *memory_offset;
*memory_offset += 12;
init_tls_functions = libraries
.iter()
.map(|&index| (index, get_and_increment(table_offset)))
.collect::<Vec<_>>();
for &(index, table_index) in &init_tls_functions {
write_u32(&mut buffer, metadata[index].tls_size);
write_u32(&mut buffer, metadata[index].tls_align);
write_u32(&mut buffer, table_index);
}
write_u32(&mut buffer, count);
write_u32(&mut buffer, library_info);
write_u32(&mut buffer, main_thread_tls_base);
}
Self {
main_thread_tls_base,
library_info,
program_info,
init_tls_functions,
slots,
buffer,
}
}
/// The slot library `index` uses in the array of TLS base pointers.
fn slot(&self, index: usize) -> Option<u32> {
self.slots.get(index).copied().flatten()
}
}
fn write_u32(buffer: &mut Vec<u8>, value: u32) {
buffer.extend(value.to_le_bytes());
}
fn write_bytes_padded(buffer: &mut Vec<u8>, bytes: &[u8]) {
buffer.extend(bytes);
let len = u32::try_from(bytes.len()).unwrap();
for _ in len..align(len, 4) {
buffer.push(0);
}
}
fn align(a: u32, b: u32) -> u32 {
assert!(b.is_power_of_two());
(a + (b - 1)) & !(b - 1)
}
fn get_and_increment(n: &mut u32) -> u32 {
let v = *n;
*n += 1;
v
}
fn const_u32(a: u32) -> ConstExpr {
ConstExpr::i32_const(a as i32)
}
/// Helper trait for determining the size of a set or map
trait Length {
fn len(&self) -> usize;
}
impl<T> Length for HashSet<T> {
fn len(&self) -> usize {
HashSet::len(self)
}
}
impl<K, V> Length for HashMap<K, V> {
fn len(&self) -> usize {
HashMap::len(self)
}
}
impl<T> Length for IndexSet<T> {
fn len(&self) -> usize {
IndexSet::len(self)
}
}
impl<K, V> Length for IndexMap<K, V> {
fn len(&self) -> usize {
IndexMap::len(self)
}
}
/// Extension trait for collecting into a set or map and asserting that there were no duplicate entries in the
/// source iterator.
trait CollectUnique: Iterator + Sized {
fn collect_unique<T: FromIterator<Self::Item> + Length>(self) -> T {
let tmp = self.collect::<Vec<_>>();
let len = tmp.len();
let result = tmp.into_iter().collect::<T>();
assert!(
result.len() == len,
"one or more duplicate items detected when collecting into set or map"
);
result
}
}
impl<T: Iterator> CollectUnique for T {}
/// Extension trait for inserting into a map and asserting that an entry did not already exist for the key
trait InsertUnique {
type Key;
type Value;
fn insert_unique(&mut self, k: Self::Key, v: Self::Value);
}
impl<K: Hash + Eq + PartialEq + Debug, V: Debug> InsertUnique for HashMap<K, V> {
type Key = K;
type Value = V;
fn insert_unique(&mut self, k: Self::Key, v: Self::Value) {
if let Some(old_v) = self.get(&k) {
panic!(
"duplicate item inserted into map for key {k:?} (old value: {old_v:?}; new value: {v:?})"
);
}
self.insert(k, v);
}
}
/// Synthesize the "main" module for the component, responsible for exporting functions which break cyclic
/// dependencies, as well as hosting the memory and function table.
fn make_env_module<'a>(
metadata: &'a [Metadata<'a>],
env_exports: &[EnvExport<'_>],
cabi_realloc_exporter: Option<&str>,
stack_size_bytes: u32,
) -> (Vec<u8>, DlOpenables<'a>, TlsLayout, u32) {
// TODO: deduplicate types
let mut types = TypeSection::new();
let mut imports = ImportSection::new();
let mut import_map = IndexMap::new();
let mut function_count = 0;
let mut global_offset = 0;
let mut wasi_start = None;
for metadata in metadata {
for import in &metadata.imports {
if let Entry::Vacant(entry) = import_map.entry(import) {
imports.import(
import.module,
import.name,
match &import.ty {
Type::Function(ty) => {
let index = get_and_increment(&mut function_count);
entry.insert(index);
types.ty().function(
ty.parameters.iter().copied().map(ValType::from),
ty.results.iter().copied().map(ValType::from),
);
EntityType::Function(index)
}
Type::Global(ty) => {
entry.insert(get_and_increment(&mut global_offset));
EntityType::Global(wasm_encoder::GlobalType {
val_type: ty.ty.into(),
mutable: ty.mutable,
shared: ty.shared,
})
}
Type::Tag(_) => continue,
},
);
}
}
if metadata.has_wasi_start {
if wasi_start.is_some() {
panic!("multiple libraries export {}", metadata::START);
}
let index = get_and_increment(&mut function_count);
types.ty().function(vec![], vec![]);
imports.import(metadata.name, metadata::START, EntityType::Function(index));
wasi_start = Some(index);
}
}
let mut memory_offset = stack_size_bytes;
// Table offset 0 is reserved for the null function pointer.
// This convention follows wasm-ld's table layout:
// https://github.com/llvm/llvm-project/blob/913622d012f72edb5ac3a501cef8639d0ebe471b/lld/wasm/Driver.cpp#L581-L584
let mut table_offset = 1;
let mut globals = GlobalSection::new();
let mut exports = ExportSection::new();
if let Some(exporter) = cabi_realloc_exporter {
let index = get_and_increment(&mut function_count);
types.ty().function([ValType::I32; 4], [ValType::I32]);
imports.import(exporter, CABI_REALLOC, EntityType::Function(index));
exports.export(CABI_REALLOC, ExportKind::Func, index);
}
// If tls base shims are being generated, and something might spawn a
// thread, then the shims generated will need access to `context.get 1`.
let indirect_tls_base = metadata
.iter()
.any(|m| m.needs_get_tls_base || m.needs_set_tls_base)
&& metadata.iter().any(|m| m.uses_thread_new_indirect);
let tls_context_get = if indirect_tls_base {
let index = get_and_increment(&mut function_count);
types.ty().function([], [ValType::I32]);
imports.import(
metadata::ROOT,
metadata::CONTEXT_GET_1,
EntityType::Function(index),
);
Some(index)
} else {
None
};
let mut add_global_export = |name: &str, value, mutable| {
let index = globals.len();
globals.global(
wasm_encoder::GlobalType {
val_type: ValType::I32,
mutable,
shared: false,
},
&const_u32(value),
);
exports.export(name, ExportKind::Global, index);
};
let dl_openables = DlOpenables::new(table_offset, memory_offset, metadata);
if metadata.iter().any(|m| m.needs_libdl_libraries) {
add_global_export(
metadata::LIBDL_LIBRARIES,
dl_openables.libraries_address,
true,
);
}
table_offset += dl_openables.function_count;
memory_offset += u32::try_from(dl_openables.buffer.len()).unwrap();
let tls = TlsLayout::new(metadata, &mut memory_offset, &mut table_offset);
if metadata.iter().any(|m| m.needs_program_tls_info) {
add_global_export(metadata::PROGRAM_TLS_INFO, tls.program_info, true);
}
let memory_size = {
if metadata.iter().any(|m| m.needs_stack_pointer) {
add_global_export(metadata::STACK_POINTER, stack_size_bytes, true);
}
if metadata.iter().any(|m| m.needs_init_stack_pointer) {
add_global_export(metadata::INIT_STACK_POINTER, stack_size_bytes, false);
}
// Binaryen's Asyncify transform for shared everything linking requires these globals
// to be provided from env module
let has_asyncified_module = metadata.iter().any(|m| m.is_asyncified);
if has_asyncified_module {
add_global_export(metadata::ASYNCIFY_STATE, 0, true);
add_global_export(metadata::ASYNCIFY_DATA, 0, true);
}
// The libc.so in WASI-SDK 28+ requires these:
if metadata.iter().any(|m| m.needs_stack_high) {
add_global_export(metadata::STACK_HIGH, stack_size_bytes, true);
}
if metadata.iter().any(|m| m.needs_stack_low) {
add_global_export(metadata::STACK_LOW, 0, true);
}
for metadata in metadata {
memory_offset = align(memory_offset, 1 << metadata.mem_info.memory_alignment);
table_offset = align(table_offset, 1 << metadata.mem_info.table_alignment);
add_global_export(
&format!("{}:memory_base", metadata.name),
memory_offset,
false,
);
add_global_export(
&format!("{}:table_base", metadata.name),
table_offset,
false,
);
memory_offset += metadata.mem_info.memory_size;
table_offset += metadata.mem_info.table_size;
for import in &metadata.memory_address_imports {
// Note that we initialize this to zero and let the init module compute the real value at
// instantiation time.
add_global_export(&format!("{}:{import}", metadata.name), 0, true);
}
}
{
let offsets = env_exports
.iter()
.enumerate()
.map(|(offset, EnvExport { name, exporter, .. })| {
(
*name,
(
table_offset + u32::try_from(offset).unwrap(),
metadata[*exporter].name == STUB_LIBRARY_NAME,
),
)
})
.collect_unique::<HashMap<_, _>>();
for metadata in metadata {
for import in &metadata.table_address_imports {
let &(offset, is_stub) = offsets.get(import).unwrap();
if is_stub
&& metadata
.env_imports
.iter()
.any(|e| e.0 == *import && e.1.1.contains(SymbolFlags::BINDING_WEAK))
{
add_global_export(&format!("{}:{import}", metadata.name), 0, true);
} else {
add_global_export(&format!("{}:{import}", metadata.name), offset, true);
}
}
}
}
memory_offset = align(memory_offset, HEAP_ALIGNMENT_BYTES);
if metadata.iter().any(|m| m.needs_heap_base) {
add_global_export(metadata::HEAP_BASE, memory_offset, true);
}
let heap_end = align(memory_offset, PAGE_SIZE_BYTES);
if metadata.iter().any(|m| m.needs_heap_end) {
add_global_export(metadata::HEAP_END, heap_end, true);
}
heap_end / PAGE_SIZE_BYTES
};
let indirection_table_base = table_offset;
let mut functions = FunctionSection::new();
let mut code = CodeSection::new();
for export in env_exports {
let index = get_and_increment(&mut function_count);
types.ty().function(
export.ty.parameters.iter().copied().map(ValType::from),
export.ty.results.iter().copied().map(ValType::from),
);
functions.function(u32::try_from(index).unwrap());
let mut function = Function::new([]);
for local in 0..export.ty.parameters.len() {
function
.instructions()
.local_get(u32::try_from(local).unwrap());
}
function
.instructions()
.i32_const(i32::try_from(table_offset).unwrap())
.call_indirect(0, u32::try_from(index).unwrap())
.end();
code.function(&function);
exports.export(export.name, ExportKind::Func, index);
table_offset += 1;
}
// Define a distinct `__wasm_{get,set}_tls_base` pair for each library that
// needs one. Each pair reads and writes that library's slot of the array of
// pointers described by `TlsLayout`.
for (index, metadata) in metadata.iter().enumerate() {
// A library with no thread-local storage of its own has no slot in the
// array. If it still imports these then synthesize functions that trap
// since they shouldn't ever be called.
let Some(slot) = tls.slot(index) else {
for (needed, name, params, results) in [
(
metadata.needs_get_tls_base,
metadata::GET_TLS_BASE,
&[][..],
&[ValType::I32][..],
),
(
metadata.needs_set_tls_base,
metadata::SET_TLS_BASE,
&[ValType::I32][..],
&[][..],
),
] {
if !needed {
continue;
}
let func = get_and_increment(&mut function_count);
types
.ty()
.function(params.iter().copied(), results.iter().copied());
functions.function(func);
let mut function = Function::new([]);
function.instructions().unreachable().end();
code.function(&function);
exports.export(&format!("{}:{name}", metadata.name), ExportKind::Func, func);
}
continue;
};
let mem_arg = MemArg {
offset: u64::from(slot * 4),
align: 2,
memory_index: 0,
};
if metadata.needs_get_tls_base {
let func = get_and_increment(&mut function_count);
types.ty().function([], [ValType::I32]);
functions.function(func);
let mut function = Function::new([]);
// With coop threads the base pointer is in `context.get 1`. Without
// coop threads the base pointer is `main_thread_tls_base` itself.
match tls_context_get {
Some(get) => {
function.instructions().call(get);
}
None => {
function
.instructions()
.i32_const(i32::try_from(tls.main_thread_tls_base).unwrap());
}
}
function.instructions().i32_load(mem_arg).end();
code.function(&function);
exports.export(
&format!("{}:{}", metadata.name, metadata::GET_TLS_BASE),
ExportKind::Func,
func,
);
}
if metadata.needs_set_tls_base {
let func = get_and_increment(&mut function_count);
types.ty().function([ValType::I32], []);
functions.function(func);
let mut function = Function::new_with_locals_types(if tls_context_get.is_some() {
vec![ValType::I32]
} else {
vec![]
});
// With coop threads this intrinsic conditionally initializes
// `main_thread_tls_base` based on `context.get 1`. Otherwise it
// writes through to it if it's set.
//
// Without coop threads this is updating `main_thread_tls_base`.
match tls_context_get {
Some(get) => {
function
.instructions()
.call(get)
.local_tee(1)
.i32_eqz()
.if_(wasm_encoder::BlockType::Empty)
.i32_const(i32::try_from(tls.main_thread_tls_base).unwrap())
.local_get(0)
.i32_store(mem_arg)
.else_()
.local_get(1)
.local_get(0)
.i32_store(mem_arg)
.end()
.end();
}
None => {
function
.instructions()
.i32_const(i32::try_from(tls.main_thread_tls_base).unwrap())
.local_get(0)
.i32_store(mem_arg)
.end();
}
}
code.function(&function);
exports.export(
&format!("{}:{}", metadata.name, metadata::SET_TLS_BASE),
ExportKind::Func,
func,
);
}
}
for (import, offset) in import_map {
exports.export(
&format!("{}:{}", import.module, import.name),
ExportKind::from(&import.ty),
offset,
);
}
if let Some(index) = wasi_start {
exports.export(metadata::START, ExportKind::Func, index);
}
let mut module = Module::new();
module.section(&types);
module.section(&imports);
module.section(&functions);
{
let mut tables = TableSection::new();
tables.table(TableType {
element_type: RefType::FUNCREF,
minimum: table_offset.into(),
maximum: None,
table64: false,
shared: false,
});
exports.export(metadata::INDIRECT_FUNCTION_TABLE, ExportKind::Table, 0);
module.section(&tables);
}
{
let mut memories = MemorySection::new();
memories.memory(MemoryType {
minimum: u64::from(memory_size),
maximum: None,
memory64: false,
shared: false,
page_size_log2: None,
});
exports.export(metadata::MEMORY, ExportKind::Memory, 0);
module.section(&memories);
}
module.section(&globals);
module.section(&exports);
module.section(&code);
module.section(&RawCustomSection(
&crate::base_producers().raw_custom_section(),
));
let module = module.finish();
wasmparser::validate(&module).unwrap();
(module, dl_openables, tls, indirection_table_base)
}
/// Synthesize the "init" module, responsible for initializing global variables per the dynamic linking tool
/// convention and calling any static constructors and/or link-time fixup functions.
///
/// This module also contains the data segment for the `dlopen`/`dlsym` lookup table.
fn make_init_module(
metadata: &[Metadata],
exporters: &IndexMap<&ExportKey, (&str, &Export)>,
env_exports: &[EnvExport<'_>],
dl_openables: DlOpenables,
tls: TlsLayout,
indirection_table_base: u32,
) -> Result<Vec<u8>> {
let mut module = Module::new();
// TODO: deduplicate types
let mut types = TypeSection::new();
types.ty().function([], []);
let thunk_ty = 0;
types.ty().function([ValType::I32], []);
let init_tls_ty = 1;
let mut type_offset = 2;
for metadata in metadata {
if metadata.dl_openable {
for export in &metadata.exports {
if let Type::Function(ty) = &export.key.ty {
types.ty().function(
ty.parameters.iter().copied().map(ValType::from),
ty.results.iter().copied().map(ValType::from),
);
}
}
}
}
for export in env_exports {
types.ty().function(
export.ty.parameters.iter().copied().map(ValType::from),
export.ty.results.iter().copied().map(ValType::from),
);
}
module.section(&types);
let mut imports = ImportSection::new();
imports.import(
metadata::ENV,
metadata::MEMORY,
MemoryType {
minimum: 0,
maximum: None,
memory64: false,
shared: false,
page_size_log2: None,
},
);
imports.import(
metadata::ENV,
metadata::INDIRECT_FUNCTION_TABLE,
TableType {
element_type: RefType::FUNCREF,
minimum: 0,
maximum: None,
table64: false,
shared: false,
},
);
let mut global_count = 0;
let mut global_map = HashMap::new();
let mut add_global_import = |imports: &mut ImportSection, module: &str, name: &str, mutable| {
*global_map
.entry((module.to_owned(), name.to_owned()))
.or_insert_with(|| {
imports.import(
module,
name,
wasm_encoder::GlobalType {
val_type: ValType::I32,
mutable,
shared: false,
},
);
get_and_increment(&mut global_count)
})
};
let mut function_count = 0;
let mut function_map = HashMap::new();
let mut add_function_import = |imports: &mut ImportSection, module: &str, name: &str, ty| {
*function_map
.entry((module.to_owned(), name.to_owned()))
.or_insert_with(|| {
imports.import(module, name, EntityType::Function(ty));
get_and_increment(&mut function_count)
})
};
let mut start = Function::new([]);
let mut names = HashMap::new();
for (index, metadata) in metadata.iter().enumerate() {
names.insert_unique(index, metadata.name);
}
for (exporter, export, address) in dl_openables.global_addresses.iter() {
let memory_base = add_global_import(
&mut imports,
metadata::ENV,
&format!("{exporter}:memory_base"),
false,
);
let export = add_global_import(&mut imports, exporter, export, false);
start
.instructions()
.i32_const(i32::try_from(*address).unwrap())
.global_get(memory_base)
.global_get(export)
.i32_add()
.i32_store(MemArg {
offset: 0,
align: 2,
memory_index: 0,
});
}
for metadata in metadata {
for import in &metadata.memory_address_imports {
let (exporter, _) = find_offset_exporter(import, exporters)?;
let memory_base = add_global_import(
&mut imports,
metadata::ENV,
&format!("{exporter}:memory_base"),
false,
);
let offset = add_global_import(&mut imports, exporter, import, false);
let address = add_global_import(
&mut imports,
metadata::ENV,
&format!("{}:{import}", metadata.name),
true,
);
start
.instructions()
.global_get(memory_base)
.global_get(offset)
.i32_add()
.global_set(address);
}
}
for metadata in metadata {
if metadata.has_data_relocs {
let func = add_function_import(
&mut imports,
metadata.name,
metadata::APPLY_DATA_RELOCS,
thunk_ty,
);
start.instructions().call(func);
}
}
let mut init_task_exporter = exporters
.get(&ExportKey {
name: metadata::INIT_TASK,
ty: Type::Function(EMPTY_FUNCTION_TYPE.clone()),