]> git.lizzy.rs Git - rust.git/blob - src/libstd/sys/sgx/abi/usercalls/mod.rs
SGX target: implement user memory management
[rust.git] / src / libstd / sys / sgx / abi / usercalls / mod.rs
1 // Copyright 2018 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 pub use fortanix_sgx_abi::*;
12
13 use io::{Error as IoError, Result as IoResult};
14
15 mod alloc;
16 #[macro_use]
17 mod raw;
18
19 pub fn exit(panic: bool) -> ! {
20     unsafe { raw::exit(panic) }
21 }
22
23 pub fn alloc(size: usize, alignment: usize) -> IoResult<*mut u8> {
24     unsafe { raw::alloc(size, alignment).from_sgx_result() }
25 }
26
27 pub use self::raw::free;
28
29 fn check_os_error(err: Result) -> i32 {
30     // FIXME: not sure how to make sure all variants of Error are covered
31     if err == Error::NotFound as _ ||
32        err == Error::PermissionDenied as _ ||
33        err == Error::ConnectionRefused as _ ||
34        err == Error::ConnectionReset as _ ||
35        err == Error::ConnectionAborted as _ ||
36        err == Error::NotConnected as _ ||
37        err == Error::AddrInUse as _ ||
38        err == Error::AddrNotAvailable as _ ||
39        err == Error::BrokenPipe as _ ||
40        err == Error::AlreadyExists as _ ||
41        err == Error::WouldBlock as _ ||
42        err == Error::InvalidInput as _ ||
43        err == Error::InvalidData as _ ||
44        err == Error::TimedOut as _ ||
45        err == Error::WriteZero as _ ||
46        err == Error::Interrupted as _ ||
47        err == Error::Other as _ ||
48        err == Error::UnexpectedEof as _ ||
49        ((Error::UserRangeStart as _)..=(Error::UserRangeEnd as _)).contains(&err)
50     {
51         err
52     } else {
53         panic!("Usercall: returned invalid error value {}", err)
54     }
55 }
56
57 trait FromSgxResult {
58     type Return;
59
60     fn from_sgx_result(self) -> IoResult<Self::Return>;
61 }
62
63 impl<T> FromSgxResult for (Result, T) {
64     type Return = T;
65
66     fn from_sgx_result(self) -> IoResult<Self::Return> {
67         if self.0 == RESULT_SUCCESS {
68             Ok(self.1)
69         } else {
70             Err(IoError::from_raw_os_error(check_os_error(self.0)))
71         }
72     }
73 }
74
75 impl FromSgxResult for Result {
76     type Return = ();
77
78     fn from_sgx_result(self) -> IoResult<Self::Return> {
79         if self == RESULT_SUCCESS {
80             Ok(())
81         } else {
82             Err(IoError::from_raw_os_error(check_os_error(self)))
83         }
84     }
85 }