]> git.lizzy.rs Git - rust.git/blob - src/shims/foreign_items/posix.rs
Add a warning that Miri does not check for data-races.
[rust.git] / src / shims / foreign_items / posix.rs
1 mod linux;
2 mod macos;
3
4 use std::convert::TryFrom;
5
6 use log::trace;
7
8 use crate::*;
9 use rustc_index::vec::Idx;
10 use rustc_middle::mir;
11 use rustc_target::abi::{Align, LayoutOf, Size};
12
13 impl<'mir, 'tcx: 'mir> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
14 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
15     fn emulate_foreign_item_by_name(
16         &mut self,
17         link_name: &str,
18         args: &[OpTy<'tcx, Tag>],
19         dest: PlaceTy<'tcx, Tag>,
20         ret: mir::BasicBlock,
21     ) -> InterpResult<'tcx, bool> {
22         let this = self.eval_context_mut();
23
24         match link_name {
25             // Environment related shims
26             "getenv" => {
27                 let result = this.getenv(args[0])?;
28                 this.write_scalar(result, dest)?;
29             }
30             "unsetenv" => {
31                 let result = this.unsetenv(args[0])?;
32                 this.write_scalar(Scalar::from_i32(result), dest)?;
33             }
34             "setenv" => {
35                 let result = this.setenv(args[0], args[1])?;
36                 this.write_scalar(Scalar::from_i32(result), dest)?;
37             }
38             "getcwd" => {
39                 let result = this.getcwd(args[0], args[1])?;
40                 this.write_scalar(result, dest)?;
41             }
42             "chdir" => {
43                 let result = this.chdir(args[0])?;
44                 this.write_scalar(Scalar::from_i32(result), 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_i32(result), dest)?;
51             }
52             "fcntl" => {
53                 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
54                 this.write_scalar(Scalar::from_i32(result), dest)?;
55             }
56             "read" => {
57                 let result = this.read(args[0], args[1], args[2])?;
58                 this.write_scalar(Scalar::from_machine_isize(result, this), dest)?;
59             }
60             "write" => {
61                 let fd = this.read_scalar(args[0])?.to_i32()?;
62                 let buf = this.read_scalar(args[1])?.not_undef()?;
63                 let n = this.read_scalar(args[2])?.to_machine_usize(this)?;
64                 trace!("Called write({:?}, {:?}, {:?})", fd, buf, n);
65                 let result = if fd == 1 || fd == 2 {
66                     // stdout/stderr
67                     use std::io::{self, Write};
68
69                     let buf_cont = this.memory.read_bytes(buf, Size::from_bytes(n))?;
70                     // We need to flush to make sure this actually appears on the screen
71                     let res = if fd == 1 {
72                         // Stdout is buffered, flush to make sure it appears on the screen.
73                         // This is the write() syscall of the interpreted program, we want it
74                         // to correspond to a write() syscall on the host -- there is no good
75                         // in adding extra buffering here.
76                         let res = io::stdout().write(buf_cont);
77                         io::stdout().flush().unwrap();
78                         res
79                     } else {
80                         // No need to flush, stderr is not buffered.
81                         io::stderr().write(buf_cont)
82                     };
83                     match res {
84                         Ok(n) => i64::try_from(n).unwrap(),
85                         Err(_) => -1,
86                     }
87                 } else {
88                     this.write(args[0], args[1], args[2])?
89                 };
90                 // Now, `result` is the value we return back to the program.
91                 this.write_scalar(Scalar::from_machine_isize(result, this), dest)?;
92             }
93             "unlink" => {
94                 let result = this.unlink(args[0])?;
95                 this.write_scalar(Scalar::from_i32(result), dest)?;
96             }
97             "symlink" => {
98                 let result = this.symlink(args[0], args[1])?;
99                 this.write_scalar(Scalar::from_i32(result), dest)?;
100             }
101             "rename" => {
102                 let result = this.rename(args[0], args[1])?;
103                 this.write_scalar(Scalar::from_i32(result), dest)?;
104             }
105             "mkdir" => {
106                 let result = this.mkdir(args[0], args[1])?;
107                 this.write_scalar(Scalar::from_i32(result), dest)?;
108             }
109             "rmdir" => {
110                 let result = this.rmdir(args[0])?;
111                 this.write_scalar(Scalar::from_i32(result), dest)?;
112             }
113             "closedir" => {
114                 let result = this.closedir(args[0])?;
115                 this.write_scalar(Scalar::from_i32(result), dest)?;
116             }
117             "lseek" | "lseek64" => {
118                 let result = this.lseek64(args[0], args[1], args[2])?;
119                 // "lseek" is only used on macOS which is 64bit-only, so `i64` always works.
120                 this.write_scalar(Scalar::from_i64(result), dest)?;
121             }
122
123             // Allocation
124             "posix_memalign" => {
125                 let ret = this.deref_operand(args[0])?;
126                 let align = this.read_scalar(args[1])?.to_machine_usize(this)?;
127                 let size = this.read_scalar(args[2])?.to_machine_usize(this)?;
128                 // Align must be power of 2, and also at least ptr-sized (POSIX rules).
129                 if !align.is_power_of_two() {
130                     throw_ub_format!("posix_memalign: alignment must be a power of two, but is {}", align);
131                 }
132                 if align < this.pointer_size().bytes() {
133                     throw_ub_format!(
134                         "posix_memalign: alignment must be at least the size of a pointer, but is {}",
135                         align,
136                     );
137                 }
138
139                 if size == 0 {
140                     this.write_null(ret.into())?;
141                 } else {
142                     let ptr = this.memory.allocate(
143                         Size::from_bytes(size),
144                         Align::from_bytes(align).unwrap(),
145                         MiriMemoryKind::C.into(),
146                     );
147                     this.write_scalar(ptr, ret.into())?;
148                 }
149                 this.write_null(dest)?;
150             }
151
152             // Dynamic symbol loading
153             "dlsym" => {
154                 let _handle = this.read_scalar(args[0])?;
155                 let symbol = this.read_scalar(args[1])?.not_undef()?;
156                 let symbol_name = this.memory.read_c_str(symbol)?;
157                 let err = format!("bad c unicode symbol: {:?}", symbol_name);
158                 let symbol_name = ::std::str::from_utf8(symbol_name).unwrap_or(&err);
159                 if let Some(dlsym) = Dlsym::from_str(symbol_name)? {
160                     let ptr = this.memory.create_fn_alloc(FnVal::Other(dlsym));
161                     this.write_scalar(Scalar::from(ptr), dest)?;
162                 } else {
163                     this.write_null(dest)?;
164                 }
165             }
166
167             // Querying system information
168             "sysconf" => {
169                 let name = this.read_scalar(args[0])?.to_i32()?;
170
171                 let sysconfs = &[
172                     ("_SC_PAGESIZE", Scalar::from_int(PAGE_SIZE, this.pointer_size())),
173                     ("_SC_NPROCESSORS_ONLN", Scalar::from_int(NUM_CPUS, this.pointer_size())),
174                 ];
175                 let mut result = None;
176                 for &(sysconf_name, value) in sysconfs {
177                     let sysconf_name = this.eval_libc_i32(sysconf_name)?;
178                     if sysconf_name == name {
179                         result = Some(value);
180                         break;
181                     }
182                 }
183                 if let Some(result) = result {
184                     this.write_scalar(result, dest)?;
185                 } else {
186                     throw_unsup_format!("unimplemented sysconf name: {}", name)
187                 }
188             }
189
190             // Thread-local storage
191             "pthread_key_create" => {
192                 let key_place = this.deref_operand(args[0])?;
193
194                 // Extract the function type out of the signature (that seems easier than constructing it ourselves).
195                 let dtor = match this.test_null(this.read_scalar(args[1])?.not_undef()?)? {
196                     Some(dtor_ptr) => Some(this.memory.get_fn(dtor_ptr)?.as_instance()?),
197                     None => None,
198                 };
199
200                 // Figure out how large a pthread TLS key actually is.
201                 // To this end, deref the argument type. This is `libc::pthread_key_t`.
202                 let key_type = args[0].layout.ty
203                     .builtin_deref(true)
204                     .ok_or_else(|| err_ub_format!(
205                         "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
206                     ))?
207                     .ty;
208                 let key_layout = this.layout_of(key_type)?;
209
210                 // Create key and write it into the memory where `key_ptr` wants it.
211                 let key = this.machine.tls.create_tls_key(dtor, key_layout.size)?;
212                 this.write_scalar(Scalar::from_uint(key, key_layout.size), key_place.into())?;
213
214                 // Return success (`0`).
215                 this.write_null(dest)?;
216             }
217             "pthread_key_delete" => {
218                 let key = this.force_bits(this.read_scalar(args[0])?.not_undef()?, args[0].layout.size)?;
219                 this.machine.tls.delete_tls_key(key)?;
220                 // Return success (0)
221                 this.write_null(dest)?;
222             }
223             "pthread_getspecific" => {
224                 let key = this.force_bits(this.read_scalar(args[0])?.not_undef()?, args[0].layout.size)?;
225                 let active_thread = this.get_active_thread()?;
226                 let ptr = this.machine.tls.load_tls(key, active_thread, this)?;
227                 this.write_scalar(ptr, dest)?;
228             }
229             "pthread_setspecific" => {
230                 let key = this.force_bits(this.read_scalar(args[0])?.not_undef()?, args[0].layout.size)?;
231                 let active_thread = this.get_active_thread()?;
232                 let new_ptr = this.read_scalar(args[1])?.not_undef()?;
233                 this.machine.tls.store_tls(key, active_thread, this.test_null(new_ptr)?)?;
234
235                 // Return success (`0`).
236                 this.write_null(dest)?;
237             }
238
239             // Synchronization primitives
240             "pthread_mutexattr_init" => {
241                 let result = this.pthread_mutexattr_init(args[0])?;
242                 this.write_scalar(Scalar::from_i32(result), dest)?;
243             }
244             "pthread_mutexattr_settype" => {
245                 let result = this.pthread_mutexattr_settype(args[0], args[1])?;
246                 this.write_scalar(Scalar::from_i32(result), dest)?;
247             }
248             "pthread_mutexattr_destroy" => {
249                 let result = this.pthread_mutexattr_destroy(args[0])?;
250                 this.write_scalar(Scalar::from_i32(result), dest)?;
251             }
252             "pthread_mutex_init" => {
253                 let result = this.pthread_mutex_init(args[0], args[1])?;
254                 this.write_scalar(Scalar::from_i32(result), dest)?;
255             }
256             "pthread_mutex_lock" => {
257                 let result = this.pthread_mutex_lock(args[0])?;
258                 this.write_scalar(Scalar::from_i32(result), dest)?;
259             }
260             "pthread_mutex_trylock" => {
261                 let result = this.pthread_mutex_trylock(args[0])?;
262                 this.write_scalar(Scalar::from_i32(result), dest)?;
263             }
264             "pthread_mutex_unlock" => {
265                 let result = this.pthread_mutex_unlock(args[0])?;
266                 this.write_scalar(Scalar::from_i32(result), dest)?;
267             }
268             "pthread_mutex_destroy" => {
269                 let result = this.pthread_mutex_destroy(args[0])?;
270                 this.write_scalar(Scalar::from_i32(result), dest)?;
271             }
272             "pthread_rwlock_rdlock" => {
273                 let result = this.pthread_rwlock_rdlock(args[0])?;
274                 this.write_scalar(Scalar::from_i32(result), dest)?;
275             }
276             "pthread_rwlock_tryrdlock" => {
277                 let result = this.pthread_rwlock_tryrdlock(args[0])?;
278                 this.write_scalar(Scalar::from_i32(result), dest)?;
279             }
280             "pthread_rwlock_wrlock" => {
281                 let result = this.pthread_rwlock_wrlock(args[0])?;
282                 this.write_scalar(Scalar::from_i32(result), dest)?;
283             }
284             "pthread_rwlock_trywrlock" => {
285                 let result = this.pthread_rwlock_trywrlock(args[0])?;
286                 this.write_scalar(Scalar::from_i32(result), dest)?;
287             }
288             "pthread_rwlock_unlock" => {
289                 let result = this.pthread_rwlock_unlock(args[0])?;
290                 this.write_scalar(Scalar::from_i32(result), dest)?;
291             }
292             "pthread_rwlock_destroy" => {
293                 let result = this.pthread_rwlock_destroy(args[0])?;
294                 this.write_scalar(Scalar::from_i32(result), dest)?;
295             }
296
297             // Miscellaneous
298             "isatty" => {
299                 let _fd = this.read_scalar(args[0])?.to_i32()?;
300                 // "returns 1 if fd is an open file descriptor referring to a terminal; otherwise 0 is returned, and errno is set to indicate the error"
301                 // FIXME: we just say nothing is a terminal.
302                 let enotty = this.eval_libc("ENOTTY")?;
303                 this.set_last_error(enotty)?;
304                 this.write_null(dest)?;
305             }
306             "pthread_atfork" => {
307                 let _prepare = this.read_scalar(args[0])?.not_undef()?;
308                 let _parent = this.read_scalar(args[1])?.not_undef()?;
309                 let _child = this.read_scalar(args[1])?.not_undef()?;
310                 // We do not support forking, so there is nothing to do here.
311                 this.write_null(dest)?;
312             }
313             "sched_yield" => {
314                 this.write_null(dest)?;
315             }
316
317             // Threading
318             "pthread_create" => {
319                 println!("WARNING: The thread support is experimental. \
320                           For example, Miri does not detect data races yet.");
321                 assert_eq!(args.len(), 4);
322                 let func = args[2];
323                 let fn_ptr = this.read_scalar(func)?.not_undef()?;
324                 let fn_val = this.memory.get_fn(fn_ptr)?;
325                 let instance = match fn_val {
326                     rustc_mir::interpret::FnVal::Instance(instance) => instance,
327                     _ => unreachable!(),
328                 };
329                 let thread_info_place = this.deref_operand(args[0])?;
330                 let thread_info_type = args[0].layout.ty
331                     .builtin_deref(true)
332                     .ok_or_else(|| err_ub_format!(
333                         "wrong signature used for `pthread_create`: first argument must be a raw pointer."
334                     ))?
335                     .ty;
336                 let thread_info_layout = this.layout_of(thread_info_type)?;
337                 let func_arg = match *args[3] {
338                     rustc_mir::interpret::Operand::Immediate(immediate) => immediate,
339                     _ => unreachable!(),
340                 };
341                 let func_args = [func_arg];
342                 let ret_place =
343                     this.allocate(this.layout_of(this.tcx.types.usize)?, MiriMemoryKind::Machine.into());
344                 let new_thread_id = this.create_thread()?;
345                 let old_thread_id = this.set_active_thread(new_thread_id)?;
346                 this.call_function(
347                     instance,
348                     &func_args[..],
349                     Some(ret_place.into()),
350                     StackPopCleanup::None { cleanup: true },
351                 )?;
352                 this.set_active_thread(old_thread_id)?;
353                 this.write_scalar(
354                     Scalar::from_uint(new_thread_id.index() as u128, thread_info_layout.size),
355                     thread_info_place.into(),
356                 )?;
357
358                 // Return success (`0`).
359                 this.write_null(dest)?;
360             }
361             "pthread_join" => {
362                 assert_eq!(args.len(), 2);
363                 assert!(
364                     this.is_null(this.read_scalar(args[1])?.not_undef()?)?,
365                     "Miri supports pthread_join only with retval==NULL"
366                 );
367                 let thread = this.read_scalar(args[0])?.not_undef()?.to_machine_usize(this)?;
368                 this.join_thread(thread.into())?;
369
370                 // Return success (`0`).
371                 this.write_null(dest)?;
372             }
373             "pthread_detach" => {
374                 let thread = this.read_scalar(args[0])?.not_undef()?.to_machine_usize(this)?;
375                 this.detach_thread(thread.into())?;
376
377                 // Return success (`0`).
378                 this.write_null(dest)?;
379             }
380
381             "pthread_attr_getguardsize" => {
382                 assert_eq!(args.len(), 2);
383
384                 let guard_size = this.deref_operand(args[1])?;
385                 let guard_size_type = args[1].layout.ty
386                     .builtin_deref(true)
387                     .ok_or_else(|| err_ub_format!(
388                         "wrong signature used for `pthread_attr_getguardsize`: first argument must be a raw pointer."
389                     ))?
390                     .ty;
391                 let guard_size_layout = this.layout_of(guard_size_type)?;
392                 this.write_scalar(Scalar::from_uint(crate::PAGE_SIZE, guard_size_layout.size), guard_size.into())?;
393
394                 // Return success (`0`).
395                 this.write_null(dest)?;
396             }
397
398             "prctl" => {
399                 let option = this.read_scalar(args[0])?.not_undef()?.to_i32()?;
400                 assert_eq!(option, 0xf, "Miri supports only PR_SET_NAME");
401
402                 // Return success (`0`).
403                 this.write_null(dest)?;
404             }
405
406             // Incomplete shims that we "stub out" just to get pre-main initialziation code to work.
407             // These shims are enabled only when the caller is in the standard library.
408             | "pthread_attr_init"
409             | "pthread_attr_destroy"
410             | "pthread_self"
411             | "pthread_attr_setstacksize"
412             | "pthread_condattr_init"
413             | "pthread_condattr_setclock"
414             | "pthread_cond_init"
415             | "pthread_condattr_destroy"
416             | "pthread_cond_destroy" if this.frame().instance.to_string().starts_with("std::sys::unix::")
417             => {
418                 this.write_null(dest)?;
419             }
420
421             | "signal"
422             | "sigaction"
423             | "sigaltstack"
424             | "mprotect" if this.frame().instance.to_string().starts_with("std::sys::unix::")
425             => {
426                 this.write_null(dest)?;
427             }
428
429             // Platform-specific shims
430             _ => {
431                 match this.tcx.sess.target.target.target_os.as_str() {
432                     "linux" => return linux::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
433                     "macos" => return macos::EvalContextExt::emulate_foreign_item_by_name(this, link_name, args, dest, ret),
434                     _ => unreachable!(),
435                 }
436             }
437         };
438
439         Ok(true)
440     }
441 }