spacewasm 0.4.1

A no_std WebAssembly 1.0 decoder, validator, and interpreter for on-board spacecraft use
Documentation
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
//! Methods to read Wasm Types from a [Reader] object.
//!
//! See: <https://webassembly.github.io/spec/core/binary/types.html>

use crate::util::String;
use crate::{Reader, ValidationError, Vec};

/// A pointer and length into a UTF-8 string on the original Wasm
pub struct Name;

impl Name {
    pub(crate) fn read(wasm: &mut Reader) -> Result<String, ValidationError> {
        wasm.read_vec(|r| r.read_u8())?.try_into()
    }
}

/// Value types classify the individual values that WebAssembly code can compute with and the values
/// that a variable accepts.
/// <https://www.w3.org/TR/wasm-core-1/#syntax-valtype>
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
#[repr(u8)]
pub enum ValType {
    I32,
    I64,
    F32,
    F64,
}

impl From<u8> for ValType {
    fn from(val: u8) -> Self {
        #[cfg(feature = "strict-assertions")]
        match val {
            0 => ValType::I32,
            1 => ValType::I64,
            2 => ValType::F32,
            3 => ValType::F64,
            _ => unreachable!(),
        }

        #[cfg(not(feature = "strict-assertions"))]
        unsafe {
            core::mem::transmute(val)
        }
    }
}

/// A runtime type-tracked value
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Value {
    I32(i32),
    I64(i64),
    F32(f32),
    F64(f64),
}

impl ValType {
    pub fn size(&self) -> usize {
        match self {
            ValType::I32 => 4,
            ValType::I64 => 8,
            ValType::F32 => 4,
            ValType::F64 => 8,
        }
    }

    fn convert(v: u8) -> Result<ValType, ValidationError> {
        // Value types are encoded by a single byte.
        use ValType::*;
        match v {
            0x7F => Ok(I32),
            0x7E => Ok(I64),
            0x7D => Ok(F32),
            0x7C => Ok(F64),
            other => Err(ValidationError::MalformedValueType(other)),
        }
    }

    pub(crate) fn read(wasm: &mut Reader) -> Result<Self, ValidationError> {
        ValType::convert(wasm.read_u8()?)
    }
}

/// A compile-time/configured value
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawValue(u64);

impl RawValue {
    pub fn from_32(u: u32) -> RawValue {
        RawValue(u as u64)
    }

    pub fn from_64(u: u64) -> RawValue {
        RawValue(u)
    }

    pub fn from_i32(i: i32) -> RawValue {
        RawValue::from_32(i as u32)
    }

    pub fn from_i64(i: i64) -> RawValue {
        RawValue::from_64(i as u64)
    }

    pub fn from_f32(f: f32) -> RawValue {
        RawValue::from_32(f.to_bits())
    }

    pub fn from_f64(f: f64) -> RawValue {
        RawValue::from_64(f.to_bits())
    }

    pub fn write_32(&mut self, i: u32) {
        self.0 = i as u64;
    }

    pub fn write_64(&mut self, i: u64) {
        self.0 = i;
    }

    pub fn write_i32(&mut self, i: i32) {
        self.0 = i as u64;
    }

    pub fn write_i64(&mut self, i: i64) {
        self.0 = i as u64;
    }

    pub fn write_f32(&mut self, z: f32) {
        self.0 = z.to_bits() as u64;
    }

    pub fn write_f64(&mut self, z: f64) {
        self.0 = z.to_bits();
    }

    pub fn read_32(&self) -> u32 {
        self.0 as u32
    }

    pub fn read_64(&self) -> u64 {
        self.0
    }

    pub fn read_i32(&self) -> i32 {
        self.0 as i32
    }

    pub fn read_i64(&self) -> i64 {
        self.0 as i64
    }

    pub fn read_f32(&self) -> f32 {
        f32::from_bits(self.0 as u32)
    }

    pub fn read_f64(&self) -> f64 {
        f64::from_bits(self.0)
    }

