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