4 use std::convert::TryFrom;
9 use rustc_index::vec::Idx;
10 use rustc_middle::mir;
11 use rustc_target::abi::{Align, LayoutOf, Size};
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(
18 args: &[OpTy<'tcx, Tag>],
19 dest: PlaceTy<'tcx, Tag>,
21 ) -> InterpResult<'tcx, bool> {
22 let this = self.eval_context_mut();
25 // Environment related shims
27 let result = this.getenv(args[0])?;
28 this.write_scalar(result, dest)?;
31 let result = this.unsetenv(args[0])?;
32 this.write_scalar(Scalar::from_i32(result), dest)?;
35 let result = this.setenv(args[0], args[1])?;
36 this.write_scalar(Scalar::from_i32(result), dest)?;
39 let result = this.getcwd(args[0], args[1])?;
40 this.write_scalar(result, dest)?;
43 let result = this.chdir(args[0])?;
44 this.write_scalar(Scalar::from_i32(result), dest)?;
48 "open" | "open64" => {
49 let result = this.open(args[0], args[1])?;
50 this.write_scalar(Scalar::from_i32(result), dest)?;
53 let result = this.fcntl(args[0], args[1], args.get(2).cloned())?;
54 this.write_scalar(Scalar::from_i32(result), dest)?;
57 let result = this.read(args[0], args[1], args[2])?;
58 this.write_scalar(Scalar::from_machine_isize(result, this), dest)?;
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 {
67 use std::io::{self, Write};
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();
80 // No need to flush, stderr is not buffered.
81 io::stderr().write(buf_cont)
84 Ok(n) => i64::try_from(n).unwrap(),
88 this.write(args[0], args[1], args[2])?
90 // Now, `result` is the value we return back to the program.
91 this.write_scalar(Scalar::from_machine_isize(result, this), dest)?;
94 let result = this.unlink(args[0])?;
95 this.write_scalar(Scalar::from_i32(result), dest)?;
98 let result = this.symlink(args[0], args[1])?;
99 this.write_scalar(Scalar::from_i32(result), dest)?;
102 let result = this.rename(args[0], args[1])?;
103 this.write_scalar(Scalar::from_i32(result), dest)?;
106 let result = this.mkdir(args[0], args[1])?;
107 this.write_scalar(Scalar::from_i32(result), dest)?;
110 let result = this.rmdir(args[0])?;
111 this.write_scalar(Scalar::from_i32(result), dest)?;
114 let result = this.closedir(args[0])?;
115 this.write_scalar(Scalar::from_i32(result), dest)?;
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)?;
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);
132 if align < this.pointer_size().bytes() {
134 "posix_memalign: alignment must be at least the size of a pointer, but is {}",
140 this.write_null(ret.into())?;
142 let ptr = this.memory.allocate(
143 Size::from_bytes(size),
144 Align::from_bytes(align).unwrap(),
145 MiriMemoryKind::C.into(),
147 this.write_scalar(ptr, ret.into())?;
149 this.write_null(dest)?;
152 // Dynamic symbol loading
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)?;
163 this.write_null(dest)?;
167 // Querying system information
169 let name = this.read_scalar(args[0])?.to_i32()?;
172 ("_SC_PAGESIZE", Scalar::from_int(PAGE_SIZE, this.pointer_size())),
173 ("_SC_NPROCESSORS_ONLN", Scalar::from_int(NUM_CPUS, this.pointer_size())),
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);
183 if let Some(result) = result {
184 this.write_scalar(result, dest)?;
186 throw_unsup_format!("unimplemented sysconf name: {}", name)
190 // Thread-local storage
191 "pthread_key_create" => {
192 let key_place = this.deref_operand(args[0])?;
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()?),
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
204 .ok_or_else(|| err_ub_format!(
205 "wrong signature used for `pthread_key_create`: first argument must be a raw pointer."
208 let key_layout = this.layout_of(key_type)?;
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())?;
214 // Return success (`0`).
215 this.write_null(dest)?;
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)?;
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)?;
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)?)?;
235 // Return success (`0`).
236 this.write_null(dest)?;
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)?;
244 "pthread_mutexattr_settype" => {
245 let result = this.pthread_mutexattr_settype(args[0], args[1])?;
246 this.write_scalar(Scalar::from_i32(result), dest)?;
248 "pthread_mutexattr_destroy" => {
249 let result = this.pthread_mutexattr_destroy(args[0])?;
250 this.write_scalar(Scalar::from_i32(result), dest)?;
252 "pthread_mutex_init" => {
253 let result = this.pthread_mutex_init(args[0], args[1])?;
254 this.write_scalar(Scalar::from_i32(result), dest)?;
256 "pthread_mutex_lock" => {
257 let result = this.pthread_mutex_lock(args[0])?;
258 this.write_scalar(Scalar::from_i32(result), dest)?;
260 "pthread_mutex_trylock" => {
261 let result = this.pthread_mutex_trylock(args[0])?;
262 this.write_scalar(Scalar::from_i32(result), dest)?;
264 "pthread_mutex_unlock" => {
265 let result = this.pthread_mutex_unlock(args[0])?;
266 this.write_scalar(Scalar::from_i32(result), dest)?;
268 "pthread_mutex_destroy" => {
269 let result = this.pthread_mutex_destroy(args[0])?;
270 this.write_scalar(Scalar::from_i32(result), dest)?;
272 "pthread_rwlock_rdlock" => {
273 let result = this.pthread_rwlock_rdlock(args[0])?;
274 this.write_scalar(Scalar::from_i32(result), dest)?;
276 "pthread_rwlock_tryrdlock" => {
277 let result = this.pthread_rwlock_tryrdlock(args[0])?;
278 this.write_scalar(Scalar::from_i32(result), dest)?;
280 "pthread_rwlock_wrlock" => {
281 let result = this.pthread_rwlock_wrlock(args[0])?;
282 this.write_scalar(Scalar::from_i32(result), dest)?;
284 "pthread_rwlock_trywrlock" => {
285 let result = this.pthread_rwlock_trywrlock(args[0])?;
286 this.write_scalar(Scalar::from_i32(result), dest)?;
288 "pthread_rwlock_unlock" => {
289 let result = this.pthread_rwlock_unlock(args[0])?;
290 this.write_scalar(Scalar::from_i32(result), dest)?;
292 "pthread_rwlock_destroy" => {
293 let result = this.pthread_rwlock_destroy(args[0])?;
294 this.write_scalar(Scalar::from_i32(result), dest)?;
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)?;
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)?;
314 this.write_null(dest)?;
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);
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,
329 let thread_info_place = this.deref_operand(args[0])?;
330 let thread_info_type = args[0].layout.ty
332 .ok_or_else(|| err_ub_format!(
333 "wrong signature used for `pthread_create`: first argument must be a raw pointer."
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,
341 let func_args = [func_arg];
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)?;
349 Some(ret_place.into()),
350 StackPopCleanup::None { cleanup: true },
352 this.set_active_thread(old_thread_id)?;
354 Scalar::from_uint(new_thread_id.index() as u128, thread_info_layout.size),
355 thread_info_place.into(),
358 // Return success (`0`).
359 this.write_null(dest)?;
362 assert_eq!(args.len(), 2);
364 this.is_null(this.read_scalar(args[1])?.not_undef()?)?,
365 "Miri supports pthread_join only with retval==NULL"
367 let thread = this.read_scalar(args[0])?.not_undef()?.to_machine_usize(this)?;
368 this.join_thread(thread.into())?;
370 // Return success (`0`).
371 this.write_null(dest)?;
373 "pthread_detach" => {
374 let thread = this.read_scalar(args[0])?.not_undef()?.to_machine_usize(this)?;
375 this.detach_thread(thread.into())?;
377 // Return success (`0`).
378 this.write_null(dest)?;
381 "pthread_attr_getguardsize" => {
382 assert_eq!(args.len(), 2);
384 let guard_size = this.deref_operand(args[1])?;
385 let guard_size_type = args[1].layout.ty
387 .ok_or_else(|| err_ub_format!(
388 "wrong signature used for `pthread_attr_getguardsize`: first argument must be a raw pointer."
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())?;
394 // Return success (`0`).
395 this.write_null(dest)?;
399 let option = this.read_scalar(args[0])?.not_undef()?.to_i32()?;
400 assert_eq!(option, 0xf, "Miri supports only PR_SET_NAME");
402 // Return success (`0`).
403 this.write_null(dest)?;
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"
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::")
418 this.write_null(dest)?;
424 | "mprotect" if this.frame().instance.to_string().starts_with("std::sys::unix::")
426 this.write_null(dest)?;
429 // Platform-specific shims
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),