]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
add `statx` shim for linux
[rust.git] / src / shims / env.rs
1 use std::collections::HashMap;
2 use std::ffi::OsString;
3 use std::env;
4
5 use crate::stacked_borrows::Tag;
6 use crate::*;
7
8 use rustc::ty::layout::Size;
9 use rustc_mir::interpret::{Memory, Pointer};
10
11 #[derive(Default)]
12 pub struct EnvVars {
13     /// Stores pointers to the environment variables. These variables must be stored as
14     /// null-terminated C strings with the `"{name}={value}"` format.
15     map: HashMap<Vec<u8>, Pointer<Tag>>,
16 }
17
18 impl EnvVars {
19     pub(crate) fn init<'mir, 'tcx>(
20         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
21         mut excluded_env_vars: Vec<String>,
22     ) {
23
24         // FIXME: this can be removed when we have the `stat64` shim for macos.
25         if ecx.tcx.sess.target.target.target_os.to_lowercase() != "linux" {
26             // Exclude `TERM` var to avoid terminfo trying to open the termcap file.
27             excluded_env_vars.push("TERM".to_owned());
28         }
29
30         if ecx.machine.communicate {
31             for (name, value) in env::vars() {
32                 if !excluded_env_vars.contains(&name) {
33                     let var_ptr =
34                         alloc_env_var(name.as_bytes(), value.as_bytes(), &mut ecx.memory);
35                     ecx.machine.env_vars.map.insert(name.into_bytes(), var_ptr);
36                 }
37             }
38         }
39     }
40 }
41
42 fn alloc_env_var<'mir, 'tcx>(
43     name: &[u8],
44     value: &[u8],
45     memory: &mut Memory<'mir, 'tcx, Evaluator<'tcx>>,
46 ) -> Pointer<Tag> {
47     let mut bytes = name.to_vec();
48     bytes.push(b'=');
49     bytes.extend_from_slice(value);
50     bytes.push(0);
51     memory.allocate_static_bytes(bytes.as_slice(), MiriMemoryKind::Env.into())
52 }
53
54 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
55 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
56     fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
57         let this = self.eval_context_mut();
58
59         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
60         let name = this.memory.read_c_str(name_ptr)?;
61         Ok(match this.machine.env_vars.map.get(name) {
62             // The offset is used to strip the "{name}=" part of the string.
63             Some(var_ptr) => {
64                 Scalar::from(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?)
65             }
66             None => Scalar::ptr_null(&*this.tcx),
67         })
68     }
69
70     fn setenv(
71         &mut self,
72         name_op: OpTy<'tcx, Tag>,
73         value_op: OpTy<'tcx, Tag>,
74     ) -> InterpResult<'tcx, i32> {
75         let this = self.eval_context_mut();
76
77         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
78         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
79         let value = this.memory.read_c_str(value_ptr)?;
80         let mut new = None;
81         if !this.is_null(name_ptr)? {
82             let name = this.memory.read_c_str(name_ptr)?;
83             if !name.is_empty() && !name.contains(&b'=') {
84                 new = Some((name.to_owned(), value.to_owned()));
85             }
86         }
87         if let Some((name, value)) = new {
88             let var_ptr = alloc_env_var(&name, &value, &mut this.memory);
89             if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), var_ptr) {
90                 this.memory
91                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
92             }
93             Ok(0)
94         } else {
95             Ok(-1)
96         }
97     }
98
99     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
100         let this = self.eval_context_mut();
101
102         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
103         let mut success = None;
104         if !this.is_null(name_ptr)? {
105             let name = this.memory.read_c_str(name_ptr)?.to_owned();
106             if !name.is_empty() && !name.contains(&b'=') {
107                 success = Some(this.machine.env_vars.map.remove(&name));
108             }
109         }
110         if let Some(old) = success {
111             if let Some(var) = old {
112                 this.memory
113                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
114             }
115             Ok(0)
116         } else {
117             Ok(-1)
118         }
119     }
120
121     fn getcwd(
122         &mut self,
123         buf_op: OpTy<'tcx, Tag>,
124         size_op: OpTy<'tcx, Tag>,
125     ) -> InterpResult<'tcx, Scalar<Tag>> {
126         let this = self.eval_context_mut();
127
128         this.check_no_isolation("getcwd")?;
129
130         let buf = this.read_scalar(buf_op)?.not_undef()?;
131         let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
132         // If we cannot get the current directory, we return null
133         match env::current_dir() {
134             Ok(cwd) => {
135                 if this.write_os_str_to_c_str(&OsString::from(cwd), buf, size)? {
136                     return Ok(buf);
137                 }
138                 let erange = this.eval_libc("ERANGE")?;
139                 this.set_last_error(erange)?;
140             }
141             Err(e) => this.set_last_error_from_io_error(e)?,
142         }
143         Ok(Scalar::ptr_null(&*this.tcx))
144     }
145
146     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
147         let this = self.eval_context_mut();
148
149         this.check_no_isolation("chdir")?;
150
151         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
152
153         match env::set_current_dir(path) {
154             Ok(()) => Ok(0),
155             Err(e) => {
156                 this.set_last_error_from_io_error(e)?;
157                 Ok(-1)
158             }
159         }
160     }
161 }