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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
use crate::ocall::util::*;
use libc::{self, c_int, c_void, off_t, size_t};
use std::io::Error;
use std::mem;
use std::ptr;
#[cfg(target_arch = "x86")]
const MIN_ALIGN: usize = 8;
#[cfg(target_arch = "x86_64")]
const MIN_ALIGN: usize = 16;
#[no_mangle]
pub unsafe extern "C" fn u_malloc_ocall(
error: *mut c_int,
size: size_t,
align: size_t,
zeroed: c_int,
) -> *mut c_void {
if !align.is_power_of_two() {
set_error(error, libc::EINVAL);
return ptr::null_mut();
}
if size > usize::MAX - (align - 1) {
set_error(error, libc::EINVAL);
return ptr::null_mut();
}
let (ptr, errno) = if align <= MIN_ALIGN && align <= size {
let out: *mut c_void = libc::malloc(size);
if out.is_null() {
(out, Error::last_os_error().raw_os_error().unwrap_or(0))
} else {
(out, 0)
}
} else {
let mut out: *mut c_void = ptr::null_mut();
let align = align.max(mem::size_of::<usize>());
let ret = libc::posix_memalign(&mut out as *mut *mut c_void, align, size);
if ret != 0 {
(ptr::null_mut(), ret)
} else if out.is_null() {
(out, libc::ENOMEM)
} else {
(out, 0)
}
};
if errno == 0 && !ptr.is_null() && zeroed > 0 {
ptr.write_bytes(0_u8, size)
}
set_error(error, errno);
ptr
}
#[no_mangle]
pub unsafe extern "C" fn u_free_ocall(p: *mut c_void) {
libc::free(p)
}
#[no_mangle]
pub unsafe extern "C" fn u_mmap_ocall(
error: *mut c_int,
start: *mut c_void,
length: size_t,
prot: c_int,
flags: c_int,
fd: c_int,
offset: off_t,
) -> *mut c_void {
let mut errno = 0;
let ret = libc::mmap(start, length, prot, flags, fd, offset);
if ret as isize == -1 {
errno = Error::last_os_error().raw_os_error().unwrap_or(0);
}
set_error(error, errno);
ret
}
#[no_mangle]
pub unsafe extern "C" fn u_munmap_ocall(
error: *mut c_int,
start: *mut c_void,
length: size_t,
) -> c_int {
let mut errno = 0;
let ret = libc::munmap(start, length);
if ret < 0 {
errno = Error::last_os_error().raw_os_error().unwrap_or(0);
}
set_error(error, errno);
ret
}
#[no_mangle]
pub unsafe extern "C" fn u_msync_ocall(
error: *mut c_int,
addr: *mut c_void,
length: size_t,
flags: c_int,
) -> c_int {
let mut errno = 0;
let ret = libc::msync(addr, length, flags);
if ret < 0 {
errno = Error::last_os_error().raw_os_error().unwrap_or(0);
}
set_error(error, errno);
ret
}
#[no_mangle]
pub unsafe extern "C" fn u_mprotect_ocall(
error: *mut c_int,
addr: *mut c_void,
length: size_t,
prot: c_int,
) -> c_int {
let mut errno = 0;
let ret = libc::mprotect(addr, length, prot);
if ret < 0 {
errno = Error::last_os_error().raw_os_error().unwrap_or(0);
}
set_error(error, errno);
ret
}