]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
Change error handling style for consistency
[rust.git] / src / shims / env.rs
1 use std::collections::HashMap;
2 use std::env;
3 use std::path::Path;
4
5 use crate::stacked_borrows::Tag;
6 use crate::*;
7 use rustc::ty::layout::Size;
8 use rustc_mir::interpret::{Memory, Pointer};
9
10 #[derive(Default)]
11 pub struct EnvVars {
12     /// Stores pointers to the environment variables. These variables must be stored as
13     /// null-terminated C strings with the `"{name}={value}"` format.
14     map: HashMap<Vec<u8>, Pointer<Tag>>,
15 }
16
17 impl EnvVars {
18     pub(crate) fn init<'mir, 'tcx>(
19         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
20         mut excluded_env_vars: Vec<String>,
21     ) {
22         // Exclude `TERM` var to avoid terminfo trying to open the termcap file.
23         excluded_env_vars.push("TERM".to_owned());
24
25         if ecx.machine.communicate {
26             for (name, value) in env::vars() {
27                 if !excluded_env_vars.contains(&name) {
28                     let var_ptr =
29                         alloc_env_var(name.as_bytes(), value.as_bytes(), ecx.memory_mut());
30                     ecx.machine.env_vars.map.insert(name.into_bytes(), var_ptr);
31                 }
32             }
33         }
34     }
35 }
36
37 fn alloc_env_var<'mir, 'tcx>(
38     name: &[u8],
39     value: &[u8],
40     memory: &mut Memory<'mir, 'tcx, Evaluator<'tcx>>,
41 ) -> Pointer<Tag> {
42     let mut bytes = name.to_vec();
43     bytes.push(b'=');
44     bytes.extend_from_slice(value);
45     bytes.push(0);
46     memory.allocate_static_bytes(bytes.as_slice(), MiriMemoryKind::Env.into())
47 }
48
49 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
50 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
51     fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
52         let this = self.eval_context_mut();
53
54         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
55         let name = this.memory().read_c_str(name_ptr)?;
56         Ok(match this.machine.env_vars.map.get(name) {
57             // The offset is used to strip the "{name}=" part of the string.
58             Some(var_ptr) => {
59                 Scalar::Ptr(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?)
60             }
61             None => Scalar::ptr_null(&*this.tcx),
62         })
63     }
64
65     fn setenv(
66         &mut self,
67         name_op: OpTy<'tcx, Tag>,
68         value_op: OpTy<'tcx, Tag>,
69     ) -> InterpResult<'tcx, i32> {
70         let this = self.eval_context_mut();
71
72         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
73         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
74         let value = this.memory().read_c_str(value_ptr)?;
75         let mut new = None;
76         if !this.is_null(name_ptr)? {
77             let name = this.memory().read_c_str(name_ptr)?;
78             if !name.is_empty() && !name.contains(&b'=') {
79                 new = Some((name.to_owned(), value.to_owned()));
80             }
81         }
82         if let Some((name, value)) = new {
83             let var_ptr = alloc_env_var(&name, &value, this.memory_mut());
84             if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), var_ptr) {
85                 this.memory_mut()
86                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
87             }
88             Ok(0)
89         } else {
90             Ok(-1)
91         }
92     }
93
94     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
95         let this = self.eval_context_mut();
96
97         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
98         let mut success = None;
99         if !this.is_null(name_ptr)? {
100             let name = this.memory().read_c_str(name_ptr)?.to_owned();
101             if !name.is_empty() && !name.contains(&b'=') {
102                 success = Some(this.machine.env_vars.map.remove(&name));
103             }
104         }
105         if let Some(old) = success {
106             if let Some(var) = old {
107                 this.memory_mut()
108                     .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
123         if !this.machine.communicate {
124             throw_unsup_format!("`getcwd` not available when isolation is enabled")
125         }
126
127         let tcx = &{ this.tcx.tcx };
128
129         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
130         let size = this.read_scalar(size_op)?.to_usize(&*tcx)?;
131         // If we cannot get the current directory, we return null
132         match env::current_dir() {
133             Ok(cwd) => {
134                 // It is not clear what happens with non-utf8 paths here
135                 let mut bytes = cwd.display().to_string().into_bytes();
136                 // If `size` is smaller or equal than the `bytes.len()`, writing `bytes` plus the
137                 // required null terminator to memory using the `buf` pointer would cause an
138                 // overflow. The desired behavior in this case is to return null.
139                 if (bytes.len() as u64) < size {
140                     // We add a `/0` terminator
141                     bytes.push(0);
142                     // This is ok because the buffer was strictly larger than `bytes`, so after
143                     // adding the null terminator, the buffer size is larger or equal to
144                     // `bytes.len()`, meaning that `bytes` actually fit inside tbe buffer.
145                     this.memory_mut()
146                         .get_mut(buf.alloc_id)?
147                         .write_bytes(tcx, buf, &bytes)?;
148                     return Ok(Scalar::Ptr(buf));
149                 }
150                 let erange = this.eval_libc("ERANGE")?;
151                 this.set_last_error(erange)?;
152             }
153             Err(e) => this.consume_io_error(e)?,
154         }
155         Ok(Scalar::ptr_null(&*tcx))
156     }
157
158     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
159         let this = self.eval_context_mut();
160
161         if !this.machine.communicate {
162             throw_unsup_format!("`chdir` not available when isolation is enabled")
163         }
164
165         let path_bytes = this
166             .memory()
167             .read_c_str(this.read_scalar(path_op)?.not_undef()?)?;
168
169         let path = Path::new(
170             std::str::from_utf8(path_bytes)
171                 .map_err(|_| err_unsup_format!("{:?} is not a valid utf-8 string", path_bytes))?,
172         );
173
174         match env::set_current_dir(path) {
175             Ok(()) => Ok(0),
176             Err(e) => {
177                 this.consume_io_error(e)?;
178                 Ok(-1)
179             }
180         }
181     }
182 }