]> git.lizzy.rs Git - rust.git/blob - src/shims/env.rs
Return length from write_os_str_to_c_str
[rust.git] / src / shims / env.rs
1 use std::collections::HashMap;
2 use std::ffi::{OsString, OsStr};
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::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<OsString, Pointer<Tag>>,
16 }
17
18 impl EnvVars {
19     pub(crate) fn init<'mir, 'tcx>(
20         ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
21         excluded_env_vars: Vec<String>,
22     ) {
23         if ecx.machine.communicate {
24             for (name, value) in env::vars() {
25                 if !excluded_env_vars.contains(&name) {
26                     let var_ptr =
27                         alloc_env_var_as_c_str(name.as_ref(), value.as_ref(), ecx);
28                     ecx.machine.env_vars.map.insert(OsString::from(name), var_ptr);
29                 }
30             }
31         }
32     }
33 }
34
35 fn alloc_env_var_as_c_str<'mir, 'tcx>(
36     name: &OsStr,
37     value: &OsStr,
38     ecx: &mut InterpCx<'mir, 'tcx, Evaluator<'tcx>>,
39 ) -> Pointer<Tag> {
40     let mut name_osstring = name.to_os_string();
41     name_osstring.push("=");
42     name_osstring.push(value);
43     ecx.alloc_os_str_as_c_str(name_osstring.as_os_str(), MiriMemoryKind::Env.into())
44 }
45
46 impl<'mir, 'tcx> EvalContextExt<'mir, 'tcx> for crate::MiriEvalContext<'mir, 'tcx> {}
47 pub trait EvalContextExt<'mir, 'tcx: 'mir>: crate::MiriEvalContextExt<'mir, 'tcx> {
48     fn getenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, Scalar<Tag>> {
49         let this = self.eval_context_mut();
50
51         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
52         let name = this.read_os_str_from_c_str(name_ptr)?;
53         Ok(match this.machine.env_vars.map.get(name) {
54             // The offset is used to strip the "{name}=" part of the string.
55             Some(var_ptr) => {
56                 Scalar::from(var_ptr.offset(Size::from_bytes(name.len() as u64 + 1), this)?)
57             }
58             None => Scalar::ptr_null(&*this.tcx),
59         })
60     }
61
62     fn setenv(
63         &mut self,
64         name_op: OpTy<'tcx, Tag>,
65         value_op: OpTy<'tcx, Tag>,
66     ) -> InterpResult<'tcx, i32> {
67         let mut this = self.eval_context_mut();
68
69         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
70         let value_ptr = this.read_scalar(value_op)?.not_undef()?;
71         let value = this.read_os_str_from_c_str(value_ptr)?;
72         let mut new = None;
73         if !this.is_null(name_ptr)? {
74             let name = this.read_os_str_from_c_str(name_ptr)?;
75             if !name.is_empty() && !name.to_string_lossy().contains('=') {
76                 new = Some((name.to_owned(), value.to_owned()));
77             }
78         }
79         if let Some((name, value)) = new {
80             let var_ptr = alloc_env_var_as_c_str(&name, &value, &mut this);
81             if let Some(var) = this.machine.env_vars.map.insert(name.to_owned(), var_ptr) {
82                 this.memory
83                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
84             }
85             Ok(0)
86         } else {
87             Ok(-1)
88         }
89     }
90
91     fn unsetenv(&mut self, name_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
92         let this = self.eval_context_mut();
93
94         let name_ptr = this.read_scalar(name_op)?.not_undef()?;
95         let mut success = None;
96         if !this.is_null(name_ptr)? {
97             let name = this.read_os_str_from_c_str(name_ptr)?.to_owned();
98             if !name.is_empty() && !name.to_string_lossy().contains('=') {
99                 success = Some(this.machine.env_vars.map.remove(&name));
100             }
101         }
102         if let Some(old) = success {
103             if let Some(var) = old {
104                 this.memory
105                     .deallocate(var, None, MiriMemoryKind::Env.into())?;
106             }
107             Ok(0)
108         } else {
109             Ok(-1)
110         }
111     }
112
113     fn getcwd(
114         &mut self,
115         buf_op: OpTy<'tcx, Tag>,
116         size_op: OpTy<'tcx, Tag>,
117     ) -> InterpResult<'tcx, Scalar<Tag>> {
118         let this = self.eval_context_mut();
119
120         this.check_no_isolation("getcwd")?;
121
122         let buf = this.read_scalar(buf_op)?.not_undef()?;
123         let size = this.read_scalar(size_op)?.to_machine_usize(&*this.tcx)?;
124         // If we cannot get the current directory, we return null
125         match env::current_dir() {
126             Ok(cwd) => {
127                 if this.write_os_str_to_c_str(&OsString::from(cwd), buf, size)?.0 {
128                     return Ok(buf);
129                 }
130                 let erange = this.eval_libc("ERANGE")?;
131                 this.set_last_error(erange)?;
132             }
133             Err(e) => this.set_last_error_from_io_error(e)?,
134         }
135         Ok(Scalar::ptr_null(&*this.tcx))
136     }
137
138     fn chdir(&mut self, path_op: OpTy<'tcx, Tag>) -> InterpResult<'tcx, i32> {
139         let this = self.eval_context_mut();
140
141         this.check_no_isolation("chdir")?;
142
143         let path = this.read_os_str_from_c_str(this.read_scalar(path_op)?.not_undef()?)?;
144
145         match env::set_current_dir(path) {
146             Ok(()) => Ok(0),
147             Err(e) => {
148                 this.set_last_error_from_io_error(e)?;
149                 Ok(-1)
150             }
151         }
152     }
153 }