third_party/rust/wasmparser/examples/dump.rs
author Oriol Brufau <oriol-bugzilla@hotmail.com>
Wed, 31 Oct 2018 16:15:54 +0000
changeset 500988 8a28169fa91dbde370d47bd91bc1b0c91f89cacf
parent 497122 8a644dda1dc3fef959d320ec4a737ba21a38dccb
child 504541 027bf8dee1e5bd49a0781a18e3b7d39051d70d6c
permissions -rw-r--r--
Bug 1499693 - Choose correct add-on icon size in about:addons. r=mstriemer,aswan, a=RyanVM Differential Revision: https://phabricator.services.mozilla.com/D9347

extern crate wasmparser;

use std::io;
use std::io::prelude::*;
use std::fs::File;
use std::str;
use std::env;
use wasmparser::WasmDecoder;
use wasmparser::Parser;
use wasmparser::ParserState;

fn get_name(bytes: &[u8]) -> &str {
    str::from_utf8(bytes).ok().unwrap()
}

fn main() {
    let args = env::args().collect::<Vec<_>>();
    if args.len() != 2 {
        println!("Usage: {} in.wasm", args[0]);
        return;
    }

    let ref buf: Vec<u8> = read_wasm(&args[1]).unwrap();
    let mut parser = Parser::new(buf);
    loop {
        let state = parser.read();
        match *state {
            ParserState::ExportSectionEntry {
                field,
                ref kind,
                index,
            } => {
                println!("ExportSectionEntry {{ field: \"{}\", kind: {:?}, index: {} }}",
                         get_name(field),
                         kind,
                         index);
            }
            ParserState::ImportSectionEntry {
                module,
                field,
                ref ty,
            } => {
                println!("ImportSectionEntry {{ module: \"{}\", field: \"{}\", ty: {:?} }}",
                         get_name(module),
                         get_name(field),
                         ty);
            }
            ParserState::EndWasm => break,
            ParserState::Error(err) => panic!("Error: {:?}", err),
            _ => println!("{:?}", state),
        }
    }
}

fn read_wasm(file: &str) -> io::Result<Vec<u8>> {
    let mut data = Vec::new();
    let mut f = File::open(file)?;
    f.read_to_end(&mut data)?;
    Ok(data)
}