]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
7c6b6c942e5e3aee470015f4726177aa441c65cd
[rust.git] / src / shims / env.rs
1 use std::ffi::{OsString, OsStr};
2 use std::env;
3
4 use crate::stacked_borrows::Tag;
5 use crate::rustc_target::abi::LayoutOf;
6 use crate::*;
7
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc::ty::layout::Size;
10 use rustc_mir::interpret::Pointer;
11
12 #[derive(Default)]
13 pub struct EnvVars<'tcx> {
14     /// Stores pointers to the environment variables. These variables must be stored as
15     /// null-terminated C strings with the `"{name}={value}"` format.
16     map: FxHashMap<OsString, Pointer<Tag>>,
17
18     /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
19     pub(crate) environ: Option<MPlaceTy<'tcx, Tag>>,
20 }
21
22 impl<'tcx> EnvVars<'tcx> {
23     pub(crate) fn init<'mir>(
24         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
25         excluded_env_vars: Vec<String>,
26     ) -> InterpResult<'tcx> {
27         if ecx.machine.communicate {
28             for (name, value) in env::vars() {
29                 if !excluded_env_vars.contains(&name) {
30                     let var_ptr =
31                         alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx);
32                     ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
33                 }
34             }
35         }
36         ecx.update_environ()
37     }
38 }
39
40 fn alloc_env_var_as_c_str<'mir, 'tcx>(
41     name: &OsStr,
42     value: &OsStr,
43     ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
44 ) -> Pointer<Tag> {
45     let mut name_osstring = name.to_os_string();
46     name_osstring.push("=");
47     name_osstring.push(value);
48     ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Machine.into())
49 }
50
51 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
52 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
53     fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
54         let this = self.eval_context_mut();
55
56         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
57         let name = this.read_os_str_from_c_str(name_ptr)?;
58         Ok(match this.machine.env_vars.map.get(name) {
59             // The offset is used to strip the "{name}=" part of the string.
60             Some(var_ptr) => {
61                 Scalar::from(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?)
62             }
63             None => Scalar::ptr_null(&*this.tcx),
64         })
65     }
66
67     fn setenv(
68         &mut self,
69         name_op: OpTy<'tcx, Tag>,
70         value_op: OpTy<'tcx, Tag>,
71     ) -> InterpResult<'tcx, i32> {
72         let mut this = self.eval_context_mut();
73
74         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
75         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
76         let value = this.read_os_str_from_c_str(value_ptr)?;
77         let mut new = None;
78         if !this.is_null(name_ptr)? {
79             let name = this.read_os_str_from_c_str(name_ptr)?;
80             if !name.is_empty() && !name.to_string_lossy().contains('=') {
81                 new = Some((name.to_owned(), value.to_owned()));
82             }
83         }
84         if let Some((name, value)) = new {
85             let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this);
86             if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), var_ptr) {
87                 this.memory
88                     .deallocate(var, None, MiriMemoryKind::Machine.into())?;
89             }
90             this.update_environ()?;
91             Ok(0)
92         } else {
93             Ok(-1)
94         }
95     }
96
97     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
98         let this = self.eval_context_mut();
99
100         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
101         let mut success = None;
102         if !this.is_null(name_ptr)? {
103             let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
104             if !name.is_empty() && !name.to_string_lossy().contains('=') {
105                 success = Some(this.machine.env_vars.map.remove(&name));
106             }
107         }
108         if let Some(old) = success {
109             if let Some(var) = old {
110                 this.memory
111                     .deallocate(var, None, MiriMemoryKind::Machine.into())?;
112             }
113             this.update_environ()?;
114             Ok(0)
115         } else {
116             Ok(-1)
117         }
118     }
119
120     fn getcwd(
121         &mut self,
122         buf_op: OpTy<'tcx, Tag>,
123         size_op: OpTy<'tcx, Tag>,
124     ) -> InterpResult<'tcx, Scalar<Tag>> {
125         let this = self.eval_context_mut();
126
127         this.check_no_isolation("getcwd")?;
128
129         let buf = this.read_scalar(buf_op)?.not_undef()?;
130         let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
131         // If we cannot get the current directory, we return null
132         match env::current_dir() {
133             Ok(cwd) => {
134                 if this.write_os_str_to_c_str(&OsString::from(cwd), buf, size)?.0 {
135                     return Ok(buf);
136                 }
137                 let erange = this.eval_libc("ERANGE")?;
138                 this.set_last_error(erange)?;
139             }
140             Err(e) => this.set_last_error_from_io_error(e)?,
141         }
142         Ok(Scalar::ptr_null(&*this.tcx))
143     }
144
145     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
146         let this = self.eval_context_mut();
147
148         this.check_no_isolation("chdir")?;
149
150         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
151
152         match env::set_current_dir(path) {
153             Ok(()) => Ok(0),
154             Err(e) => {
155                 this.set_last_error_from_io_error(e)?;
156                 Ok(-1)
157             }
158         }
159     }
160
161     /// Updates the `environ` static.
162     /// The first time it gets called, also initializes `extra.environ`.
163     fn update_environ(&mut self) -> InterpResult<'tcx> {
164         let this = self.eval_context_mut();
165         // Deallocate the old environ value, if any.
166         if let Some(environ) = this.machine.env_vars.environ {
167             let old_vars_ptr = this.read_scalar(environ.into())?.not_undef()?;
168             this.memory.deallocate(this.force_ptr(old_vars_ptr)?, None, MiriMemoryKind::Machine.into())?;
169         } else {
170             // No `environ` allocated yet, let's do that.
171             let layout = this.layout_of(this.tcx.types.usize)?;
172             let place = this.allocate(layout, MiriMemoryKind::Machine.into());
173             this.write_scalar(Scalar::from_machine_usize(0, &*this.tcx), place.into())?;
174             this.machine.env_vars.environ = Some(place);
175         }
176
177         // Collect all the pointers to each variable in a vector.
178         let mut vars: Vec<Scalar<Tag>> = this.machine.env_vars.map.values().map(|&ptr| ptr.into()).collect();
179         // Add the trailing null pointer.
180         vars.push(Scalar::from_int(0, this.pointer_size()));
181         // Make an array with all these pointers inside Miri.
182         let tcx = this.tcx;
183         let vars_layout =
184             this.layout_of(tcx.mk_array(tcx.types.usize, vars.len() as u64))?;
185         let vars_place = this.allocate(vars_layout, MiriMemoryKind::Machine.into());
186         for (idx, var) in vars.into_iter().enumerate() {
187             let place = this.mplace_field(vars_place, idx as u64)?;
188             this.write_scalar(var, place.into())?;
189         }
190         this.write_scalar(
191             vars_place.ptr,
192             this.machine.env_vars.environ.unwrap().into(),
193         )?;
194
195         Ok(())
196     }
197 }