fn execute_wasm(options: &Run) -> Result<(), String> {
    // force disable caching on windows
    #[cfg(target_os = "windows")]
    let disable_cache = true;
    #[cfg(not(target_os = "windows"))]
    let disable_cache = options.disable_cache;

    let wasm_path = &options.path;

    let mut wasm_binary: Vec<u8> = read_file_contents(wasm_path).map_err(|err| {
        format!(
            "Can't read the file {}: {}",
            wasm_path.as_os_str().to_string_lossy(),
            err
        )
    })?;

    let em_symbol_map = if let Some(em_symbol_map_path) = options.em_symbol_map.clone() {
        let em_symbol_map_content: String = read_to_string(&em_symbol_map_path)
            .map_err(|err| {
                format!(
                    "Can't read symbol map file {}: {}",
                    em_symbol_map_path.as_os_str().to_string_lossy(),
                    err,
                )
            })?
            .to_owned();
        let mut em_symbol_map = HashMap::new();
        for line in em_symbol_map_content.lines() {
            let mut split = line.split(':');
            let num_str = if let Some(ns) = split.next() {
                ns
            } else {
                return Err(format!(
                    "Can't parse symbol map (expected each entry to be of the form: `0:func_name`)"
                ));
            };
            let num: u32 = num_str.parse::<u32>().map_err(|err| {
                format!(
                    "Failed to parse {} as a number in symbol map: {}",
                    num_str, err
                )
            })?;
            let name_str: String = if let Some(name_str) = split.next() {
                name_str
            } else {
                return Err(format!(
                    "Can't parse symbol map (expected each entry to be of the form: `0:func_name`)"
                ));
            }
            .to_owned();

            em_symbol_map.insert(num, name_str);
        }
        Some(em_symbol_map)
    } else {
        None
    };

    if !utils::is_wasm_binary(&wasm_binary) {
        wasm_binary = wabt::wat2wasm(wasm_binary)
            .map_err(|e| format!("Can't convert from wast to wasm: {:?}", e))?;
    }

    let module = if !disable_cache {
        // If we have cache enabled

        // We generate a hash for the given binary, so we can use it as key
        // for the Filesystem cache
        let hash = WasmHash::generate(&wasm_binary);

        let wasmer_cache_dir = get_cache_dir();

        // We create a new cache instance.
        // It could be possible to use any other kinds of caching, as long as they
        // implement the Cache trait (with save and load functions)
        let mut cache = unsafe {
            FileSystemCache::new(wasmer_cache_dir).map_err(|e| format!("Cache error: {:?}", e))?
        };

        // cache.load will return the Module if it's able to deserialize it properly, and an error if:
        // * The file is not found
        // * The file exists, but it's corrupted or can't be converted to a module
        let module = match cache.load(hash) {
            Ok(module) => {
                // We are able to load the module from cache
                module
            }
            Err(_) => {
                let module = webassembly::compile_with_config(
                    &wasm_binary[..],
                    CompilerConfig {
                        symbol_map: em_symbol_map,
                    },
                )
                .map_err(|e| format!("Can't compile module: {:?}", e))?;
                // We try to save the module into a cache file
                cache.store(hash, module.clone()).unwrap_or_default();

                module
            }
        };
        module
    } else {
        webassembly::compile_with_config(
            &wasm_binary[..],
            CompilerConfig {
                symbol_map: em_symbol_map,
            },
        )
        .map_err(|e| format!("Can't compile module: {:?}", e))?
    };

    // TODO: refactor this
    let (abi, import_object, _em_globals) = if wasmer_emscripten::is_emscripten_module(&module) {
        let mut emscripten_globals = wasmer_emscripten::EmscriptenGlobals::new(&module);
        (
            InstanceABI::Emscripten,
            wasmer_emscripten::generate_emscripten_env(&mut emscripten_globals),
            Some(emscripten_globals), // TODO Em Globals is here to extend, lifetime, find better solution
        )
    } else {
        if cfg!(feature = "wasi") && wasmer_wasi::is_wasi_module(&module) {
            (
                InstanceABI::WASI,
                wasmer_wasi::generate_import_object(
                    [options.path.to_str().unwrap().to_owned()]
                        .iter()
                        .chain(options.args.iter())
                        .cloned()
                        .map(|arg| arg.into_bytes())
                        .collect(),
                    env::vars()
                        .map(|(k, v)| format!("{}={}", k, v).into_bytes())
                        .collect(),
                ),
                None,
            )
        } else {
            (
                InstanceABI::None,
                wasmer_runtime_core::import::ImportObject::new(),
                None,
            )
        }
    };

    let mut instance = module
        .instantiate(&import_object)
        .map_err(|e| format!("Can't instantiate module: {:?}", e))?;

    webassembly::run_instance(
        &module,
        &mut instance,
        abi,
        options.path.to_str().unwrap(),
        options.args.iter().map(|arg| arg.as_str()).collect(),
    )
    .map_err(|e| format!("{:?}", e))?;

    Ok(())
}
/// Execute a wasm/wat file
Execute a wasm/wat file
Execute a wasm / wat file
fn execute_wasm(options: &Run) -> Result<(), String> {
    // force disable caching on windows
    #[cfg(target_os = "windows")]
    let disable_cache = true;
    #[cfg(not(target_os = "windows"))]
    let disable_cache = options.disable_cache;
    let wasm_path = &options.path;
    let mut wasm_binary: Vec<u8> = read_file_contents(wasm_path).map_err(|err| {
        format!(
            "Can't read the file {}: {}",
            wasm_path.as_os_str().to_string_lossy(),
            err
        )
    })?;
    let em_symbol_map = if let Some(em_symbol_map_path) = options.em_symbol_map.clone() {
        let em_symbol_map_content: String = read_to_string(&em_symbol_map_path)
            .map_err(|err| {
                format!(
                    "Can't read symbol map file {}: {}",
                    em_symbol_map_path.as_os_str().to_string_lossy(),
                    err,
                )
            })?
            .to_owned();
        let mut em_symbol_map = HashMap::new();
        for line in em_symbol_map_content.lines() {
            let mut split = line.split(':');
            let num_str = if let Some(ns) = split.next() {
                ns
            } else {
                return Err(format!(
                    "Can't parse symbol map (expected each entry to be of the form: `0:func_name`)"
                ));
            };
            let num: u32 = num_str.parse::<u32>().map_err(|err| {
                format!(
                    "Failed to parse {} as a number in symbol map: {}",
                    num_str, err
                )
            })?;
            let name_str: String = if let Some(name_str) = split.next() {
                name_str
            } else {
                return Err(format!(
                    "Can't parse symbol map (expected each entry to be of the form: `0:func_name`)"
                ));
            }
            .to_owned();
            em_symbol_map.insert(num, name_str);
        }
        Some(em_symbol_map)
    } else {
        None
    };
    if !utils::is_wasm_binary(&wasm_binary) {
        wasm_binary = wabt::wat2wasm(wasm_binary)
            .map_err(|e| format!("Can't convert from wast to wasm: {:?}", e))?;
    }
    let module = if !disable_cache {
        // If we have cache enabled
        // We generate a hash for the given binary, so we can use it as key
        // for the Filesystem cache
        let hash = WasmHash::generate(&wasm_binary);
        let wasmer_cache_dir = get_cache_dir();
        // We create a new cache instance.
        // It could be possible to use any other kinds of caching, as long as they
        // implement the Cache trait (with save and load functions)
        let mut cache = unsafe {
            FileSystemCache::new(wasmer_cache_dir).map_err(|e| format!("Cache error: {:?}", e))?
        };
        // cache.load will return the Module if it's able to deserialize it properly, and an error if:
        // * The file is not found
        // * The file exists, but it's corrupted or can't be converted to a module
        let module = match cache.load(hash) {
            Ok(module) => {
                // We are able to load the module from cache
                module
            }
            Err(_) => {
                let module = webassembly::compile_with_config(
                    &wasm_binary[..],
                    CompilerConfig {
                        symbol_map: em_symbol_map,
                    },
                )
                .map_err(|e| format!("Can't compile module: {:?}", e))?;
                // We try to save the module into a cache file
                cache.store(hash, module.clone()).unwrap_or_default();
                module
            }
        };
        module
    } else {
        webassembly::compile_with_config(
            &wasm_binary[..],
            CompilerConfig {
                symbol_map: em_symbol_map,
            },
        )
        .map_err(|e| format!("Can't compile module: {:?}", e))?
    };
    // TODO: refactor this
    let (abi, import_object, _em_globals) = if wasmer_emscripten::is_emscripten_module(&module) {
        let mut emscripten_globals = wasmer_emscripten::EmscriptenGlobals::new(&module);
        (
            InstanceABI::Emscripten,
            wasmer_emscripten::generate_emscripten_env(&mut emscripten_globals),
            Some(emscripten_globals), // TODO Em Globals is here to extend, lifetime, find better solution
        )
    } else {
        if cfg!(feature = "wasi") && wasmer_wasi::is_wasi_module(&module) {
            (
                InstanceABI::WASI,
                wasmer_wasi::generate_import_object(
                    [options.path.to_str().unwrap().to_owned()]
                        .iter()
                        .chain(options.args.iter())
                        .cloned()
                        .map(|arg| arg.into_bytes())
                        .collect(),
                    env::vars()
                        .map(|(k, v)| format!("{}={}", k, v).into_bytes())
                        .collect(),
                ),
                None,
            )
        } else {
            (
                InstanceABI::None,
                wasmer_runtime_core::import::ImportObject::new(),
                None,
            )
        }
    };
    let mut instance = module
        .instantiate(&import_object)
        .map_err(|e| format!("Can't instantiate module: {:?}", e))?;
    webassembly::run_instance(
        &module,
        &mut instance,
        abi,
        options.path.to_str().unwrap(),
        options.args.iter().map(|arg| arg.as_str()).collect(),
    )
    .map_err(|e| format!("{:?}", e))?;
    Ok(())
}
fn execute_wasm ( options : & Run ) -> Result < ( ) , String > { // force disable caching on windows # [ cfg ( target_os " " ) ] let disable_cache = true ; # [ cfg ( not ( target_os " " ) ) ] let disable_cache = options . disable_cache ; let wasm_path = & options . path ; let mut wasm_binary : Vec < u8 > = read_file_contents ( wasm_path ) . map_err ( | err | { format ! ( " " wasm_path as_os_str ( ) to_string_lossy ( ) err ) } ) ? ; let em_symbol_map = if let Some ( em_symbol_map_path ) = options . em_symbol_map . clone ( ) { let em_symbol_map_content : String = read_to_string ( & em_symbol_map_path ) . map_err ( | err | { format ! ( " " em_symbol_map_path as_os_str ( ) to_string_lossy ( ) err ) } ) ? . to_owned ( ) ; let mut em_symbol_map = HashMap :: new ( ) ; for line in em_symbol_map_content . lines ( ) { let mut split = line . split ( ':' ) ; let num_str = if let Some ( ns ) = split . next ( ) { ns } else { return Err ( format ! ( " " ) ) ; } ; let num : u32 = num_str . parse :: < u32 > ( ) . map_err ( | err | { format ! ( " " num_str err ) } ) ? ; let name_str : String = if let Some ( name_str ) = split . next ( ) { name_str } else { return Err ( format ! ( " " ) ) ; } . to_owned ( ) ; em_symbol_map . insert ( num , name_str ) ; } Some ( em_symbol_map ) } else { None } ; if ! utils :: is_wasm_binary ( & wasm_binary ) { wasm_binary = wabt :: wat2wasm ( wasm_binary ) . map_err ( | e | format ! ( " " e ) ) ? ; } let module = if ! disable_cache { // If we have cache enabled // We generate a hash for the given binary, so we can use it as key // for the Filesystem cache let hash = WasmHash :: generate ( & wasm_binary ) ; let wasmer_cache_dir = get_cache_dir ( ) ; // We create a new cache instance. // It could be possible to use any other kinds of caching, as long as they // implement the Cache trait (with save and load functions) let mut cache = unsafe { FileSystemCache :: new ( wasmer_cache_dir ) . map_err ( | e | format ! ( " " e ) ) ? } ; // cache.load will return the Module if it's able to deserialize it properly, and an error if: // * The file is not found // * The file exists, but it's corrupted or can't be converted to a module let module = match cache . load ( hash ) { Ok ( module ) => { // We are able to load the module from cache module } Err ( _ ) => { let module = webassembly :: compile_with_config ( & wasm_binary [ .. ] , CompilerConfig { symbol_map : em_symbol_map , } , ) . map_err ( | e | format ! ( " " e ) ) ? ; // We try to save the module into a cache file cache . store ( hash , module . clone ( ) ) . unwrap_or_default ( ) ; module } } ; module } else { webassembly :: compile_with_config ( & wasm_binary [ .. ] , CompilerConfig { symbol_map : em_symbol_map , } , ) . map_err ( | e | format ! ( " " e ) ) ? } ; // TODO: refactor this let ( abi , import_object , _em_globals ) = if wasmer_emscripten :: is_emscripten_module ( & module ) { let mut emscripten_globals = wasmer_emscripten :: EmscriptenGlobals :: new ( & module ) ; ( InstanceABI :: Emscripten , wasmer_emscripten :: generate_emscripten_env ( & mut emscripten_globals ) , Some ( emscripten_globals ) , // TODO Em Globals is here to extend, lifetime, find better solution ) } else { if cfg ! ( feature " " ) && wasmer_wasi :: is_wasi_module ( & module ) { ( InstanceABI :: WASI , wasmer_wasi :: generate_import_object ( [ options . path . to_str ( ) . unwrap ( ) . to_owned ( ) ] . iter ( ) . chain ( options . args . iter ( ) ) . cloned ( ) . map ( | arg | arg . into_bytes ( ) ) . collect ( ) , env :: vars ( ) . map ( | ( k , v ) | format ! ( " " k v ) . into_bytes ( ) ) . collect ( ) , ) , None , ) } else { ( InstanceABI :: None , wasmer_runtime_core :: import :: ImportObject :: new ( ) , None , ) } } ; let mut instance = module . instantiate ( & import_object ) . map_err ( | e | format ! ( " " e ) ) ? ; webassembly :: run_instance ( & module , & mut instance , abi , options . path . to_str ( ) . unwrap ( ) , options . args . iter ( ) . map ( | arg | arg . as_str ( ) ) . collect ( ) , ) . map_err ( | e | format ! ( " " e ) ) ? ; Ok ( ( ) ) }
Execute a wasm/wat file
Execute a wasm / wat file
options
&Run
options
&Run