miri/shims/unix/
env.rs

1use std::ffi::{OsStr, OsString};
2use std::io::ErrorKind;
3use std::{env, mem};
4
5use rustc_abi::{FieldIdx, Size};
6use rustc_data_structures::fx::FxHashMap;
7use rustc_index::IndexVec;
8use rustc_middle::ty::Ty;
9use rustc_middle::ty::layout::LayoutOf;
10
11use crate::*;
12
13pub struct UnixEnvVars<'tcx> {
14    /// Stores pointers to the environment variables. These variables must be stored as
15    /// null-terminated target strings (c_str or wide_str) with the `"{name}={value}"` format.
16    map: FxHashMap<OsString, Pointer>,
17
18    /// Place where the `environ` static is stored. Lazily initialized, but then never changes.
19    environ: MPlaceTy<'tcx>,
20}
21
22impl VisitProvenance for UnixEnvVars<'_> {
23    fn visit_provenance(&self, visit: &mut VisitWith<'_>) {
24        let UnixEnvVars { map, environ } = self;
25
26        environ.visit_provenance(visit);
27        for ptr in map.values() {
28            ptr.visit_provenance(visit);
29        }
30    }
31}
32
33impl<'tcx> UnixEnvVars<'tcx> {
34    pub(crate) fn new(
35        ecx: &mut InterpCx<'tcx, MiriMachine<'tcx>>,
36        env_vars: FxHashMap<OsString, OsString>,
37    ) -> InterpResult<'tcx, Self> {
38        // Allocate memory for all these env vars.
39        let mut env_vars_machine = FxHashMap::default();
40        for (name, val) in env_vars.into_iter() {
41            let ptr = alloc_env_var(ecx, &name, &val)?;
42            env_vars_machine.insert(name, ptr);
43        }
44
45        // This is memory backing an extern static, hence `ExternStatic`, not `Env`.
46        let layout = ecx.machine.layouts.mut_raw_ptr;
47        let environ = ecx.allocate(layout, MiriMemoryKind::ExternStatic.into())?;
48        let environ_block = alloc_environ_block(ecx, env_vars_machine.values().copied().collect())?;
49        ecx.write_pointer(environ_block, &environ)?;
50
51        interp_ok(UnixEnvVars { map: env_vars_machine, environ })
52    }
53
54    pub(crate) fn cleanup(ecx: &mut InterpCx<'tcx, MiriMachine<'tcx>>) -> InterpResult<'tcx> {
55        // Deallocate individual env vars.
56        let env_vars = mem::take(&mut ecx.machine.env_vars.unix_mut().map);
57        for (_name, ptr) in env_vars {
58            ecx.deallocate_ptr(ptr, None, MiriMemoryKind::Runtime.into())?;
59        }
60        // Deallocate environ var list.
61        let environ = &ecx.machine.env_vars.unix().environ;
62        let old_vars_ptr = ecx.read_pointer(environ)?;
63        ecx.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
64
65        interp_ok(())
66    }
67
68    pub(crate) fn environ(&self) -> Pointer {
69        self.environ.ptr()
70    }
71
72    fn get_ptr(
73        &self,
74        ecx: &InterpCx<'tcx, MiriMachine<'tcx>>,
75        name: &OsStr,
76    ) -> InterpResult<'tcx, Option<Pointer>> {
77        // We don't care about the value as we have the `map` to keep track of everything,
78        // but we do want to do this read so it shows up as a data race.
79        let _vars_ptr = ecx.read_pointer(&self.environ)?;
80        let Some(var_ptr) = self.map.get(name) else {
81            return interp_ok(None);
82        };
83        // The offset is used to strip the "{name}=" part of the string.
84        let var_ptr = var_ptr.wrapping_offset(
85            Size::from_bytes(u64::try_from(name.len()).unwrap().strict_add(1)),
86            ecx,
87        );
88        interp_ok(Some(var_ptr))
89    }
90
91    /// Implementation detail for [`InterpCx::get_env_var`]. This basically does `getenv`, complete
92    /// with the reads of the environment, but returns an [`OsString`] instead of a pointer.
93    pub(crate) fn get(
94        &self,
95        ecx: &InterpCx<'tcx, MiriMachine<'tcx>>,
96        name: &OsStr,
97    ) -> InterpResult<'tcx, Option<OsString>> {
98        let var_ptr = self.get_ptr(ecx, name)?;
99        if let Some(ptr) = var_ptr {
100            let var = ecx.read_os_str_from_c_str(ptr)?;
101            interp_ok(Some(var.to_owned()))
102        } else {
103            interp_ok(None)
104        }
105    }
106}
107
108fn alloc_env_var<'tcx>(
109    ecx: &mut InterpCx<'tcx, MiriMachine<'tcx>>,
110    name: &OsStr,
111    value: &OsStr,
112) -> InterpResult<'tcx, Pointer> {
113    let mut name_osstring = name.to_os_string();
114    name_osstring.push("=");
115    name_osstring.push(value);
116    ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Runtime.into())
117}
118
119/// Allocates an `environ` block with the given list of pointers.
120fn alloc_environ_block<'tcx>(
121    ecx: &mut InterpCx<'tcx, MiriMachine<'tcx>>,
122    mut vars: IndexVec<FieldIdx, Pointer>,
123) -> InterpResult<'tcx, Pointer> {
124    // Add trailing null.
125    vars.push(Pointer::null());
126    // Make an array with all these pointers inside Miri.
127    let vars_layout = ecx.layout_of(Ty::new_array(
128        *ecx.tcx,
129        ecx.machine.layouts.mut_raw_ptr.ty,
130        u64::try_from(vars.len()).unwrap(),
131    ))?;
132    let vars_place = ecx.allocate(vars_layout, MiriMemoryKind::Runtime.into())?;
133    for (idx, var) in vars.into_iter_enumerated() {
134        let place = ecx.project_field(&vars_place, idx)?;
135        ecx.write_pointer(var, &place)?;
136    }
137    interp_ok(vars_place.ptr())
138}
139
140impl<'tcx> EvalContextExt<'tcx> for crate::MiriInterpCx<'tcx> {}
141pub trait EvalContextExt<'tcx>: crate::MiriInterpCxExt<'tcx> {
142    fn getenv(&mut self, name_op: &OpTy<'tcx>) -> InterpResult<'tcx, Pointer> {
143        let this = self.eval_context_mut();
144        this.assert_target_os_is_unix("getenv");
145
146        let name_ptr = this.read_pointer(name_op)?;
147        let name = this.read_os_str_from_c_str(name_ptr)?;
148
149        let var_ptr = this.machine.env_vars.unix().get_ptr(this, name)?;
150        interp_ok(var_ptr.unwrap_or_else(Pointer::null))
151    }
152
153    fn setenv(
154        &mut self,
155        name_op: &OpTy<'tcx>,
156        value_op: &OpTy<'tcx>,
157    ) -> InterpResult<'tcx, Scalar> {
158        let this = self.eval_context_mut();
159        this.assert_target_os_is_unix("setenv");
160
161        let name_ptr = this.read_pointer(name_op)?;
162        let value_ptr = this.read_pointer(value_op)?;
163
164        let mut new = None;
165        if !this.ptr_is_null(name_ptr)? {
166            let name = this.read_os_str_from_c_str(name_ptr)?;
167            if !name.is_empty() && !name.to_string_lossy().contains('=') {
168                let value = this.read_os_str_from_c_str(value_ptr)?;
169                new = Some((name.to_owned(), value.to_owned()));
170            }
171        }
172        if let Some((name, value)) = new {
173            let var_ptr = alloc_env_var(this, &name, &value)?;
174            if let Some(var) = this.machine.env_vars.unix_mut().map.insert(name, var_ptr) {
175                this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
176            }
177            this.update_environ()?;
178            interp_ok(Scalar::from_i32(0)) // return zero on success
179        } else {
180            // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
181            this.set_last_error_and_return_i32(LibcError("EINVAL"))
182        }
183    }
184
185    fn unsetenv(&mut self, name_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
186        let this = self.eval_context_mut();
187        this.assert_target_os_is_unix("unsetenv");
188
189        let name_ptr = this.read_pointer(name_op)?;
190        let mut success = None;
191        if !this.ptr_is_null(name_ptr)? {
192            let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
193            if !name.is_empty() && !name.to_string_lossy().contains('=') {
194                success = Some(this.machine.env_vars.unix_mut().map.remove(&name));
195            }
196        }
197        if let Some(old) = success {
198            if let Some(var) = old {
199                this.deallocate_ptr(var, None, MiriMemoryKind::Runtime.into())?;
200            }
201            this.update_environ()?;
202            interp_ok(Scalar::from_i32(0))
203        } else {
204            // name argument is a null pointer, points to an empty string, or points to a string containing an '=' character.
205            this.set_last_error_and_return_i32(LibcError("EINVAL"))
206        }
207    }
208
209    fn getcwd(&mut self, buf_op: &OpTy<'tcx>, size_op: &OpTy<'tcx>) -> InterpResult<'tcx, Pointer> {
210        let this = self.eval_context_mut();
211        this.assert_target_os_is_unix("getcwd");
212
213        let buf = this.read_pointer(buf_op)?;
214        let size = this.read_target_usize(size_op)?;
215
216        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
217            this.reject_in_isolation("`getcwd`", reject_with)?;
218            this.set_last_error(ErrorKind::PermissionDenied)?;
219            return interp_ok(Pointer::null());
220        }
221
222        // If we cannot get the current directory, we return null
223        match env::current_dir() {
224            Ok(cwd) => {
225                if this.write_path_to_c_str(&cwd, buf, size)?.0 {
226                    return interp_ok(buf);
227                }
228                this.set_last_error(LibcError("ERANGE"))?;
229            }
230            Err(e) => this.set_last_error(e)?,
231        }
232
233        interp_ok(Pointer::null())
234    }
235
236    fn chdir(&mut self, path_op: &OpTy<'tcx>) -> InterpResult<'tcx, Scalar> {
237        let this = self.eval_context_mut();
238        this.assert_target_os_is_unix("chdir");
239
240        let path = this.read_path_from_c_str(this.read_pointer(path_op)?)?;
241
242        if let IsolatedOp::Reject(reject_with) = this.machine.isolated_op {
243            this.reject_in_isolation("`chdir`", reject_with)?;
244            return this.set_last_error_and_return_i32(ErrorKind::PermissionDenied);
245        }
246
247        let result = env::set_current_dir(path).map(|()| 0);
248        interp_ok(Scalar::from_i32(this.try_unwrap_io_result(result)?))
249    }
250
251    /// Updates the `environ` static.
252    fn update_environ(&mut self) -> InterpResult<'tcx> {
253        let this = self.eval_context_mut();
254        // Deallocate the old environ list.
255        let environ = this.machine.env_vars.unix().environ.clone();
256        let old_vars_ptr = this.read_pointer(&environ)?;
257        this.deallocate_ptr(old_vars_ptr, None, MiriMemoryKind::Runtime.into())?;
258
259        // Write the new list.
260        let vals = this.machine.env_vars.unix().map.values().copied().collect();
261        let environ_block = alloc_environ_block(this, vals)?;
262        this.write_pointer(environ_block, &environ)?;
263
264        interp_ok(())
265    }
266
267    fn getpid(&mut self) -> InterpResult<'tcx, Scalar> {
268        let this = self.eval_context_mut();
269        this.assert_target_os_is_unix("getpid");
270
271        // The reason we need to do this wacky of a conversion is because
272        // `libc::getpid` returns an i32, however, `std::process::id()` return an u32.
273        // So we un-do the conversion that stdlib does and turn it back into an i32.
274        // In `Scalar` representation, these are the same, so we don't need to anything else.
275        interp_ok(Scalar::from_u32(this.get_pid()))
276    }
277
278    fn linux_gettid(&mut self) -> InterpResult<'tcx, Scalar> {
279        let this = self.eval_context_ref();
280        this.assert_target_os("linux", "gettid");
281
282        let index = this.machine.threads.active_thread().to_u32();
283
284        // Compute a TID for this thread, ensuring that the main thread has PID == TID.
285        let tid = this.get_pid().strict_add(index);
286
287        interp_ok(Scalar::from_u32(tid))
288    }
289}