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
use crate::tunables::Tunables;
use crate::WASM_MAX_PAGES;
use cranelift_entity::{EntityRef, PrimaryMap};
use cranelift_wasm::*;
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::convert::TryFrom;
use std::sync::Arc;
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub enum MemoryStyle {
Dynamic,
Static {
bound: u32,
},
}
impl MemoryStyle {
pub fn for_memory(memory: Memory, tunables: &Tunables) -> (Self, u64) {
let maximum = std::cmp::min(
memory.maximum.unwrap_or(WASM_MAX_PAGES),
if tunables.static_memory_bound_is_maximum {
std::cmp::min(tunables.static_memory_bound, WASM_MAX_PAGES)
} else {
WASM_MAX_PAGES
},
);
if memory.minimum <= maximum && maximum <= tunables.static_memory_bound {
return (
Self::Static {
bound: tunables.static_memory_bound,
},
tunables.static_memory_offset_guard_size,
);
}
(Self::Dynamic, tunables.dynamic_memory_offset_guard_size)
}
}
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub struct MemoryPlan {
pub memory: Memory,
pub style: MemoryStyle,
pub offset_guard_size: u64,
}
impl MemoryPlan {
pub fn for_memory(memory: Memory, tunables: &Tunables) -> Self {
let (style, offset_guard_size) = MemoryStyle::for_memory(memory, tunables);
Self {
memory,
style,
offset_guard_size,
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct MemoryInitializer {
pub memory_index: MemoryIndex,
pub base: Option<GlobalIndex>,
pub offset: u32,
pub data: Box<[u8]>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum MemoryInitialization {
Segmented(Vec<MemoryInitializer>),
Paged {
map: PrimaryMap<DefinedMemoryIndex, Vec<Option<Box<[u8]>>>>,
out_of_bounds: bool,
},
}
impl MemoryInitialization {
pub fn to_paged(&self, module: &Module) -> Option<Self> {
const WASM_PAGE_SIZE: usize = crate::WASM_PAGE_SIZE as usize;
match self {
Self::Paged { .. } => None,
Self::Segmented(initializers) => {
let num_defined_memories = module.memory_plans.len() - module.num_imported_memories;
let mut out_of_bounds = false;
let mut map = PrimaryMap::with_capacity(num_defined_memories);
for _ in 0..num_defined_memories {
map.push(Vec::new());
}
for initializer in initializers {
match (
module.defined_memory_index(initializer.memory_index),
initializer.base.is_some(),
) {
(None, _) | (_, true) => {
return None;
}
(Some(index), false) => {
if out_of_bounds {
continue;
}
let offset = usize::try_from(initializer.offset).unwrap();
let end = match offset.checked_add(initializer.data.len()) {
Some(end) => end,
None => {
out_of_bounds = true;
continue;
}
};
if end
> ((module.memory_plans[initializer.memory_index].memory.minimum
as usize)
* WASM_PAGE_SIZE)
{
out_of_bounds = true;
continue;
}
let pages = &mut map[index];
let mut page_index = offset / WASM_PAGE_SIZE;
let mut page_offset = offset % WASM_PAGE_SIZE;
let mut data_offset = 0;
let mut data_remaining = initializer.data.len();
if data_remaining == 0 {
continue;
}
loop {
if page_index >= pages.len() {
pages.resize(page_index + 1, None);
}
let page = pages[page_index].get_or_insert_with(|| {
vec![0; WASM_PAGE_SIZE].into_boxed_slice()
});
let len =
std::cmp::min(data_remaining, WASM_PAGE_SIZE - page_offset);
page[page_offset..page_offset + len].copy_from_slice(
&initializer.data[data_offset..(data_offset + len)],
);
if len == data_remaining {
break;
}
page_index += 1;
page_offset = 0;
data_offset += len;
data_remaining -= len;
}
}
};
}
Some(Self::Paged { map, out_of_bounds })
}
}
}
}
impl Default for MemoryInitialization {
fn default() -> Self {
Self::Segmented(Vec::new())
}
}
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub enum TableStyle {
CallerChecksSignature,
}
impl TableStyle {
pub fn for_table(_table: Table, _tunables: &Tunables) -> Self {
Self::CallerChecksSignature
}
}
#[derive(Debug, Clone, Hash, Serialize, Deserialize)]
pub struct TablePlan {
pub table: cranelift_wasm::Table,
pub style: TableStyle,
}
impl TablePlan {
pub fn for_table(table: Table, tunables: &Tunables) -> Self {
let style = TableStyle::for_table(table, tunables);
Self { table, style }
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TableInitializer {
pub table_index: TableIndex,
pub base: Option<GlobalIndex>,
pub offset: u32,
pub elements: Box<[FuncIndex]>,
}
#[derive(Debug, Copy, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
pub enum ModuleType {
Function(SignatureIndex),
Module(ModuleTypeIndex),
Instance(InstanceTypeIndex),
}
impl ModuleType {
pub fn unwrap_function(&self) -> SignatureIndex {
match self {
ModuleType::Function(f) => *f,
_ => panic!("not a function type"),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct Module {
pub name: Option<String>,
pub initializers: Vec<Initializer>,
pub exports: IndexMap<String, EntityIndex>,
pub start_func: Option<FuncIndex>,
pub table_initializers: Vec<TableInitializer>,
pub memory_initialization: MemoryInitialization,
pub passive_elements: Vec<Box<[FuncIndex]>>,
pub passive_elements_map: HashMap<ElemIndex, usize>,
#[serde(with = "passive_data_serde")]
pub passive_data: Vec<Arc<[u8]>>,
pub passive_data_map: HashMap<DataIndex, usize>,
pub func_names: HashMap<FuncIndex, String>,
pub types: PrimaryMap<TypeIndex, ModuleType>,
pub num_imported_funcs: usize,
pub num_imported_tables: usize,
pub num_imported_memories: usize,
pub num_imported_globals: usize,
pub functions: PrimaryMap<FuncIndex, SignatureIndex>,
pub table_plans: PrimaryMap<TableIndex, TablePlan>,
pub memory_plans: PrimaryMap<MemoryIndex, MemoryPlan>,
pub globals: PrimaryMap<GlobalIndex, Global>,
pub instances: PrimaryMap<InstanceIndex, InstanceTypeIndex>,
pub modules: PrimaryMap<ModuleIndex, ModuleTypeIndex>,
pub possibly_exported_funcs: HashSet<DefinedFuncIndex>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum Initializer {
Import {
name: String,
field: Option<String>,
index: EntityIndex,
},
AliasInstanceExport {
instance: InstanceIndex,
export: String,
},
Instantiate {
module: ModuleIndex,
args: IndexMap<String, EntityIndex>,
},
CreateModule {
artifact_index: usize,
artifacts: Vec<usize>,
modules: Vec<ModuleUpvar>,
},
DefineModule(usize),
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ModuleUpvar {
Inherit(usize),
Local(ModuleIndex),
}
impl Module {
pub fn new() -> Self {
Module::default()
}
pub fn get_passive_element(&self, index: ElemIndex) -> Option<&[FuncIndex]> {
let index = *self.passive_elements_map.get(&index)?;
Some(self.passive_elements[index].as_ref())
}
#[inline]
pub fn func_index(&self, defined_func: DefinedFuncIndex) -> FuncIndex {
FuncIndex::new(self.num_imported_funcs + defined_func.index())
}
#[inline]
pub fn defined_func_index(&self, func: FuncIndex) -> Option<DefinedFuncIndex> {
if func.index() < self.num_imported_funcs {
None
} else {
Some(DefinedFuncIndex::new(
func.index() - self.num_imported_funcs,
))
}
}
#[inline]
pub fn is_imported_function(&self, index: FuncIndex) -> bool {
index.index() < self.num_imported_funcs
}
#[inline]
pub fn table_index(&self, defined_table: DefinedTableIndex) -> TableIndex {
TableIndex::new(self.num_imported_tables + defined_table.index())
}
#[inline]
pub fn defined_table_index(&self, table: TableIndex) -> Option<DefinedTableIndex> {
if table.index() < self.num_imported_tables {
None
} else {
Some(DefinedTableIndex::new(
table.index() - self.num_imported_tables,
))
}
}
#[inline]
pub fn is_imported_table(&self, index: TableIndex) -> bool {
index.index() < self.num_imported_tables
}
#[inline]
pub fn memory_index(&self, defined_memory: DefinedMemoryIndex) -> MemoryIndex {
MemoryIndex::new(self.num_imported_memories + defined_memory.index())
}
#[inline]
pub fn defined_memory_index(&self, memory: MemoryIndex) -> Option<DefinedMemoryIndex> {
if memory.index() < self.num_imported_memories {
None
} else {
Some(DefinedMemoryIndex::new(
memory.index() - self.num_imported_memories,
))
}
}
#[inline]
pub fn is_imported_memory(&self, index: MemoryIndex) -> bool {
index.index() < self.num_imported_memories
}
#[inline]
pub fn global_index(&self, defined_global: DefinedGlobalIndex) -> GlobalIndex {
GlobalIndex::new(self.num_imported_globals + defined_global.index())
}
#[inline]
pub fn defined_global_index(&self, global: GlobalIndex) -> Option<DefinedGlobalIndex> {
if global.index() < self.num_imported_globals {
None
} else {
Some(DefinedGlobalIndex::new(
global.index() - self.num_imported_globals,
))
}
}
#[inline]
pub fn is_imported_global(&self, index: GlobalIndex) -> bool {
index.index() < self.num_imported_globals
}
pub fn imports(&self) -> impl Iterator<Item = (&str, Option<&str>, EntityType)> {
self.initializers.iter().filter_map(move |i| match i {
Initializer::Import { name, field, index } => {
Some((name.as_str(), field.as_deref(), self.type_of(*index)))
}
_ => None,
})
}
pub fn type_of(&self, index: EntityIndex) -> EntityType {
match index {
EntityIndex::Global(i) => EntityType::Global(self.globals[i]),
EntityIndex::Table(i) => EntityType::Table(self.table_plans[i].table),
EntityIndex::Memory(i) => EntityType::Memory(self.memory_plans[i].memory),
EntityIndex::Function(i) => EntityType::Function(self.functions[i]),
EntityIndex::Instance(i) => EntityType::Instance(self.instances[i]),
EntityIndex::Module(i) => EntityType::Module(self.modules[i]),
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[allow(missing_docs)]
pub struct TypeTables {
pub wasm_signatures: PrimaryMap<SignatureIndex, WasmFuncType>,
pub module_signatures: PrimaryMap<ModuleTypeIndex, ModuleSignature>,
pub instance_signatures: PrimaryMap<InstanceTypeIndex, InstanceSignature>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModuleSignature {
pub imports: IndexMap<String, EntityType>,
pub exports: InstanceTypeIndex,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct InstanceSignature {
pub exports: IndexMap<String, EntityType>,
}
mod passive_data_serde {
use super::Arc;
use serde::{de::SeqAccess, de::Visitor, ser::SerializeSeq, Deserializer, Serializer};
use std::fmt;
pub(super) fn serialize<S>(data: &Vec<Arc<[u8]>>, ser: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = ser.serialize_seq(Some(data.len()))?;
for v in data {
seq.serialize_element(v.as_ref())?;
}
seq.end()
}
struct PassiveDataVisitor;
impl<'de> Visitor<'de> for PassiveDataVisitor {
type Value = Vec<Arc<[u8]>>;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a passive data sequence")
}
fn visit_seq<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: SeqAccess<'de>,
{
let mut data = Vec::with_capacity(access.size_hint().unwrap_or(0));
while let Some(value) = access.next_element::<Vec<u8>>()? {
data.push(value.into());
}
Ok(data)
}
}
pub(super) fn deserialize<'de, D>(de: D) -> Result<Vec<Arc<[u8]>>, D::Error>
where
D: Deserializer<'de>,
{
de.deserialize_seq(PassiveDataVisitor)
}
}