baedeker-core 0.1.0

WebAssembly runtime core — decode, validate, execute (no_std)
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
// Copyright (C) 2026 Industrial Algebra
// SPDX-License-Identifier: Apache-2.0

//! LEB128 (Little Endian Base 128) encoder/decoder.
//!
//! WASM uses LEB128 extensively for compact integer encoding in the binary format.
//! See [Spec §5.2.2](https://webassembly.github.io/spec/core/binary/values.html#integers).

use crate::error::{ByteOffset, DecodeContext, DecodeError, DecodeErrorKind};

/// A cursor over a byte slice, tracking the current read position.
#[derive(Debug)]
pub struct Cursor<'a> {
    data: &'a [u8],
    pos: usize,
}

impl<'a> Cursor<'a> {
    /// Create a new cursor at position 0.
    pub fn new(data: &'a [u8]) -> Self {
        Self { data, pos: 0 }
    }

    /// Current byte offset.
    pub fn position(&self) -> usize {
        self.pos
    }

    /// Remaining bytes.
    pub fn remaining(&self) -> &'a [u8] {
        &self.data[self.pos..]
    }

    /// Pre-allocation capacity for `count` entries yet to be parsed.
    ///
    /// Malformed binaries can declare counts in the billions; blindly
    /// trusting them in `Vec::with_capacity` turns a tiny input into a
    /// multi-gigabyte allocation. Every entry needs at least one byte in
    /// the stream, so the remaining input length is a sound upper bound.
    pub fn capacity_hint(&self, count: u32) -> usize {
        (count as usize).min(self.remaining().len())
    }

    /// Original backing slice.
    pub fn original(&self) -> &'a [u8] {
        self.data
    }

    /// Whether we've consumed all input.
    pub fn is_empty(&self) -> bool {
        self.pos >= self.data.len()
    }

    /// Read a single byte, advancing the cursor.
    pub fn read_byte(&mut self) -> Result<u8, DecodeError> {
        if self.pos < self.data.len() {
            let b = self.data[self.pos];
            self.pos += 1;
            Ok(b)
        } else {
            Err(DecodeError {
                offset: ByteOffset(self.pos),
                context: DecodeContext::Leb128,
                kind: DecodeErrorKind::UnexpectedEof,
            })
        }
    }

    /// Read exactly `n` bytes as a slice, advancing the cursor.
    pub fn read_bytes(&mut self, n: usize) -> Result<&'a [u8], DecodeError> {
        if self.pos + n <= self.data.len() {
            let slice = &self.data[self.pos..self.pos + n];
            self.pos += n;
            Ok(slice)
        } else {
            Err(DecodeError {
                offset: ByteOffset(self.pos),
                context: DecodeContext::Leb128,
                kind: DecodeErrorKind::UnexpectedEof,
            })
        }
    }

    /// Advance the cursor by `n` bytes.
    pub fn advance(&mut self, n: usize) -> Result<(), DecodeError> {
        if self.pos + n <= self.data.len() {
            self.pos += n;
            Ok(())
        } else {
            Err(DecodeError {
                offset: ByteOffset(self.pos),
                context: DecodeContext::Leb128,
                kind: DecodeErrorKind::UnexpectedEof,
            })
        }
    }
}

/// Decode an unsigned LEB128-encoded u32.
///
/// The encoding uses at most 5 bytes. The final byte's unused high bits
/// must be zero (no overlong encodings).
/// See [Spec §5.2.2](https://webassembly.github.io/spec/core/binary/values.html#integers).
pub fn decode_u32(cursor: &mut Cursor<'_>) -> Result<u32, DecodeError> {
    let start = cursor.position();
    let mut result: u32 = 0;
    let mut shift: u32 = 0;

    for i in 0..5 {
        let byte = cursor.read_byte().map_err(|mut e| {
            e.context = DecodeContext::Leb128;
            e.offset = ByteOffset(start);
            e
        })?;

        let low_bits = u32::from(byte & 0x7F);

        // Check for overflow on the 5th byte (shift=28): only 4 low bits are valid.
        if i == 4 && (byte & 0xF0) != 0 {
            return Err(DecodeError {
                offset: ByteOffset(start),
                context: DecodeContext::Leb128,
                kind: DecodeErrorKind::Leb128Overflow,
            });
        }

        result |= low_bits << shift;

        if byte & 0x80 == 0 {
            return Ok(result);
        }

        shift += 7;
    }

    Err(DecodeError {
        offset: ByteOffset(start),
        context: DecodeContext::Leb128,
        kind: DecodeErrorKind::Leb128TooLong,
    })
}

