]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
Fix merge conflicts
[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         // Exclude `TERM` var to avoid terminfo trying to open the termcap file.
24         excluded_env_vars.push("TERM".to_owned());
25
26         if ecx.machine.communicate {
27             for (name, value) in env::vars() {
28                 if !excluded_env_vars.contains(&name) {
29                     let var_ptr =
30                         alloc_env_var(name.as_bytes(), value.as_bytes(), &mut ecx.memory);
31                     ecx.machine.env_vars.map.insert(name.into_bytes(), var_ptr);
32                 }
33             }
34         }
35     }
36 }
37
38 fn alloc_env_var<'mir, 'tcx>(
39     name: &[u8],
40     value: &[u8],
41     memory: &mut Memory<'mir, 'tcx, Evaluator<'tcx>>,
42 ) -> Pointer<Tag> {
43     let mut bytes = name.to_vec();
44     bytes.push(b'=');
45     bytes.extend_from_slice(value);
46     bytes.push(0);
47     memory.allocate_static_bytes(bytes.as_slice(), MiriMemoryKind::Env.into())
48 }
49
50 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
51 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
52     fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> 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) => {
60                 Scalar::Ptr(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?)
61             }
62             None => Scalar::ptr_null(&*this.tcx),
63         })
64     }
65
66     fn setenv(
67         &mut self,
68         name_op: OpTy<'tcx, Tag>,
69         value_op: OpTy<'tcx, Tag>,
70     ) -> InterpResult<'tcx, i32> {
71         let this = self.eval_context_mut();
72
73         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
74         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
75         let value = this.memory.read_c_str(value_ptr)?;
76         let mut new = None;
77         if !this.is_null(name_ptr)? {
78             let name = this.memory.read_c_str(name_ptr)?;
79             if !name.is_empty() && !name.contains(&b'=') {
80                 new = Some((name.to_owned(), value.to_owned()));
81             }
82         }
83         if let Some((name, value)) = new {
84             let var_ptr = alloc_env_var(&name, &value, &mut this.memory);
85             if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), var_ptr) {
86                 this.memory
87                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
88             }
89             Ok(0)
90         } else {
91             Ok(-1)
92         }
93     }
94
95     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> 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
109                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
110             }
111             Ok(0)
112         } else {
113             Ok(-1)
114         }
115     }
116
117     fn getcwd(
118         &mut self,
119         buf_op: OpTy<'tcx, Tag>,
120         size_op: OpTy<'tcx, Tag>,
121     ) -> InterpResult<'tcx, Scalar<Tag>> {
122         let this = self.eval_context_mut();
123
124         this.check_no_isolation("getcwd")?;
125
126         let buf = this.force_ptr(this.read_scalar(buf_op)?.not_undef()?)?;
127         let size = this.read_scalar(size_op)?.to_usize(&*this.tcx)?;
128         // If we cannot get the current directory, we return null
129         match env::current_dir() {
130             Ok(cwd) => {
131                 if this.write_os_str_to_c_string(&OsString::from(cwd), buf, size).is_ok() {
132                     return Ok(Scalar::Ptr(buf));
133                 }
134                 let erange = this.eval_libc("ERANGE")?;
135                 this.set_last_error(erange)?;
136             }
137             Err(e) => this.set_last_error_from_io_error(e)?,
138         }
139         Ok(Scalar::ptr_null(&*this.tcx))
140     }
141
142     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
143         let this = self.eval_context_mut();
144
145         this.check_no_isolation("chdir")?;
146
147         let path = this.read_os_string_from_c_string(this.read_scalar(path_op)?.not_undef()?)?;
148
149         match env::set_current_dir(path) {
150             Ok(()) => Ok(0),
151             Err(e) => {
152                 this.set_last_error_from_io_error(e)?;
153                 Ok(-1)
154             }
155         }
156     }
157 }