]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items/posix.rs
f524e4df291eeb669125ccbde8094fa881d20102
[rust.git] / src / shims / foreign_items / posix.rs
1 mod linux;
2 mod macos;
3
4 use crate::*;
5 use rustc::ty::layout::{Align, LayoutOf, Size};
6
7 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
8 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
9     fn emulate_foreign_item_by_name(
10         &mut self,
11         link_name: &str,
12         args: &[OpTy<'tcx, Tag>],
13         dest: PlaceTy<'tcx, Tag>,
14     ) -> InterpResult<'tcx> {
15         let this = self.eval_context_mut();
16         let tcx = &{ this.tcx.tcx };
17
18         match link_name {
19             // Environment related shims
20             "getenv" => {
21                 let result = this.getenv(args[0])?;
22                 this.write_scalar(result, dest)?;
23             }
24
25             "unsetenv" => {
26                 let result = this.unsetenv(args[0])?;
27                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
28             }
29
30             "setenv" => {
31                 let result = this.setenv(args[0], args[1])?;
32                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
33             }
34
35             "getcwd" => {
36                 let result = this.getcwd(args[0], args[1])?;
37                 this.write_scalar(result, dest)?;
38             }
39
40             "chdir" => {
41                 let result = this.chdir(args[0])?;
42                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
43             }
44
45             // File related shims
46             "fcntl" => {
47                 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
48                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
49             }
50
51             "read" => {
52                 let result = this.read(args[0], args[1], args[2])?;
53                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
54             }
55
56             "write" => {
57                 let fd = this.read_scalar(args[0])?.to_i32()?;
58                 let buf = this.read_scalar(args[1])?.not_undef()?;
59                 let n = this.read_scalar(args[2])?.to_machine_usize(tcx)?;
60                 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
61                 let result = if fd == 1 || fd == 2 {
62                     // stdout/stderr
63                     use std::io::{self, Write};
64
65                     let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
66                     // We need to flush to make sure this actually appears on the screen
67                     let res = if fd == 1 {
68                         // Stdout is buffered, flush to make sure it appears on the screen.
69                         // This is the write() syscall of the interpreted program, we want it
70                         // to correspond to a write() syscall on the host -- there is no good
71                         // in adding extra buffering here.
72                         let res = io::stdout().write(buf_cont);
73                         io::stdout().flush().unwrap();
74                         res
75                     } else {
76                         // No need to flush, stderr is not buffered.
77                         io::stderr().write(buf_cont)
78                     };
79                     match res {
80                         Ok(n) => n as i64,
81                         Err(_) => -1,
82                     }
83                 } else {
84                     this.write(args[0], args[1], args[2])?
85                 };
86                 // Now, `result` is the value we return back to the program.
87                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
88             }
89
90             "unlink" => {
91                 let result = this.unlink(args[0])?;
92                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
93             }
94
95             "symlink" => {
96                 let result = this.symlink(args[0], args[1])?;
97                 this.write_scalar(Scalar::from_int(result, dest.layout.size), dest)?;
98             }
99
100             "posix_memalign" => {
101                 let ret = this.deref_operand(args[0])?;
102                 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
103                 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
104                 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
105                 if !align.is_power_of_two() {
106                     throw_unsup!(HeapAllocNonPowerOfTwoAlignment(align));
107                 }
108                 if align < this.pointer_size().bytes() {
109                     throw_ub_format!(
110                         "posix_memalign: alignment must be at least the size of a pointer, but is {}",
111                         align,
112                     );
113                 }
114
115                 if size == 0 {
116                     this.write_null(ret.into())?;
117                 } else {
118                     let ptr = this.memory.allocate(
119                         Size::from_bytes(size),
120                         Align::from_bytes(align).unwrap(),
121                         MiriMemoryKind::C.into(),
122                     );
123                     this.write_scalar(ptr, ret.into())?;
124                 }
125                 this.write_null(dest)?;
126             }
127
128             "dlsym" => {
129                 let _handle = this.read_scalar(args[0])?;
130                 let symbol = this.read_scalar(args[1])?.not_undef()?;
131                 let symbol_name = this.memory.read_c_str(symbol)?;
132                 let err = format!("bad c unicode symbol: {:?}", symbol_name);
133                 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
134                 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
135                     let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
136                     this.write_scalar(Scalar::from(ptr), dest)?;
137                 } else {
138                     this.write_null(dest)?;
139                 }
140             }
141
142             "memrchr" => {
143                 let ptr = this.read_scalar(args[0])?.not_undef()?;
144                 let val = this.read_scalar(args[1])?.to_i32()? as u8;
145                 let num = this.read_scalar(args[2])?.to_machine_usize(this)?;
146                 if let Some(idx) = this
147                     .memory
148                     .read_bytes(ptr, Size::from_bytes(num))?
149                     .iter()
150                     .rev()
151                     .position(|&c| c == val)
152                 {
153                     let new_ptr = ptr.ptr_offset(Size::from_bytes(num - idx as u64 - 1), this)?;
154                     this.write_scalar(new_ptr, dest)?;
155                 } else {
156                     this.write_null(dest)?;
157                 }
158             }
159
160             // Hook pthread calls that go to the thread-local storage memory subsystem.
161             "pthread_key_create" => {
162                 let key_place = this.deref_operand(args[0])?;
163
164                 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
165                 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
166                     Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
167                     None => None,
168                 };
169
170                 // Figure out how large a pthread TLS key actually is.
171                 // This is `libc::pthread_key_t`.
172                 let key_type = args[0].layout.ty
173                     .builtin_deref(true)
174                     .ok_or_else(|| err_ub_format!(
175                         "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
176                     ))?
177                     .ty;
178                 let key_layout = this.layout_of(key_type)?;
179
180                 // Create key and write it into the memory where `key_ptr` wants it.
181                 let key = this.machine.tls.create_tls_key(dtor) as u128;
182                 if key_layout.size.bits() < 128 && key >= (1u128 << key_layout.size.bits() as u128)
183                 {
184                     throw_unsup!(OutOfTls);
185                 }
186
187                 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
188
189                 // Return success (`0`).
190                 this.write_null(dest)?;
191             }
192             "pthread_key_delete" => {
193                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
194                 this.machine.tls.delete_tls_key(key)?;
195                 // Return success (0)
196                 this.write_null(dest)?;
197             }
198             "pthread_getspecific" => {
199                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
200                 let ptr = this.machine.tls.load_tls(key, tcx)?;
201                 this.write_scalar(ptr, dest)?;
202             }
203             "pthread_setspecific" => {
204                 let key = this.read_scalar(args[0])?.to_bits(args[0].layout.size)?;
205                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
206                 this.machine.tls.store_tls(key, this.test_null(new_ptr)?)?;
207
208                 // Return success (`0`).
209                 this.write_null(dest)?;
210             }
211
212             // Stack size/address stuff.
213             | "pthread_attr_init"
214             | "pthread_attr_destroy"
215             | "pthread_self"
216             | "pthread_attr_setstacksize" => {
217                 this.write_null(dest)?;
218             }
219             "pthread_attr_getstack" => {
220                 let addr_place = this.deref_operand(args[1])?;
221                 let size_place = this.deref_operand(args[2])?;
222
223                 this.write_scalar(
224                     Scalar::from_uint(STACK_ADDR, addr_place.layout.size),
225                     addr_place.into(),
226                 )?;
227                 this.write_scalar(
228                     Scalar::from_uint(STACK_SIZE, size_place.layout.size),
229                     size_place.into(),
230                 )?;
231
232                 // Return success (`0`).
233                 this.write_null(dest)?;
234             }
235
236             // We don't support threading. (Also for Windows.)
237             | "pthread_create"
238             | "CreateThread"
239             => {
240                 throw_unsup_format!("Miri does not support threading");
241             }
242
243             // Stub out calls for condvar, mutex and rwlock, to just return `0`.
244             | "pthread_mutexattr_init"
245             | "pthread_mutexattr_settype"
246             | "pthread_mutex_init"
247             | "pthread_mutexattr_destroy"
248             | "pthread_mutex_lock"
249             | "pthread_mutex_unlock"
250             | "pthread_mutex_destroy"
251             | "pthread_rwlock_rdlock"
252             | "pthread_rwlock_unlock"
253             | "pthread_rwlock_wrlock"
254             | "pthread_rwlock_destroy"
255             | "pthread_condattr_init"
256             | "pthread_condattr_setclock"
257             | "pthread_cond_init"
258             | "pthread_condattr_destroy"
259             | "pthread_cond_destroy"
260             => {
261                 this.write_null(dest)?;
262             }
263
264             // We don't support fork so we don't have to do anything for atfork.
265             "pthread_atfork" => {
266                 this.write_null(dest)?;
267             }
268
269             // Some things needed for `sys::thread` initialization to go through.
270             | "signal"
271             | "sigaction"
272             | "sigaltstack"
273             => {
274                 this.write_scalar(Scalar::from_int(0, dest.layout.size), dest)?;
275             }
276
277             "sysconf" => {
278                 let name = this.read_scalar(args[0])?.to_i32()?;
279
280                 trace!("sysconf() called with name {}", name);
281                 // TODO: Cache the sysconf integers via Miri's global cache.
282                 let paths = &[
283                     (&["libc", "_SC_PAGESIZE"], Scalar::from_int(PAGE_SIZE, dest.layout.size)),
284                     (&["libc", "_SC_GETPW_R_SIZE_MAX"], Scalar::from_int(-1, dest.layout.size)),
285                     (
286                         &["libc", "_SC_NPROCESSORS_ONLN"],
287                         Scalar::from_int(NUM_CPUS, dest.layout.size),
288                     ),
289                 ];
290                 let mut result = None;
291                 for &(path, path_value) in paths {
292                     if let Some(val) = this.eval_path_scalar(path)? {
293                         let val = val.to_i32()?;
294                         if val == name {
295                             result = Some(path_value);
296                             break;
297                         }
298                     }
299                 }
300                 if let Some(result) = result {
301                     this.write_scalar(result, dest)?;
302                 } else {
303                     throw_unsup_format!("Unimplemented sysconf name: {}", name)
304                 }
305             }
306
307             "isatty" => {
308                 this.write_null(dest)?;
309             }
310
311             "posix_fadvise" => {
312                 // fadvise is only informational, we can ignore it.
313                 this.write_null(dest)?;
314             }
315
316             "mmap" => {
317                 // This is a horrible hack, but since the guard page mechanism calls mmap and expects a particular return value, we just give it that value.
318                 let addr = this.read_scalar(args[0])?.not_undef()?;
319                 this.write_scalar(addr, dest)?;
320             }
321
322             "mprotect" => {
323                 this.write_null(dest)?;
324             }
325
326             _ => {
327                 match this.tcx.sess.target.target.target_os.to_lowercase().as_str() {
328                     "linux" => linux::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest)?,
329                     "macos" => macos::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest)?,
330                     _ => unreachable!(),
331                 }
332             }
333         };
334
335         Ok(())
336     }
337 }
338
339 // Shims the posix 'getrandom()' syscall.
340 fn getrandom<'tcx>(
341     this: &mut MiriEvalContext<'_, 'tcx>,
342     args: &[OpTy<'tcx, Tag>],
343     dest: PlaceTy<'tcx, Tag>,
344 ) -> InterpResult<'tcx> {
345     let ptr = this.read_scalar(args[0])?.not_undef()?;
346     let len = this.read_scalar(args[1])?.to_machine_usize(this)?;
347
348     // The only supported flags are GRND_RANDOM and GRND_NONBLOCK,
349     // neither of which have any effect on our current PRNG.
350     let _flags = this.read_scalar(args[2])?.to_i32()?;
351
352     this.gen_random(ptr, len as usize)?;
353     this.write_scalar(Scalar::from_uint(len, dest.layout.size), dest)?;
354     Ok(())
355 }