/// Decode an unsigned LEB128-encoded u64.
///
/// The encoding uses at most 10 bytes.
pub fn decode_u64(cursor: &mut Cursor<'_>) -> Result<u64, DecodeError> {
    let start = cursor.position();
    let mut result: u64 = 0;
    let mut shift: u32 = 0;

    for i in 0..10 {
        let byte = cursor.read_byte().map_err(|mut e| {
            e.context = DecodeContext::Leb128;
            e.offset = ByteOffset(start);
            e
        })?;

        let low_bits = u64::from(byte & 0x7F);

        // 10th byte (shift=63): only 1 low bit is valid.
        if i == 9 && (byte & 0xFE) != 0 {
            return Err(DecodeError {
                offset: ByteOffset(start),
                context: DecodeContext::Leb128,
                kind: DecodeErrorKind::Leb128Overflow,
            });
        }

        result |= low_bits << shift;

        if byte & 0x80 == 0 {
            return Ok(result);
        }

        shift += 7;
    }

    Err(DecodeError {
        offset: ByteOffset(start),
        context: DecodeContext::Leb128,
        kind: DecodeErrorKind::Leb128TooLong,
    })
}

/// Decode a signed LEB128-encoded i32.
///
/// The encoding uses at most 5 bytes. Sign extension is applied based on
/// the sign bit of the final byte.
pub fn decode_i32(cursor: &mut Cursor<'_>) -> Result<i32, DecodeError> {
    let start = cursor.position();
    let mut result: i32 = 0;
    let mut shift: u32 = 0;

    for i in 0..5 {
        let byte = cursor.read_byte().map_err(|mut e| {
            e.context = DecodeContext::Leb128;
            e.offset = ByteOffset(start);
            e
        })?;

        let low_bits = i32::from(byte & 0x7F);
        result |= low_bits << shift;
        shift += 7;

        if byte & 0x80 == 0 {
            // On the final byte, check that the unused high bits are consistent
            // with the sign bit (either all 0s or all 1s).
            if i == 4 {
                // 5th byte at shift=28: bits 0-3 carry data (bit 3 = the
                // i32 sign bit); bits 4-6 must sign-extend bit 3 exactly.
                let sign = byte & 0x08;
                let extension = byte & 0x70;
                if (sign == 0 && extension != 0) || (sign != 0 && extension != 0x70) {
                    return Err(DecodeError {
                        offset: ByteOffset(start),
                        context: DecodeContext::Leb128,
                        kind: DecodeErrorKind::Leb128Overflow,
                    });
                }
            } else if shift < 32 && (byte & 0x40) != 0 {
                // Sign-extend negative values.
                result |= !0 << shift;
            }
            return Ok(result);
        }
    }

    Err(DecodeError {
        offset: ByteOffset(start),
        context: DecodeContext::Leb128,
        kind: DecodeErrorKind::Leb128TooLong,
    })
}