    pub fn to_value(self, ty: ValType) -> Value {
        match ty {
            ValType::I32 => Value::I32((self.0 as u32) as i32),
            ValType::I64 => Value::I64(self.0 as i64),
            ValType::F32 => Value::F32(f32::from_bits(self.0 as u32)),
            ValType::F64 => Value::F64(f64::from_bits(self.0)),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResultType(pub Option<ValType>);

impl ResultType {
    pub(crate) fn read(wasm: &mut Reader) -> Result<Self, ValidationError> {
        // The only result types occurring in the binary format are the types of blocks.
        // These are encoded in special compressed form, by either the byte 0x40 indicating
        // the empty type or as a single value type.
        match wasm.read_u8()? {
            0x40 => Ok(ResultType(None)),
            c => ValType::convert(c).map(|v| ResultType(Some(v))),
        }
    }
}

#[derive(Clone, PartialEq, Eq, Debug)]
pub struct FuncType {
    pub params: Vec<ValType>,
    pub returns: Vec<ValType>,
}

impl FuncType {
    pub(crate) fn read(wasm: &mut Reader) -> Result<Self, ValidationError> {
        // Function types are encoded by the byte 0x60 followed by the respective
        // vectors of parameter and result types.
        match wasm.read_u8()? {
            0x60 => {
                let params = wasm.read_vec(ValType::read)?;
                let returns = wasm.read_vec(ValType::read)?;

                if returns.len() > 1 {
                    // Wasm 1.0 does not support multiple returns
                    Err(ValidationError::FunctionReturnsTooLarge)
                } else {
                    Ok(FuncType { params, returns })
                }
            }
            c => Err(ValidationError::MalformedFunction(c)),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limit {
    pub min: u32,
    pub max: Option<u32>,
}

impl Limit {
    pub(crate) fn read(wasm: &mut Reader) -> Result<Self, ValidationError> {
        // Limits are encoded with a preceding flag indicating whether a maximum is present.
        match wasm.read_u8()? {
            0x00 => Ok(Limit {
                min: wasm.read_u32()?,
                max: None,
            }),
            0x01 => {
                let min = wasm.read_u32()?;

                // Note: We are disabling `max` memory size since we don't support memory.grow
                let max = wasm.read_u32()?;
                if max < min {
                    return Err(ValidationError::InvalidMaxLimit);
                }

                Ok(Limit {
                    min,
                    max: Some(max),
                })
            }
            c => Err(ValidationError::MalformedLimit(c)),
        }
    }

    pub fn matches(&self, other: &Limit) -> bool {
        if self.min < other.min {
            return false;
        }

        match (self.max, other.max) {
            (_, None) => true,
            (Some(m1), Some(m2)) => m1 <= m2,
            _ => false,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MemPageSize {
    _1,
    _65536,
}

impl MemPageSize {
    pub fn size(&self) -> usize {
        match self {
            MemPageSize::_1 => 1,
            MemPageSize::_65536 => 65536,
        }
    }

    pub fn alignment(&self) -> usize {
        match self {
            MemPageSize::_1 => 1,
            MemPageSize::_65536 => 16,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemType {
    pub initial_pages: u32,
    pub max_pages: Option<u32>,
    pub page_size: MemPageSize,
}

impl MemType {
    pub(crate) fn read(wasm: &mut Reader) -> Result<MemType, ValidationError> {
        let flag = wasm.read_u8()?;

        let min = wasm.read_u32()?;

        // Bit 0: Whether a maximum bound (m) for the limit follows.
        let max = if (flag & (1 << 0)) != 0 {
            let max = wasm.read_u32()?;
            if max < min {
                return Err(ValidationError::InvalidMaxLimit);
            }

            Some(max)
        } else {
            None
        };

        // Bit 1: Whether the memory is shared or unshared. This was introduced in the threads proposal.
        // Not supported
        if (flag & (1 << 1)) != 0 {
            return Err(ValidationError::MalformedMemType(flag));
        }

        // Bit 2: Whether the memory's index type is i32 or i64. This was introduced in the memory64 proposal.
        // Not supported
        if (flag & (1 << 2)) != 0 {
            return Err(ValidationError::MalformedMemType(flag));
        }

        // Bit 3: Whether the memory defines a custom page size (p) or not and therefore whether another u32 follows after the limits.
        // This was introduced in the custom-page-sizes proposal
        let page_size = if (flag & (1 << 3)) != 0 {
            let p = wasm.read_u32()?;
            match p {
                0 => MemPageSize::_1,
                16 => MemPageSize::_65536,
                p if p <= 64 => return Err(ValidationError::InvalidPageSize(p as u8)),
                _ => return Err(ValidationError::InvalidPageSize(0xFF)),
            }
        } else {
            MemPageSize::_65536
        };

        // Mask the rest of the flag bits to validate they are not set
        if (flag & 0xF0) != 0 {
            return Err(ValidationError::MalformedMemType(flag));
        }

        // The limits must be valid within the range 2**32 - 1.
        // The limits must be valid within the range 2**32 / pagesize

        let max_allowed_pages = match page_size {
            MemPageSize::_1 => (u32::MAX as u64) + 1,
            MemPageSize::_65536 => 65536,
        };

        if min as u64 > max_allowed_pages {
            return Err(ValidationError::MemoryTooLarge);
        } else if let Some(max) = max {
            if max as u64 > max_allowed_pages {
                return Err(ValidationError::MemoryTooLarge);
            }
        }

        Ok(MemType {
            initial_pages: min,
            max_pages: max,
            page_size,
        })
    }

    pub fn zero() -> MemType {
        MemType {
            initial_pages: 0,
            max_pages: Some(0),
            page_size: MemPageSize::_65536,
        }
    }

    pub fn min(&self) -> u32 {
        self.initial_pages
    }

    pub fn can_hold(&self, n_pages: u32) -> bool {
        if let Some(max) = self.max_pages {
            if n_pages > max {
                return false;
            }
        } else {
            // Wasm only has 4 GiB per memory
            let n_bytes = (n_pages as u64) * (self.page_size() as u64);
            if n_bytes > (1 << 32) {
                return false;
            }
        }

        self.initial_pages <= n_pages
    }

    pub fn page_size(&self) -> usize {
        self.page_size.size()
    }

    pub fn page_alignment(&self) -> usize {
        self.page_size.alignment()
    }

    pub fn matches(&self, other: &MemType) -> bool {
        Limit {
            min: self.initial_pages,
            max: self.max_pages,
        }
        .matches(&Limit {
            min: other.initial_pages,
            max: other.max_pages,
        }) && self.page_size == other.page_size
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ElemType {
    FuncRef,
}

impl ElemType {
    pub(crate) fn read(wasm: &mut Reader) -> Result<Self, ValidationError> {
        match wasm.read_u8()? {
            0x70 => Ok(ElemType::FuncRef),
            c => Err(ValidationError::MalformedElemType(c)),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct TableType {
    pub elem_type: ElemType,
    pub limits: Limit,
}

impl TableType {
    pub(crate) fn read(wasm: &mut Reader) -> Result<Self, ValidationError> {
        // Table types are encoded with their limits and a constant byte indicating their element type.
        Ok(TableType {
            elem_type: ElemType::read(wasm)?,
            limits: Limit::read(wasm)?,
        })
    }
}

#[derive(Debug, Clone, Copy)]
pub struct GlobalType {
    pub ty: ValType,
    pub mutable: bool,
}

impl GlobalType {
    pub(crate) fn read(wasm: &mut Reader) -> Result<Self, ValidationError> {
        let ty = ValType::read(wasm)?;
        let mutable = match wasm.read_u8()? {
            0x00 => false, // const
            0x01 => true,  // mutable
            c => return Err(ValidationError::ExpectedConstOrVar(c)),
        };

        Ok(GlobalType { ty, mutable })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn raw_value_roundtrip_word() {
        // The 32-bit accessors only touch the low word; the high bits stay clear.
        let mut v = RawValue::from_32(0xDEAD_BEEF);
        assert_eq!(v.read_32(), 0xDEAD_BEEF);
        assert_eq!(v.read_i32(), 0xDEAD_BEEFu32 as i32);

        v.write_32(1);
        assert_eq!(v.read_32(), 1);

        v.write_i32(-1);
        assert_eq!(v.read_i32(), -1);
        assert_eq!(v.read_32(), u32::MAX);
    }

    #[test]
    fn raw_value_roundtrip_dword() {
        let mut v = RawValue::from_64(0x0123_4567_89AB_CDEF);
        assert_eq!(v.read_64(), 0x0123_4567_89AB_CDEF);
        assert_eq!(v.read_i64(), 0x0123_4567_89AB_CDEF);

        v.write_64(u64::MAX);
        assert_eq!(v.read_64(), u64::MAX);
        assert_eq!(v.read_i64(), -1);

        v.write_i64(-2);
        assert_eq!(v.read_i64(), -2);
    }

    #[test]
    fn raw_value_roundtrip_float() {
        let mut v = RawValue::from_f32(3.5);
        assert_eq!(v.read_f32(), 3.5);
        v.write_f32(-1.25);
        assert_eq!(v.read_f32(), -1.25);

        let mut v = RawValue::from_f64(3.5);
        assert_eq!(v.read_f64(), 3.5);
        v.write_f64(-1.25);
        assert_eq!(v.read_f64(), -1.25);
    }

    #[test]
    fn raw_value_from_signed_constructors() {
        assert_eq!(RawValue::from_i32(-1).read_32(), u32::MAX);
        assert_eq!(RawValue::from_i64(-1).read_64(), u64::MAX);
    }

    #[test]
    fn raw_value_to_value_by_type() {
        assert_eq!(
            RawValue::from_i32(-7).to_value(ValType::I32),
            Value::I32(-7)
        );
        assert_eq!(
            RawValue::from_i64(-7).to_value(ValType::I64),
            Value::I64(-7)
        );
        assert_eq!(
            RawValue::from_f32(2.0).to_value(ValType::F32),
            Value::F32(2.0)
        );
        assert_eq!(
            RawValue::from_f64(2.0).to_value(ValType::F64),
            Value::F64(2.0)
        );
    }

    #[test]
    fn limit_matches_rules() {
        // `a.matches(b)` asks whether limit `a` satisfies requirement `b`; it
        // requires `a.min >= b.min`. A smaller minimum fails immediately.
        assert!(!Limit { min: 1, max: None }.matches(&Limit { min: 2, max: None }));

        // A larger-or-equal minimum with no requirement maximum always matches.
        assert!(Limit { min: 2, max: None }.matches(&Limit { min: 1, max: None }));
        assert!(
            Limit {
                min: 1,
                max: Some(5)
            }
            .matches(&Limit { min: 1, max: None })
        );

        // Both bounded: the candidate max must fit within the requirement max.
        assert!(
            Limit {
                min: 1,
                max: Some(3)
            }
            .matches(&Limit {
                min: 1,
                max: Some(4)
            })
        );
        assert!(
            !Limit {
                min: 1,
                max: Some(5)
            }
            .matches(&Limit {
                min: 1,
                max: Some(4)
            })
        );

        // A bounded requirement rejects an unbounded candidate.
        assert!(!Limit { min: 1, max: None }.matches(&Limit {
            min: 1,
            max: Some(4)
        }));
    }
}