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
pub mod ssvm_wasi_helper {

    #[no_mangle]
    pub fn _initialize() {
        extern "C" {
            fn __wasm_call_ctors();
        }
        static mut INITED: bool = false;
        if unsafe { INITED } {
            return;
        }
        unsafe { __wasm_call_ctors() };
        unsafe { INITED = true };
    }

    pub fn get_bytes_from_caller() -> Result<Vec<u8>, &'static str> {
        // Get data path from the caller
        let path = match std::env::var("SSVM_DATA_TO_CALLEE") {
            Err(_) => Err("No data found from caller. Please check the SSVM_DATA_TO_CALLEE is set"),
            Ok(val) => Ok(val),
        };

        // Read the data from the given path.
        match std::fs::read(&path.unwrap()) {
            Err(err) => {
                eprintln!("Failed to open file. Due to: {:?}", err);
                return Err("Cannot retrieve data from caller");
            },
            Ok(buf) => Ok(buf),
        }
    }

    pub fn get_string_from_caller() -> Result<String, &'static str> {
        // Get data path from the caller
        let path = match std::env::var("SSVM_DATA_TO_CALLEE") {
            Err(_) => Err("No data found from caller. Please check the SSVM_DATA_TO_CALLEE is set"),
            Ok(val) => Ok(val),
        };

        // Read the data from the given path.
        match std::fs::read(&path.unwrap()) {
            Err(err) => {
                eprintln!("Failed to open file. Due to: {:?}", err);
                return Err("Cannot retrieve data from caller");
            },
            Ok(buf) => Ok(String::from_utf8_lossy(&buf).to_string()),
        }
    }

    pub fn send_string_to_caller(s: &str) -> std::io::Result<()> {
        // Get data path from the caller
        let path = match std::env::var("SSVM_DATA_FROM_CALLEE") {
            Err(_) => Err("Cannot find path from caller. Please check the SSVM_DATA_FROM_CALLEE is set"),
            Ok(val) => Ok(val),
        };

        // Read the data from the given path.
        std::fs::write(&path.unwrap(), s)?;
        Ok(())
    }

    pub fn send_bytes_to_caller(bytes: &Vec<u8>) -> std::io::Result<()> {
        // Get data path from the caller
        let path = match std::env::var("SSVM_DATA_FROM_CALLEE") {
            Err(_) => Err("Cannot find path from caller. Please check the SSVM_DATA_FROM_CALLEE is set"),
            Ok(val) => Ok(val),
        };

        // Read the data from the given path.
        std::fs::write(&path.unwrap(), bytes)?;
        Ok(())
    }
}