/// Decode a signed LEB128-encoded i64.
///
/// The encoding uses at most 10 bytes.
pub fn decode_i64(cursor: &mut Cursor<'_>) -> Result<i64, DecodeError> {
    let start = cursor.position();
    let mut result: i64 = 0;
    let mut shift: u32 = 0;

    for i in 0..10 {
        let byte = cursor.read_byte().map_err(|mut e| {
            e.context = DecodeContext::Leb128;
            e.offset = ByteOffset(start);
            e
        })?;

        let low_bits = i64::from(byte & 0x7F);
        result |= low_bits << shift;
        shift += 7;

        if byte & 0x80 == 0 {
            if i == 9 {
                // 10th byte at shift=63: bit 0 carries data (the i64 sign
                // bit); bits 1-6 must sign-extend bit 0 exactly.
                let sign = byte & 0x01;
                let extension = byte & 0x7E;
                if (sign == 0 && extension != 0) || (sign != 0 && extension != 0x7E) {
                    return Err(DecodeError {
                        offset: ByteOffset(start),
                        context: DecodeContext::Leb128,
                        kind: DecodeErrorKind::Leb128Overflow,
                    });
                }
            } else if shift < 64 && (byte & 0x40) != 0 {
                result |= !0i64 << shift;
            }
            return Ok(result);
        }
    }

    Err(DecodeError {
        offset: ByteOffset(start),
        context: DecodeContext::Leb128,
        kind: DecodeErrorKind::Leb128TooLong,
    })
}

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

    // ── decode_u32 ──────────────────────────────────────────

    #[test]
    fn u32_zero() {
        let mut c = Cursor::new(&[0x00]);
        assert_eq!(decode_u32(&mut c).unwrap(), 0);
    }

    #[test]
    fn u32_single_byte() {
        let mut c = Cursor::new(&[0x08]);
        assert_eq!(decode_u32(&mut c).unwrap(), 8);
    }

    #[test]
    fn u32_max_single_byte() {
        // 127 = 0x7F
        let mut c = Cursor::new(&[0x7F]);
        assert_eq!(decode_u32(&mut c).unwrap(), 127);
    }

    #[test]
    fn u32_two_bytes() {
        // 128 = 0x80 0x01
        let mut c = Cursor::new(&[0x80, 0x01]);
        assert_eq!(decode_u32(&mut c).unwrap(), 128);
    }

    #[test]
    fn u32_624485() {
        // Classic LEB128 test value: 624485 = 0xE5 0x8E 0x26
        let mut c = Cursor::new(&[0xE5, 0x8E, 0x26]);
        assert_eq!(decode_u32(&mut c).unwrap(), 624485);
    }

    #[test]
    fn u32_max_value() {
        // u32::MAX = 4294967295 = 0xFF 0xFF 0xFF 0xFF 0x0F
        let mut c = Cursor::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0x0F]);
        assert_eq!(decode_u32(&mut c).unwrap(), u32::MAX);
    }

    #[test]
    fn u32_overflow_fifth_byte() {
        // 5th byte has bit 4 set → overflow
        let mut c = Cursor::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0x1F]);
        let err = decode_u32(&mut c).unwrap_err();
        assert_eq!(err.kind, DecodeErrorKind::Leb128Overflow);
    }

    #[test]
    fn u32_too_long() {
        // 6 continuation bytes
        let mut c = Cursor::new(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x00]);
        let err = decode_u32(&mut c).unwrap_err();
        assert_eq!(err.kind, DecodeErrorKind::Leb128Overflow);
    }

    #[test]
    fn u32_unexpected_eof() {
        let mut c = Cursor::new(&[0x80]);
        let err = decode_u32(&mut c).unwrap_err();
        assert_eq!(err.kind, DecodeErrorKind::UnexpectedEof);
    }

    // ── decode_i32 ──────────────────────────────────────────

    #[test]
    fn i32_zero() {
        let mut c = Cursor::new(&[0x00]);
        assert_eq!(decode_i32(&mut c).unwrap(), 0);
    }

    #[test]
    fn i32_positive() {
        let mut c = Cursor::new(&[0x08]);
        assert_eq!(decode_i32(&mut c).unwrap(), 8);
    }

    #[test]
    fn i32_negative_one() {
        // -1 = 0x7F (sign bit set, single byte)
        let mut c = Cursor::new(&[0x7F]);
        assert_eq!(decode_i32(&mut c).unwrap(), -1);
    }

    #[test]
    fn i32_negative_two() {
        // -2 = 0x7E
        let mut c = Cursor::new(&[0x7E]);
        assert_eq!(decode_i32(&mut c).unwrap(), -2);
    }

    #[test]
    fn i32_negative_128() {
        // -128 = 0x80 0x7F
        let mut c = Cursor::new(&[0x80, 0x7F]);
        assert_eq!(decode_i32(&mut c).unwrap(), -128);
    }

    #[test]
    fn i32_min_value() {
        // i32::MIN = -2147483648 = 0x80 0x80 0x80 0x80 0x78
        let mut c = Cursor::new(&[0x80, 0x80, 0x80, 0x80, 0x78]);
        assert_eq!(decode_i32(&mut c).unwrap(), i32::MIN);
    }

    #[test]
    fn i32_max_value() {
        // i32::MAX = 2147483647 = 0xFF 0xFF 0xFF 0xFF 0x07
        let mut c = Cursor::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0x07]);
        assert_eq!(decode_i32(&mut c).unwrap(), i32::MAX);
    }

    // ── decode_u64 ──────────────────────────────────────────

    #[test]
    fn u64_zero() {
        let mut c = Cursor::new(&[0x00]);
        assert_eq!(decode_u64(&mut c).unwrap(), 0);
    }

    #[test]
    fn u64_max_value() {
        // u64::MAX = 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF 0x01
        let mut c = Cursor::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x01]);
        assert_eq!(decode_u64(&mut c).unwrap(), u64::MAX);
    }

    #[test]
    fn u64_overflow() {
        // 10th byte has extra bits set
        let mut c = Cursor::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x03]);
        let err = decode_u64(&mut c).unwrap_err();
        assert_eq!(err.kind, DecodeErrorKind::Leb128Overflow);
    }

    // ── decode_i64 ──────────────────────────────────────────

    #[test]
    fn i64_negative_one() {
        let mut c = Cursor::new(&[0x7F]);
        assert_eq!(decode_i64(&mut c).unwrap(), -1i64);
    }

    #[test]
    fn i64_min_value() {
        // i64::MIN encoded as signed LEB128
        let mut c = Cursor::new(&[0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x7F]);
        assert_eq!(decode_i64(&mut c).unwrap(), i64::MIN);
    }

    #[test]
    fn i64_max_value() {
        // i64::MAX encoded as signed LEB128
        let mut c = Cursor::new(&[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x00]);
        assert_eq!(decode_i64(&mut c).unwrap(), i64::MAX);
    }

    // ── cursor ──────────────────────────────────────────────

    #[test]
    fn cursor_tracks_position() {
        let mut c = Cursor::new(&[0x01, 0x02, 0x03]);
        assert_eq!(c.position(), 0);
        c.read_byte().unwrap();
        assert_eq!(c.position(), 1);
        c.read_bytes(2).unwrap();
        assert_eq!(c.position(), 3);
        assert!(c.is_empty());
    }
}