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