Debian Codegraph @

third_party/rust/minidump-writer/src/linux/mem_reader.rs

raw
1 //! Functionality for reading a remote process's memory
2
3 use crate::{errors::CopyFromProcessError, ptrace_dumper::PtraceDumper, Pid};
4
5 enum Style {
6 /// Uses [`process_vm_readv`](https://linux.die.net/man/2/process_vm_readv)
7 /// to read the memory.
8 ///
9 /// This is not available on old <3.2 (really, ancient) kernels, and requires
10 /// the same permissions as ptrace
11 VirtualMem,
12 /// Reads the memory from `/proc/<pid>/mem`
13 ///
14 /// Available on basically all versions of Linux, but could fail if the process
15 /// has insufficient privileges, ie ptrace
16 File(std::fs::File),
17 /// Reads the memory with [ptrace (`PTRACE_PEEKDATA`)](https://man7.org/linux/man-pages/man2/ptrace.2.html)
18 ///
19 /// Reads data one word at a time, so slow, but fairly reliable, as long as
20 /// the process can be ptraced
21 Ptrace,
22 /// No methods succeeded, generally there isn't a case where failing a syscall
23 /// will work if called again
24 Unavailable {
25 vmem: nix::Error,
26 file: nix::Error,
27 ptrace: nix::Error,
28 },
29 }
30
31 pub struct MemReader {
32 /// The pid of the child to read
33 pid: nix::unistd::Pid,
34 style: Option<Style>,
35 }
36
37 impl std::fmt::Debug for MemReader {
38 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
39 let s = match &self.style {
40 Some(Style::VirtualMem) => "process_vm_readv",
41 Some(Style::File(_)) => "/proc/<pid>/mem",
42 Some(Style::Ptrace) => "PTRACE_PEEKDATA",
43 Some(Style::Unavailable { vmem, file, ptrace }) => {
44 return write!(
45 f,
46 "process_vm_readv: {vmem}, /proc/<pid>/mem: {file}, PTRACE_PEEKDATA: {ptrace}"
47 );
48 }
49 None => "unknown",
50 };
51
52 f.write_str(s)
53 }
54 }
55
56 impl MemReader {
57 /// Creates a [`Self`] for the specified process id, the method used will
58 /// be probed for on the first access
59 #[inline]
60 pub fn new(pid: i32) -> Self {
61 Self {
62 pid: nix::unistd::Pid::from_raw(pid),
63 style: None,
64 }
65 }
66
67 #[inline]
68 #[doc(hidden)]
69 pub fn for_virtual_mem(pid: i32) -> Self {
70 Self {
71 pid: nix::unistd::Pid::from_raw(pid),
72 style: Some(Style::VirtualMem),
73 }
74 }
75
76 #[inline]
77 #[doc(hidden)]
78 pub fn for_file(pid: i32) -> std::io::Result<Self> {
79 let file = std::fs::File::open(format!("/proc/{pid}/mem"))?;
80
81 Ok(Self {
82 pid: nix::unistd::Pid::from_raw(pid),
83 style: Some(Style::File(file)),
84 })
85 }
86
87 #[inline]
88 #[doc(hidden)]
89 pub fn for_ptrace(pid: i32) -> Self {
90 Self {
91 pid: nix::unistd::Pid::from_raw(pid),
92 style: Some(Style::Ptrace),
93 }
94 }
95
96 #[inline]
97 pub fn read_to_vec(
98 &mut self,
99 src: usize,
100 length: std::num::NonZeroUsize,
101 ) -> Result<Vec<u8>, CopyFromProcessError> {
102 let length = length.into();
103 let layout =
104 std::alloc::Layout::array::<u8>(length).map_err(|_err| CopyFromProcessError {
105 child: self.pid.as_raw(),
106 src,
107 offset: 0,
108 length,
109 source: nix::errno::Errno::EINVAL,
110 })?;
111
112 // SAFETY: we've guaranteed the layout we're allocating is valid at this point
113 let output = unsafe {
114 let ptr = std::alloc::alloc(layout);
115 if ptr.is_null() {
116 return Err(CopyFromProcessError {
117 child: self.pid.as_raw(),
118 src,
119 offset: 0,
120 length,
121 source: nix::errno::Errno::ENOMEM,
122 });
123 }
124 std::slice::from_raw_parts_mut(ptr, length)
125 };
126
127 match self.read(src, output) {
128 Ok(read) => {
129 // SAFETY: we've filled initialized read bytes of our allocation block
130 unsafe { Ok(Vec::from_raw_parts(output.as_mut_ptr(), read, length)) }
131 }
132 Err(err) => {
133 // SAFETY: the pointer and layout are the same we just allocated
134 unsafe {
135 std::alloc::dealloc(output.as_mut_ptr(), layout);
136 }
137 Err(err)
138 }
139 }
140 }
141
142 pub fn read(&mut self, src: usize, dst: &mut [u8]) -> Result<usize, CopyFromProcessError> {
143 if let Some(rs) = &mut self.style {
144 let res = match rs {
145 Style::VirtualMem => Self::vmem(self.pid, src, dst).map_err(|s| (s, 0)),
146 Style::File(file) => Self::file(file, src, dst).map_err(|s| (s, 0)),
147 Style::Ptrace => Self::ptrace(self.pid, src, dst),
148 Style::Unavailable { ptrace, .. } => Err((*ptrace, 0)),
149 };
150
151 return res.map_err(|(source, offset)| CopyFromProcessError {
152 child: self.pid.as_raw(),
153 src,
154 offset,
155 length: dst.len(),
156 source,
157 });
158 }
159
160 // Attempt to read in order of speed
161 let vmem = match Self::vmem(self.pid, src, dst) {
162 Ok(len) => {
163 self.style = Some(Style::VirtualMem);
164 return Ok(len);
165 }
166 Err(err) => err,
167 };
168
169 let file = match std::fs::File::open(format!("/proc/{}/mem", self.pid)) {
170 Ok(mut file) => match Self::file(&mut file, src, dst) {
171 Ok(len) => {
172 self.style = Some(Style::File(file));
173 return Ok(len);
174 }
175 Err(err) => err,
176 },
177 Err(err) => nix::Error::from_raw(err.raw_os_error().expect(
178 "failed to open /proc/<pid>/mem and the I/O error doesn't have an OS code",
179 )),
180 };
181
182 let ptrace = match Self::ptrace(self.pid, src, dst) {
183 Ok(len) => {
184 self.style = Some(Style::Ptrace);
185 return Ok(len);
186 }
187 Err((err, _)) => err,
188 };
189
190 self.style = Some(Style::Unavailable { vmem, file, ptrace });
191 Err(CopyFromProcessError {
192 child: self.pid.as_raw(),
193 src,
194 offset: 0,
195 length: dst.len(),
196 source: ptrace,
197 })
198 }
199
200 #[inline]
201 fn vmem(pid: nix::unistd::Pid, src: usize, dst: &mut [u8]) -> Result<usize, nix::Error> {
202 let remote = &[nix::sys::uio::RemoteIoVec {
203 base: src,
204 len: dst.len(),
205 }];
206 nix::sys::uio::process_vm_readv(pid, &mut [std::io::IoSliceMut::new(dst)], remote)
207 }
208
209 #[inline]
210 fn file(file: &mut std::fs::File, src: usize, dst: &mut [u8]) -> Result<usize, nix::Error> {
211 use std::os::unix::fs::FileExt;
212
213 file.read_exact_at(dst, src as u64).map_err(|err| {
214 if let Some(os) = err.raw_os_error() {
215 nix::Error::from_raw(os)
216 } else {
217 nix::Error::E2BIG /* EOF */
218 }
219 })?;
220
221 Ok(dst.len())
222 }
223
224 #[inline]
225 fn ptrace(
226 pid: nix::unistd::Pid,
227 src: usize,
228 dst: &mut [u8],
229 ) -> Result<usize, (nix::Error, usize)> {
230 let mut offset = 0;
231 let mut chunks = dst.chunks_exact_mut(std::mem::size_of::<usize>());
232
233 for chunk in chunks.by_ref() {
234 let word = nix::sys::ptrace::read(pid, (src + offset) as *mut std::ffi::c_void)
235 .map_err(|err| (err, offset))?;
236 chunk.copy_from_slice(&word.to_ne_bytes());
237 offset += std::mem::size_of::<usize>();
238 }
239
240 // I don't think there would ever be a case where we would not read on word boundaries, but just in case...
241 let last = chunks.into_remainder();
242 if !last.is_empty() {
243 let word = nix::sys::ptrace::read(pid, (src + offset) as *mut std::ffi::c_void)
244 .map_err(|err| (err, offset))?;
245 last.copy_from_slice(&word.to_ne_bytes()[..last.len()]);
246 }
247
248 Ok(dst.len())
249 }
250 }
251
252 impl PtraceDumper {
253 /// Copies a block of bytes from the target process, returning the heap
254 /// allocated copy
255 #[inline]
256 pub fn copy_from_process(
257 pid: Pid,
258 src: usize,
259 length: usize,
260 ) -> Result<Vec<u8>, crate::errors::DumperError> {
261 let length = std::num::NonZeroUsize::new(length).ok_or(
262 crate::errors::DumperError::CopyFromProcessError(CopyFromProcessError {
263 src,
264 child: pid,
265 offset: 0,
266 length,
267 // TODO: We should make copy_from_process also take a NonZero,
268 // as EINVAL could also come from the syscalls that actually read
269 // memory as well which could be confusing
270 source: nix::errno::Errno::EINVAL,
271 }),
272 )?;
273
274 let mut mem = MemReader::new(pid);
275 Ok(mem.read_to_vec(src, length)?)
276 }
277 }