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
// Copyright (C) 2020 Second State.
// This file is part of EVMC-Client.

// EVMC-Client is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.

// EVMC-Client is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.

// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use evmc_sys as ffi;
use std::ffi::{CStr, CString};
use std::os::raw::c_char;
use std::str;
extern crate num;
use num::FromPrimitive;

#[link(name = "evmc-loader")]
extern "C" {
    fn evmc_load_and_create(
        filename: *const c_char,
        evmc_loader_error_code: *mut i32,
    ) -> *mut ffi::evmc_instance;
    fn evmc_last_error_msg() -> *const c_char;
}

enum_from_primitive! {
#[derive(Debug)]
pub enum EvmcLoaderErrorCode {
    /** The loader succeeded. */
    EvmcLoaderSucces = 0,

    /** The loader cannot open the given file name. */
    EvmcLoaderCannotOpen = 1,

    /** The VM create function not found. */
    EvmcLoaderSymbolNotFound = 2,

    /** The invalid argument value provided. */
    EvmcLoaderInvalidArgument = 3,

    /** The creation of a VM instance has failed. */
    EvmcLoaderInstanceCreationFailure = 4,

    /** The ABI version of the VM instance has mismatched. */
    EvmcLoaderAbiVersionMismatch = 5,

    /** The VM option is invalid. */
    EvmcLoaderInvalidOptionName = 6,

    /** The VM option value is invalid. */
    EvmcLoaderInvalidOptionValue = 7,
}
}

fn error(err: EvmcLoaderErrorCode) -> Result<EvmcLoaderErrorCode, &'static str> {
    match err {
        EvmcLoaderErrorCode::EvmcLoaderSucces => Ok(EvmcLoaderErrorCode::EvmcLoaderSucces),
        _ => unsafe { Err(CStr::from_ptr(evmc_last_error_msg()).to_str().unwrap()) },
    }
}

pub fn load_and_create(
    fname: &str,
) -> (
    *mut ffi::evmc_instance,
    Result<EvmcLoaderErrorCode, &'static str>,
) {
    let c_str = CString::new(fname).unwrap();
    unsafe {
        let mut error_code: i32 = 0;
        let instance = evmc_load_and_create(c_str.as_ptr() as *const c_char, &mut error_code);
        return (
            instance,
            error(EvmcLoaderErrorCode::from_i32(error_code).unwrap()),
        );
    }
}