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