Skip to main content

atmos/os_lib/wasm/
decode.rs

1//! WebAssembly のバイナリ形式(MVP + 多値の結果・符号拡張・飽和変換・一括メモリ操作の一部)を読む。
2//!
3//! 関数の本体は生のバイト列のまま持ち、実行時に解釈する(`exec.rs`)。
4//! 読み込みの時点で、命令の即値の長さと入れ子(block/loop/if と end/else の対応)を確かめ、
5//! 各構造の `else`/`end` の位置を表にしておく(分岐の飛び先を探し直さないため)。
6
7extern crate alloc;
8
9use alloc::collections::BTreeMap;
10use alloc::string::String;
11use alloc::vec::Vec;
12
13/// 値の型。
14#[derive(Clone, Copy, Debug, PartialEq, Eq)]
15pub enum ValType {
16    I32,
17    I64,
18    F32,
19    F64,
20    FuncRef,
21    ExternRef,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct FuncType {
26    pub params: Vec<ValType>,
27    pub results: Vec<ValType>,
28}
29
30#[derive(Clone, Copy, Debug, PartialEq, Eq)]
31pub struct Limits {
32    pub min: u32,
33    pub max: Option<u32>,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct TableType {
38    pub elem: ValType,
39    pub limits: Limits,
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub struct GlobalType {
44    pub ty: ValType,
45    pub mutable: bool,
46}
47
48/// 定数式(グローバルの初期値・要素とデータの開始位置)。
49#[derive(Clone, Copy, Debug, PartialEq)]
50pub enum ConstExpr {
51    I32(i32),
52    I64(i64),
53    F32(u32),
54    F64(u64),
55    GlobalGet(u32),
56    RefNull,
57    RefFunc(u32),
58}
59
60#[derive(Clone, Debug, PartialEq)]
61pub enum ImportDesc {
62    Func(u32),
63    Table(TableType),
64    Memory(Limits),
65    Global(GlobalType),
66}
67
68#[derive(Clone, Debug, PartialEq)]
69pub struct Import {
70    pub module: String,
71    pub name: String,
72    pub desc: ImportDesc,
73}
74
75#[derive(Clone, Copy, Debug, PartialEq, Eq)]
76pub enum ExportDesc {
77    Func(u32),
78    Table(u32),
79    Memory(u32),
80    Global(u32),
81}
82
83#[derive(Clone, Debug, PartialEq)]
84pub struct Export {
85    pub name: String,
86    pub desc: ExportDesc,
87}
88
89/// 定義された関数(取り込みは含まない)。
90#[derive(Clone, Debug)]
91pub struct Func {
92    pub type_idx: u32,
93    /// 引数の後ろに並ぶ局所変数の型。
94    pub locals: Vec<ValType>,
95    /// 本体の命令列(局所変数の宣言の後ろから、最後の `end` まで)。
96    pub code: Vec<u8>,
97    /// block/loop/if の開始位置 → (else の位置, end の位置)。
98    pub blocks: BTreeMap<usize, (Option<usize>, usize)>,
99}
100
101#[derive(Clone, Debug, PartialEq)]
102pub struct Global {
103    pub ty: GlobalType,
104    pub init: ConstExpr,
105}
106
107/// 要素の区画(能動的なものだけ表へ書く。受動的・宣言的なものは持つだけ)。
108#[derive(Clone, Debug, PartialEq)]
109pub struct Elem {
110    pub table: u32,
111    pub offset: Option<ConstExpr>,
112    pub funcs: Vec<Option<u32>>,
113}
114
115#[derive(Clone, Debug, PartialEq)]
116pub struct Data {
117    pub memory: u32,
118    pub offset: Option<ConstExpr>,
119    pub bytes: Vec<u8>,
120}
121
122#[derive(Clone, Debug, Default)]
123pub struct Module {
124    pub types: Vec<FuncType>,
125    pub imports: Vec<Import>,
126    pub funcs: Vec<Func>,
127    pub tables: Vec<TableType>,
128    pub memories: Vec<Limits>,
129    pub globals: Vec<Global>,
130    pub exports: Vec<Export>,
131    pub start: Option<u32>,
132    pub elems: Vec<Elem>,
133    pub datas: Vec<Data>,
134}
135
136impl Module {
137    /// 取り込みの関数の数。関数の番号は取り込みが先に並ぶ。
138    pub fn imported_funcs(&self) -> usize {
139        self.imports.iter().filter(|i| matches!(i.desc, ImportDesc::Func(_))).count()
140    }
141    pub fn imported_globals(&self) -> usize {
142        self.imports.iter().filter(|i| matches!(i.desc, ImportDesc::Global(_))).count()
143    }
144    pub fn imported_tables(&self) -> usize {
145        self.imports.iter().filter(|i| matches!(i.desc, ImportDesc::Table(_))).count()
146    }
147    pub fn imported_memories(&self) -> usize {
148        self.imports.iter().filter(|i| matches!(i.desc, ImportDesc::Memory(_))).count()
149    }
150    /// 関数の番号 `idx`(取り込みを含む)の型。
151    pub fn func_type(&self, idx: u32) -> Option<&FuncType> {
152        let n = self.imported_funcs();
153        let ti = if (idx as usize) < n {
154            self.imports
155                .iter()
156                .filter_map(|i| match i.desc {
157                    ImportDesc::Func(t) => Some(t),
158                    _ => None,
159                })
160                .nth(idx as usize)?
161        } else {
162            self.funcs.get(idx as usize - n)?.type_idx
163        };
164        self.types.get(ti as usize)
165    }
166}
167
168/// 読み込みの失敗(`WebAssembly.CompileError` の文言になる)。
169#[derive(Clone, Debug, PartialEq, Eq)]
170pub struct DecodeError(pub String);
171
172type R<T> = Result<T, DecodeError>;
173
174fn err<T>(msg: &str) -> R<T> {
175    Err(DecodeError(String::from(msg)))
176}
177
178struct Reader<'a> {
179    b: &'a [u8],
180    pos: usize,
181}
182
183impl<'a> Reader<'a> {
184    fn new(b: &'a [u8]) -> Self {
185        Reader { b, pos: 0 }
186    }
187    fn eof(&self) -> bool {
188        self.pos >= self.b.len()
189    }
190    fn byte(&mut self) -> R<u8> {
191        let v = *self.b.get(self.pos).ok_or_else(|| DecodeError(String::from("unexpected end")))?;
192        self.pos += 1;
193        Ok(v)
194    }
195    fn bytes(&mut self, n: usize) -> R<&'a [u8]> {
196        let end = self.pos.checked_add(n).ok_or_else(|| DecodeError(String::from("length overflow")))?;
197        let s = self.b.get(self.pos..end).ok_or_else(|| DecodeError(String::from("unexpected end")))?;
198        self.pos = end;
199        Ok(s)
200    }
201    fn u32(&mut self) -> R<u32> {
202        let v = self.uleb(32)?;
203        Ok(v as u32)
204    }
205    fn uleb(&mut self, bits: u32) -> R<u64> {
206        let mut result: u64 = 0;
207        let mut shift = 0u32;
208        loop {
209            let b = self.byte()?;
210            if shift >= bits && (b & 0x7f) != 0 {
211                return err("integer too large");
212            }
213            if shift < 64 {
214                result |= ((b & 0x7f) as u64) << shift;
215            }
216            shift += 7;
217            if b & 0x80 == 0 {
218                break;
219            }
220            if shift > bits + 6 {
221                return err("integer representation too long");
222            }
223        }
224        if bits < 64 && result >> bits != 0 {
225            return err("integer too large");
226        }
227        Ok(result)
228    }
229    fn sleb(&mut self, bits: u32) -> R<i64> {
230        let mut result: i64 = 0;
231        let mut shift = 0u32;
232        let mut b;
233        loop {
234            b = self.byte()?;
235            if shift < 64 {
236                result |= ((b & 0x7f) as i64) << shift;
237            }
238            shift += 7;
239            if b & 0x80 == 0 {
240                break;
241            }
242            if shift > bits + 6 {
243                return err("integer representation too long");
244            }
245        }
246        if shift < 64 && (b & 0x40) != 0 {
247            result |= -1i64 << shift;
248        }
249        if bits < 64 {
250            let min = -(1i64 << (bits - 1));
251            let max = (1i64 << (bits - 1)) - 1;
252            if result < min || result > max {
253                return err("integer too large");
254            }
255        }
256        Ok(result)
257    }
258    fn name(&mut self) -> R<String> {
259        let n = self.u32()? as usize;
260        let s = self.bytes(n)?;
261        core::str::from_utf8(s).map(String::from).map_err(|_| DecodeError(String::from("malformed UTF-8 encoding")))
262    }
263    fn valtype(&mut self) -> R<ValType> {
264        match self.byte()? {
265            0x7f => Ok(ValType::I32),
266            0x7e => Ok(ValType::I64),
267            0x7d => Ok(ValType::F32),
268            0x7c => Ok(ValType::F64),
269            0x70 => Ok(ValType::FuncRef),
270            0x6f => Ok(ValType::ExternRef),
271            _ => err("invalid value type"),
272        }
273    }
274    fn limits(&mut self) -> R<Limits> {
275        match self.byte()? {
276            0x00 => Ok(Limits { min: self.u32()?, max: None }),
277            0x01 => {
278                let min = self.u32()?;
279                let max = self.u32()?;
280                if max < min {
281                    return err("size minimum must not be greater than maximum");
282                }
283                Ok(Limits { min, max: Some(max) })
284            }
285            _ => err("integer too large"),
286        }
287    }
288    fn table_type(&mut self) -> R<TableType> {
289        let elem = self.valtype()?;
290        if !matches!(elem, ValType::FuncRef | ValType::ExternRef) {
291            return err("malformed reference type");
292        }
293        Ok(TableType { elem, limits: self.limits()? })
294    }
295    fn global_type(&mut self) -> R<GlobalType> {
296        let ty = self.valtype()?;
297        let mutable = match self.byte()? {
298            0 => false,
299            1 => true,
300            _ => return err("malformed mutability"),
301        };
302        Ok(GlobalType { ty, mutable })
303    }
304    fn const_expr(&mut self) -> R<ConstExpr> {
305        let e = match self.byte()? {
306            0x41 => ConstExpr::I32(self.sleb(32)? as i32),
307            0x42 => ConstExpr::I64(self.sleb(64)?),
308            0x43 => {
309                let s = self.bytes(4)?;
310                ConstExpr::F32(u32::from_le_bytes([s[0], s[1], s[2], s[3]]))
311            }
312            0x44 => {
313                let s = self.bytes(8)?;
314                ConstExpr::F64(u64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]))
315            }
316            0x23 => ConstExpr::GlobalGet(self.u32()?),
317            0xd0 => {
318                self.byte()?;
319                ConstExpr::RefNull
320            }
321            0xd2 => ConstExpr::RefFunc(self.u32()?),
322            _ => return err("constant expression required"),
323        };
324        if self.byte()? != 0x0b {
325            return err("constant expression required");
326        }
327        Ok(e)
328    }
329}
330
331/// `bytes` を WebAssembly のモジュールとして読む。
332pub fn decode(bytes: &[u8]) -> R<Module> {
333    let mut r = Reader::new(bytes);
334    if r.bytes(4).ok() != Some(b"\0asm".as_slice()) {
335        return err("magic header not detected");
336    }
337    if r.bytes(4).ok() != Some([1u8, 0, 0, 0].as_slice()) {
338        return err("unknown binary version");
339    }
340    let mut m = Module::default();
341    let mut func_types: Vec<u32> = Vec::new();
342    let mut last_id = 0u8;
343    while !r.eof() {
344        let id = r.byte()?;
345        let size = r.u32()? as usize;
346        let body = r.bytes(size)?;
347        // 独自区画(0)以外は決まった順(12 = data count は 10 の前)。
348        if id != 0 {
349            let order = |x: u8| if x == 12 { 9 } else if x >= 10 { x + 1 } else { x };
350            if order(id) <= order(last_id) {
351                return err("unexpected section");
352            }
353            last_id = id;
354        }
355        let mut s = Reader::new(body);
356        match id {
357            0 => {}
358            1 => {
359                for _ in 0..s.u32()? {
360                    if s.byte()? != 0x60 {
361                        return err("integer representation too long");
362                    }
363                    let np = s.u32()?;
364                    let mut params = Vec::new();
365                    for _ in 0..np {
366                        params.push(s.valtype()?);
367                    }
368                    let nr = s.u32()?;
369                    let mut results = Vec::new();
370                    for _ in 0..nr {
371                        results.push(s.valtype()?);
372                    }
373                    m.types.push(FuncType { params, results });
374                }
375            }
376            2 => {
377                for _ in 0..s.u32()? {
378                    let module = s.name()?;
379                    let name = s.name()?;
380                    let desc = match s.byte()? {
381                        0 => ImportDesc::Func(s.u32()?),
382                        1 => ImportDesc::Table(s.table_type()?),
383                        2 => ImportDesc::Memory(s.limits()?),
384                        3 => ImportDesc::Global(s.global_type()?),
385                        _ => return err("malformed import kind"),
386                    };
387                    m.imports.push(Import { module, name, desc });
388                }
389            }
390            3 => {
391                for _ in 0..s.u32()? {
392                    func_types.push(s.u32()?);
393                }
394            }
395            4 => {
396                for _ in 0..s.u32()? {
397                    m.tables.push(s.table_type()?);
398                }
399            }
400            5 => {
401                for _ in 0..s.u32()? {
402                    m.memories.push(s.limits()?);
403                }
404            }
405            6 => {
406                for _ in 0..s.u32()? {
407                    let ty = s.global_type()?;
408                    let init = s.const_expr()?;
409                    m.globals.push(Global { ty, init });
410                }
411            }
412            7 => {
413                for _ in 0..s.u32()? {
414                    let name = s.name()?;
415                    let desc = match s.byte()? {
416                        0 => ExportDesc::Func(s.u32()?),
417                        1 => ExportDesc::Table(s.u32()?),
418                        2 => ExportDesc::Memory(s.u32()?),
419                        3 => ExportDesc::Global(s.u32()?),
420                        _ => return err("malformed export kind"),
421                    };
422                    if m.exports.iter().any(|e| e.name == name) {
423                        return err("duplicate export name");
424                    }
425                    m.exports.push(Export { name, desc });
426                }
427            }
428            8 => m.start = Some(s.u32()?),
429            9 => {
430                for _ in 0..s.u32()? {
431                    m.elems.push(decode_elem(&mut s)?);
432                }
433            }
434            10 => {
435                let n = s.u32()? as usize;
436                if n != func_types.len() {
437                    return err("function and code section have inconsistent lengths");
438                }
439                for &type_idx in func_types.iter() {
440                    let size = s.u32()? as usize;
441                    let fb = s.bytes(size)?;
442                    m.funcs.push(decode_func(type_idx, fb)?);
443                }
444            }
445            11 => {
446                for _ in 0..s.u32()? {
447                    let flag = s.u32()?;
448                    let (memory, offset) = match flag {
449                        0 => (0, Some(s.const_expr()?)),
450                        1 => (0, None),
451                        2 => (s.u32()?, Some(s.const_expr()?)),
452                        _ => return err("malformed data segment kind"),
453                    };
454                    let n = s.u32()? as usize;
455                    let bytes = s.bytes(n)?.to_vec();
456                    m.datas.push(Data { memory, offset, bytes });
457                }
458            }
459            12 => {
460                s.u32()?;
461            }
462            _ => return err("malformed section id"),
463        }
464        if id != 0 && !s.eof() {
465            return err("section size mismatch");
466        }
467    }
468    if !func_types.is_empty() && m.funcs.is_empty() {
469        return err("function and code section have inconsistent lengths");
470    }
471    validate_indices(&m)?;
472    Ok(m)
473}
474
475fn decode_elem(s: &mut Reader) -> R<Elem> {
476    let flag = s.u32()?;
477    let read_funcs = |s: &mut Reader| -> R<Vec<Option<u32>>> {
478        let n = s.u32()?;
479        let mut v = Vec::new();
480        for _ in 0..n {
481            v.push(Some(s.u32()?));
482        }
483        Ok(v)
484    };
485    let read_exprs = |s: &mut Reader| -> R<Vec<Option<u32>>> {
486        let n = s.u32()?;
487        let mut v = Vec::new();
488        for _ in 0..n {
489            v.push(match s.const_expr()? {
490                ConstExpr::RefFunc(f) => Some(f),
491                _ => None,
492            });
493        }
494        Ok(v)
495    };
496    Ok(match flag {
497        0 => {
498            let offset = s.const_expr()?;
499            Elem { table: 0, offset: Some(offset), funcs: read_funcs(s)? }
500        }
501        1 => {
502            s.byte()?;
503            Elem { table: 0, offset: None, funcs: read_funcs(s)? }
504        }
505        2 => {
506            let table = s.u32()?;
507            let offset = s.const_expr()?;
508            s.byte()?;
509            Elem { table, offset: Some(offset), funcs: read_funcs(s)? }
510        }
511        3 => {
512            s.byte()?;
513            Elem { table: 0, offset: None, funcs: read_funcs(s)? }
514        }
515        4 => {
516            let offset = s.const_expr()?;
517            Elem { table: 0, offset: Some(offset), funcs: read_exprs(s)? }
518        }
519        5 | 7 => {
520            s.valtype()?;
521            Elem { table: 0, offset: None, funcs: read_exprs(s)? }
522        }
523        6 => {
524            let table = s.u32()?;
525            let offset = s.const_expr()?;
526            s.valtype()?;
527            Elem { table, offset: Some(offset), funcs: read_exprs(s)? }
528        }
529        _ => return err("malformed elements segment kind"),
530    })
531}
532
533fn decode_func(type_idx: u32, body: &[u8]) -> R<Func> {
534    let mut r = Reader::new(body);
535    let mut locals = Vec::new();
536    let groups = r.u32()?;
537    let mut total: u64 = 0;
538    for _ in 0..groups {
539        let n = r.u32()?;
540        total += n as u64;
541        if total > 50_000 {
542            return err("too many locals");
543        }
544        let t = r.valtype()?;
545        for _ in 0..n {
546            locals.push(t);
547        }
548    }
549    let code = body.get(r.pos..).unwrap_or(&[]).to_vec();
550    let blocks = scan_blocks(&code)?;
551    Ok(Func { type_idx, locals, code, blocks })
552}
553
554/// 命令列を 1 回なめて、即値の長さと入れ子を確かめ、block/loop/if の else/end の位置を集める。
555fn scan_blocks(code: &[u8]) -> R<BTreeMap<usize, (Option<usize>, usize)>> {
556    let mut r = Reader::new(code);
557    let mut stack: Vec<(usize, Option<usize>)> = Vec::new();
558    let mut out = BTreeMap::new();
559    let mut ended = false;
560    while !r.eof() {
561        if ended {
562            return err("section size mismatch");
563        }
564        let at = r.pos;
565        let op = r.byte()?;
566        match op {
567            0x02..=0x04 => {
568                skip_blocktype(&mut r)?;
569                stack.push((at, None));
570            }
571            0x05 => match stack.last_mut() {
572                Some((start, els)) if code.get(*start) == Some(&0x04) && els.is_none() => *els = Some(at),
573                _ => return err("else without if"),
574            },
575            0x0b => match stack.pop() {
576                Some((start, els)) => {
577                    out.insert(start, (els, at));
578                }
579                None => ended = true,
580            },
581            _ => skip_immediates(op, &mut r)?,
582        }
583    }
584    if !ended || !stack.is_empty() {
585        return err("unexpected end of section or function");
586    }
587    Ok(out)
588}
589
590fn skip_blocktype(r: &mut Reader) -> R<()> {
591    let b = *r.b.get(r.pos).ok_or_else(|| DecodeError(String::from("unexpected end")))?;
592    if b == 0x40 || matches!(b, 0x7f | 0x7e | 0x7d | 0x7c | 0x70 | 0x6f) {
593        r.pos += 1;
594        Ok(())
595    } else {
596        r.sleb(33).map(|_| ())
597    }
598}
599
600fn skip_immediates(op: u8, r: &mut Reader) -> R<()> {
601    match op {
602        0x00 | 0x01 | 0x0f | 0x1a | 0x1b | 0x45..=0xc4 | 0xd1 => {}
603        0x0c | 0x0d | 0x10 | 0x20..=0x24 | 0x25 | 0x26 | 0xd2 => {
604            r.u32()?;
605        }
606        0x0e => {
607            for _ in 0..=r.u32()? {
608                r.u32()?;
609            }
610        }
611        0x11 => {
612            r.u32()?;
613            r.u32()?;
614        }
615        0x1c => {
616            for _ in 0..r.u32()? {
617                r.valtype()?;
618            }
619        }
620        0x28..=0x3e => {
621            r.u32()?;
622            r.u32()?;
623        }
624        0x3f | 0x40 => {
625            r.byte()?;
626        }
627        0x41 => {
628            r.sleb(32)?;
629        }
630        0x42 => {
631            r.sleb(64)?;
632        }
633        0x43 => {
634            r.bytes(4)?;
635        }
636        0x44 => {
637            r.bytes(8)?;
638        }
639        0xd0 => {
640            r.byte()?;
641        }
642        0xfc => {
643            let sub = r.u32()?;
644            match sub {
645                0..=7 => {}
646                8 => {
647                    r.u32()?;
648                    r.byte()?;
649                }
650                9 | 13 | 15 | 16 | 17 => {
651                    r.u32()?;
652                }
653                10 | 12 | 14 => {
654                    r.u32()?;
655                    r.u32()?;
656                }
657                11 => {
658                    r.byte()?;
659                }
660                _ => return err("illegal opcode"),
661            }
662        }
663        _ => return err("illegal opcode"),
664    }
665    Ok(())
666}
667
668fn validate_indices(m: &Module) -> R<()> {
669    let nfuncs = m.imported_funcs() + m.funcs.len();
670    for i in &m.imports {
671        if let ImportDesc::Func(t) = i.desc {
672            if t as usize >= m.types.len() {
673                return err("unknown type");
674            }
675        }
676    }
677    for f in &m.funcs {
678        if f.type_idx as usize >= m.types.len() {
679            return err("unknown type");
680        }
681    }
682    if m.imported_memories() + m.memories.len() > 1 {
683        return err("multiple memories");
684    }
685    for e in &m.exports {
686        let ok = match e.desc {
687            ExportDesc::Func(i) => (i as usize) < nfuncs,
688            ExportDesc::Table(i) => (i as usize) < m.imported_tables() + m.tables.len(),
689            ExportDesc::Memory(i) => (i as usize) < m.imported_memories() + m.memories.len(),
690            ExportDesc::Global(i) => (i as usize) < m.imported_globals() + m.globals.len(),
691        };
692        if !ok {
693            return err("unknown export index");
694        }
695    }
696    if let Some(s) = m.start {
697        if s as usize >= nfuncs {
698            return err("unknown function");
699        }
700        if m.func_type(s).is_some_and(|t| !t.params.is_empty() || !t.results.is_empty()) {
701            return err("start function");
702        }
703    }
704    Ok(())
705}