| 1 |
use { |
| 2 |
super::{ |
| 3 |
auxv::AuxvError, |
| 4 |
errors::{AndroidError, MapsReaderError}, |
| 5 |
serializers::*, |
| 6 |
}, |
| 7 |
crate::{ |
| 8 |
linux::{ |
| 9 |
auxv::AuxvDumpInfo, |
| 10 |
errors::{DumperError, ThreadInfoError}, |
| 11 |
maps_reader::MappingInfo, |
| 12 |
module_reader, |
| 13 |
thread_info::ThreadInfo, |
| 14 |
Pid, |
| 15 |
}, |
| 16 |
serializers::*, |
| 17 |
}, |
| 18 |
error_graph::{ErrorList, WriteErrorList}, |
| 19 |
failspot::failspot, |
| 20 |
nix::{ |
| 21 |
errno::Errno, |
| 22 |
sys::{ptrace, signal, wait}, |
| 23 |
}, |
| 24 |
procfs_core::{ |
| 25 |
process::{MMPermissions, ProcState, Stat}, |
| 26 |
FromRead, ProcError, |
| 27 |
}, |
| 28 |
std::{ |
| 29 |
ffi::OsString, |
| 30 |
path, |
| 31 |
result::Result, |
| 32 |
time::{Duration, Instant}, |
| 33 |
}, |
| 34 |
thiserror::Error, |
| 35 |
}; |
| 36 |
|
| 37 |
#[cfg(target_os = "android")] |
| 38 |
use crate::linux::android::late_process_mappings; |
| 39 |
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
| 40 |
use crate::thread_info; |
| 41 |
|
| 42 |
#[derive(Debug, Clone)] |
| 43 |
pub struct Thread { |
| 44 |
pub tid: Pid, |
| 45 |
pub name: Option<String>, |
| 46 |
} |
| 47 |
|
| 48 |
#[derive(Debug)] |
| 49 |
pub struct PtraceDumper { |
| 50 |
pub pid: Pid, |
| 51 |
threads_suspended: bool, |
| 52 |
pub threads: Vec<Thread>, |
| 53 |
pub auxv: AuxvDumpInfo, |
| 54 |
pub mappings: Vec<MappingInfo>, |
| 55 |
pub page_size: usize, |
| 56 |
} |
| 57 |
|
| 58 |
#[cfg(target_pointer_width = "32")] |
| 59 |
pub const AT_SYSINFO_EHDR: u32 = 33; |
| 60 |
#[cfg(target_pointer_width = "64")] |
| 61 |
pub const AT_SYSINFO_EHDR: u64 = 33; |
| 62 |
|
| 63 |
impl Drop for PtraceDumper { |
| 64 |
fn drop(&mut self) { |
| 65 |
// Always try to resume all threads (e.g. in case of error) |
| 66 |
self.resume_threads(error_graph::strategy::DontCare); |
| 67 |
// Always allow the process to continue. |
| 68 |
let _ = self.continue_process(); |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
#[derive(Debug, Error, serde::Serialize)] |
| 73 |
pub enum InitError { |
| 74 |
#[error("failed to read auxv")] |
| 75 |
ReadAuxvFailed(#[source] crate::auxv::AuxvError), |
| 76 |
#[error("IO error for file {0}")] |
| 77 |
IOError( |
| 78 |
String, |
| 79 |
#[source] |
| 80 |
#[serde(serialize_with = "serialize_io_error")] |
| 81 |
std::io::Error, |
| 82 |
), |
| 83 |
#[error("Failed Android specific late init")] |
| 84 |
AndroidLateInitError(#[from] AndroidError), |
| 85 |
#[error("Failed to read the page size")] |
| 86 |
PageSizeError( |
| 87 |
#[from] |
| 88 |
#[serde(serialize_with = "serialize_nix_error")] |
| 89 |
nix::Error, |
| 90 |
), |
| 91 |
#[error("Ptrace does not function within the same process")] |
| 92 |
CannotPtraceSameProcess, |
| 93 |
#[error("Failed to stop the target process")] |
| 94 |
StopProcessFailed(#[source] StopProcessError), |
| 95 |
#[error("Errors occurred while filling missing Auxv info")] |
| 96 |
FillMissingAuxvInfoErrors(#[source] ErrorList<AuxvError>), |
| 97 |
#[error("Failed filling missing Auxv info")] |
| 98 |
FillMissingAuxvInfoFailed(#[source] AuxvError), |
| 99 |
#[error("Failed reading proc/pid/task entry for process")] |
| 100 |
ReadProcessThreadEntryFailed( |
| 101 |
#[source] |
| 102 |
#[serde(serialize_with = "serialize_io_error")] |
| 103 |
std::io::Error, |
| 104 |
), |
| 105 |
#[error("Process task entry `{0:?}` could not be parsed as a TID")] |
| 106 |
ProcessTaskEntryNotTid(OsString), |
| 107 |
#[error("Failed to read thread name")] |
| 108 |
ReadThreadNameFailed( |
| 109 |
#[source] |
| 110 |
#[serde(serialize_with = "serialize_io_error")] |
| 111 |
std::io::Error, |
| 112 |
), |
| 113 |
#[error("Proc task directory `{0:?}` is not a directory")] |
| 114 |
ProcPidTaskNotDirectory(String), |
| 115 |
#[error("Errors while enumerating threads")] |
| 116 |
EnumerateThreadsErrors(#[source] ErrorList<InitError>), |
| 117 |
#[error("Failed to enumerate threads")] |
| 118 |
EnumerateThreadsFailed(#[source] Box<InitError>), |
| 119 |
#[error("Failed to read process map file")] |
| 120 |
ReadProcessMapFileFailed( |
| 121 |
#[source] |
| 122 |
#[serde(serialize_with = "serialize_proc_error")] |
| 123 |
ProcError, |
| 124 |
), |
| 125 |
#[error("Failed to aggregate process mappings")] |
| 126 |
AggregateMappingsFailed(#[source] MapsReaderError), |
| 127 |
#[error("Failed to enumerate process mappings")] |
| 128 |
EnumerateMappingsFailed(#[source] Box<InitError>), |
| 129 |
} |
| 130 |
|
| 131 |
#[derive(Debug, thiserror::Error, serde::Serialize)] |
| 132 |
pub enum StopProcessError { |
| 133 |
#[error("Failed to stop the process")] |
| 134 |
Stop( |
| 135 |
#[from] |
| 136 |
#[serde(serialize_with = "serialize_nix_error")] |
| 137 |
nix::Error, |
| 138 |
), |
| 139 |
#[error("Failed to get the process state")] |
| 140 |
State( |
| 141 |
#[from] |
| 142 |
#[serde(serialize_with = "serialize_proc_error")] |
| 143 |
ProcError, |
| 144 |
), |
| 145 |
#[error("Timeout waiting for process to stop")] |
| 146 |
Timeout, |
| 147 |
} |
| 148 |
|
| 149 |
#[derive(Debug, thiserror::Error)] |
| 150 |
pub enum ContinueProcessError { |
| 151 |
#[error("Failed to continue the process")] |
| 152 |
Continue(#[from] Errno), |
| 153 |
} |
| 154 |
|
| 155 |
/// PTRACE_DETACH the given pid. |
| 156 |
/// |
| 157 |
/// This handles special errno cases (ESRCH) which we won't consider errors. |
| 158 |
fn ptrace_detach(child: Pid) -> Result<(), DumperError> { |
| 159 |
let pid = nix::unistd::Pid::from_raw(child); |
| 160 |
ptrace::detach(pid, None).or_else(|e| { |
| 161 |
// errno is set to ESRCH if the pid no longer exists, but we don't want to error in that |
| 162 |
// case. |
| 163 |
if e == nix::Error::ESRCH { |
| 164 |
Ok(()) |
| 165 |
} else { |
| 166 |
Err(DumperError::PtraceDetachError(child, e)) |
| 167 |
} |
| 168 |
}) |
| 169 |
} |
| 170 |
|
| 171 |
impl PtraceDumper { |
| 172 |
/// Constructs a dumper for extracting information from the specified process id |
| 173 |
pub fn new_report_soft_errors( |
| 174 |
pid: Pid, |
| 175 |
stop_timeout: Duration, |
| 176 |
auxv: AuxvDumpInfo, |
| 177 |
soft_errors: impl WriteErrorList<InitError>, |
| 178 |
) -> Result<Self, InitError> { |
| 179 |
if pid == std::process::id() as i32 { |
| 180 |
return Err(InitError::CannotPtraceSameProcess); |
| 181 |
} |
| 182 |
|
| 183 |
let mut dumper = Self { |
| 184 |
pid, |
| 185 |
threads_suspended: false, |
| 186 |
threads: Vec::new(), |
| 187 |
auxv, |
| 188 |
mappings: Vec::new(), |
| 189 |
page_size: 0, |
| 190 |
}; |
| 191 |
dumper.init(stop_timeout, soft_errors)?; |
| 192 |
Ok(dumper) |
| 193 |
} |
| 194 |
|
| 195 |
// TODO: late_init for chromeos and android |
| 196 |
pub fn init( |
| 197 |
&mut self, |
| 198 |
stop_timeout: Duration, |
| 199 |
mut soft_errors: impl WriteErrorList<InitError>, |
| 200 |
) -> Result<(), InitError> { |
| 201 |
// Stopping the process is best-effort. |
| 202 |
if let Err(e) = self.stop_process(stop_timeout) { |
| 203 |
soft_errors.push(InitError::StopProcessFailed(e)); |
| 204 |
} |
| 205 |
|
| 206 |
// Even if we completely fail to fill in any additional Auxv info, we can still press |
| 207 |
// forward. |
| 208 |
if let Err(e) = self.auxv.try_filling_missing_info( |
| 209 |
self.pid, |
| 210 |
soft_errors.subwriter(InitError::FillMissingAuxvInfoErrors), |
| 211 |
) { |
| 212 |
soft_errors.push(InitError::FillMissingAuxvInfoFailed(e)); |
| 213 |
} |
| 214 |
|
| 215 |
// If we completely fail to enumerate any threads... Some information is still better than |
| 216 |
// no information! |
| 217 |
if let Err(e) = |
| 218 |
self.enumerate_threads(soft_errors.subwriter(InitError::EnumerateThreadsErrors)) |
| 219 |
{ |
| 220 |
soft_errors.push(InitError::EnumerateThreadsFailed(Box::new(e))); |
| 221 |
} |
| 222 |
|
| 223 |
// Same with mappings -- Some information is still better than no information! |
| 224 |
if let Err(e) = self.enumerate_mappings() { |
| 225 |
soft_errors.push(InitError::EnumerateMappingsFailed(Box::new(e))); |
| 226 |
} |
| 227 |
|
| 228 |
self.page_size = nix::unistd::sysconf(nix::unistd::SysconfVar::PAGE_SIZE)? |
| 229 |
.expect("page size apparently unlimited: doesn't make sense.") |
| 230 |
as usize; |
| 231 |
|
| 232 |
Ok(()) |
| 233 |
} |
| 234 |
|
| 235 |
#[cfg_attr(not(target_os = "android"), allow(clippy::unused_self))] |
| 236 |
pub fn late_init(&mut self) -> Result<(), InitError> { |
| 237 |
#[cfg(target_os = "android")] |
| 238 |
{ |
| 239 |
late_process_mappings(self.pid, &mut self.mappings)?; |
| 240 |
} |
| 241 |
Ok(()) |
| 242 |
} |
| 243 |
|
| 244 |
/// Suspends a thread by attaching to it. |
| 245 |
pub fn suspend_thread(child: Pid) -> Result<(), DumperError> { |
| 246 |
use DumperError::PtraceAttachError as AttachErr; |
| 247 |
|
| 248 |
let pid = nix::unistd::Pid::from_raw(child); |
| 249 |
// This may fail if the thread has just died or debugged. |
| 250 |
ptrace::attach(pid).map_err(|e| AttachErr(child, e))?; |
| 251 |
loop { |
| 252 |
match wait::waitpid(pid, Some(wait::WaitPidFlag::__WALL)) { |
| 253 |
Ok(status) => { |
| 254 |
let wait::WaitStatus::Stopped(_, status) = status else { |
| 255 |
return Err(DumperError::WaitPidError( |
| 256 |
child, |
| 257 |
nix::errno::Errno::UnknownErrno, |
| 258 |
)); |
| 259 |
}; |
| 260 |
|
| 261 |
// Any signal will stop the thread, make sure it is SIGSTOP. Otherwise, this |
| 262 |
// signal will be delivered after PTRACE_DETACH, and the thread will enter |
| 263 |
// the "T (stopped)" state. |
| 264 |
if status == nix::sys::signal::SIGSTOP { |
| 265 |
break; |
| 266 |
} |
| 267 |
|
| 268 |
// Signals other than SIGSTOP that are received need to be reinjected, |
| 269 |
// or they will otherwise get lost. |
| 270 |
if let Err(err) = ptrace::cont(pid, status) { |
| 271 |
return Err(DumperError::WaitPidError(child, err)); |
| 272 |
} |
| 273 |
} |
| 274 |
Err(Errno::EINTR) => continue, |
| 275 |
Err(e) => { |
| 276 |
ptrace_detach(child)?; |
| 277 |
return Err(DumperError::WaitPidError(child, e)); |
| 278 |
} |
| 279 |
} |
| 280 |
} |
| 281 |
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] |
| 282 |
{ |
| 283 |
// On x86, the stack pointer is NULL or -1, when executing trusted code in |
| 284 |
// the seccomp sandbox. Not only does this cause difficulties down the line |
| 285 |
// when trying to dump the thread's stack, it also results in the minidumps |
| 286 |
// containing information about the trusted threads. This information is |
| 287 |
// generally completely meaningless and just pollutes the minidumps. |
| 288 |
// We thus test the stack pointer and exclude any threads that are part of |
| 289 |
// the seccomp sandbox's trusted code. |
| 290 |
let skip_thread; |
| 291 |
let regs = thread_info::ThreadInfo::getregs(pid.into()); |
| 292 |
if let Ok(regs) = regs { |
| 293 |
#[cfg(target_arch = "x86_64")] |
| 294 |
{ |
| 295 |
skip_thread = regs.rsp == 0; |
| 296 |
} |
| 297 |
#[cfg(target_arch = "x86")] |
| 298 |
{ |
| 299 |
skip_thread = regs.esp == 0; |
| 300 |
} |
| 301 |
} else { |
| 302 |
skip_thread = true; |
| 303 |
} |
| 304 |
if skip_thread { |
| 305 |
ptrace_detach(child)?; |
| 306 |
return Err(DumperError::DetachSkippedThread(child)); |
| 307 |
} |
| 308 |
} |
| 309 |
Ok(()) |
| 310 |
} |
| 311 |
|
| 312 |
/// Resumes a thread by detaching from it. |
| 313 |
pub fn resume_thread(child: Pid) -> Result<(), DumperError> { |
| 314 |
ptrace_detach(child) |
| 315 |
} |
| 316 |
|
| 317 |
pub fn suspend_threads(&mut self, mut soft_errors: impl WriteErrorList<DumperError>) { |
| 318 |
// Iterate over all threads and try to suspend them. |
| 319 |
// If the thread either disappeared before we could attach to it, or if |
| 320 |
// it was part of the seccomp sandbox's trusted code, it is OK to |
| 321 |
// silently drop it from the minidump. |
| 322 |
self.threads.retain(|x| match Self::suspend_thread(x.tid) { |
| 323 |
Ok(()) => true, |
| 324 |
Err(e) => { |
| 325 |
soft_errors.push(e); |
| 326 |
false |
| 327 |
} |
| 328 |
}); |
| 329 |
|
| 330 |
self.threads_suspended = true; |
| 331 |
|
| 332 |
failspot::failspot!(<crate::FailSpotName>::SuspendThreads soft_errors.push(DumperError::PtraceAttachError(1234, nix::Error::EPERM))) |
| 333 |
} |
| 334 |
|
| 335 |
pub fn resume_threads(&mut self, mut soft_errors: impl WriteErrorList<DumperError>) { |
| 336 |
if self.threads_suspended { |
| 337 |
for thread in &self.threads { |
| 338 |
match Self::resume_thread(thread.tid) { |
| 339 |
Ok(()) => (), |
| 340 |
Err(e) => { |
| 341 |
soft_errors.push(e); |
| 342 |
} |
| 343 |
} |
| 344 |
} |
| 345 |
} |
| 346 |
self.threads_suspended = false; |
| 347 |
} |
| 348 |
|
| 349 |
/// Send SIGSTOP to the process so that we can get a consistent state. |
| 350 |
/// |
| 351 |
/// This will block waiting for the process to stop until `timeout` has passed. |
| 352 |
fn stop_process(&mut self, timeout: Duration) -> Result<(), StopProcessError> { |
| 353 |
failspot!(StopProcess bail(nix::Error::EPERM)); |
| 354 |
|
| 355 |
signal::kill(nix::unistd::Pid::from_raw(self.pid), Some(signal::SIGSTOP))?; |
| 356 |
|
| 357 |
// Something like waitpid for non-child processes would be better, but we have no such |
| 358 |
// tool, so we poll the status. |
| 359 |
const POLL_INTERVAL: Duration = Duration::from_millis(1); |
| 360 |
let proc_file = format!("/proc/{}/stat", self.pid); |
| 361 |
let end = Instant::now() + timeout; |
| 362 |
|
| 363 |
loop { |
| 364 |
if let Ok(ProcState::Stopped) = Stat::from_file(&proc_file)?.state() { |
| 365 |
return Ok(()); |
| 366 |
} |
| 367 |
|
| 368 |
std::thread::sleep(POLL_INTERVAL); |
| 369 |
if Instant::now() > end { |
| 370 |
return Err(StopProcessError::Timeout); |
| 371 |
} |
| 372 |
} |
| 373 |
} |
| 374 |
|
| 375 |
/// Send SIGCONT to the process to continue. |
| 376 |
/// |
| 377 |
/// Unlike `stop_process`, this function does not wait for the process to continue. |
| 378 |
fn continue_process(&mut self) -> Result<(), ContinueProcessError> { |
| 379 |
signal::kill(nix::unistd::Pid::from_raw(self.pid), Some(signal::SIGCONT))?; |
| 380 |
Ok(()) |
| 381 |
} |
| 382 |
|
| 383 |
/// Parse /proc/$pid/task to list all the threads of the process identified by |
| 384 |
/// pid. |
| 385 |
fn enumerate_threads( |
| 386 |
&mut self, |
| 387 |
mut soft_errors: impl WriteErrorList<InitError>, |
| 388 |
) -> Result<(), InitError> { |
| 389 |
let pid = self.pid; |
| 390 |
let filename = format!("/proc/{}/task", pid); |
| 391 |
let task_path = path::PathBuf::from(&filename); |
| 392 |
if !task_path.is_dir() { |
| 393 |
return Err(InitError::ProcPidTaskNotDirectory(filename)); |
| 394 |
} |
| 395 |
|
| 396 |
for entry in std::fs::read_dir(task_path).map_err(|e| InitError::IOError(filename, e))? { |
| 397 |
let entry = match entry { |
| 398 |
Ok(entry) => entry, |
| 399 |
Err(e) => { |
| 400 |
soft_errors.push(InitError::ReadProcessThreadEntryFailed(e)); |
| 401 |
continue; |
| 402 |
} |
| 403 |
}; |
| 404 |
let file_name = entry.file_name(); |
| 405 |
let tid = match file_name.to_str().and_then(|name| name.parse::<Pid>().ok()) { |
| 406 |
Some(tid) => tid, |
| 407 |
None => { |
| 408 |
soft_errors.push(InitError::ProcessTaskEntryNotTid(file_name)); |
| 409 |
continue; |
| 410 |
} |
| 411 |
}; |
| 412 |
|
| 413 |
// Read the thread-name (if there is any) |
| 414 |
let name_result = failspot!(if ThreadName { |
| 415 |
Err(std::io::Error::other( |
| 416 |
"testing requested failure reading thread name", |
| 417 |
)) |
| 418 |
} else { |
| 419 |
std::fs::read_to_string(format!("/proc/{}/task/{}/comm", pid, tid)) |
| 420 |
}); |
| 421 |
|
| 422 |
let name = match name_result { |
| 423 |
Ok(name) => Some(name.trim_end().to_string()), |
| 424 |
Err(e) => { |
| 425 |
soft_errors.push(InitError::ReadThreadNameFailed(e)); |
| 426 |
None |
| 427 |
} |
| 428 |
}; |
| 429 |
|
| 430 |
self.threads.push(Thread { tid, name }); |
| 431 |
} |
| 432 |
|
| 433 |
Ok(()) |
| 434 |
} |
| 435 |
|
| 436 |
fn enumerate_mappings(&mut self) -> Result<(), InitError> { |
| 437 |
// linux_gate_loc is the beginning of the kernel's mapping of |
| 438 |
// linux-gate.so in the process. It doesn't actually show up in the |
| 439 |
// maps list as a filename, but it can be found using the AT_SYSINFO_EHDR |
| 440 |
// aux vector entry, which gives the information necessary to special |
| 441 |
// case its entry when creating the list of mappings. |
| 442 |
// See http://www.trilithium.com/johan/2005/08/linux-gate/ for more |
| 443 |
// information. |
| 444 |
let maps_path = format!("/proc/{}/maps", self.pid); |
| 445 |
let maps_file = |
| 446 |
std::fs::File::open(&maps_path).map_err(|e| InitError::IOError(maps_path, e))?; |
| 447 |
|
| 448 |
let maps = procfs_core::process::MemoryMaps::from_read(maps_file) |
| 449 |
.map_err(InitError::ReadProcessMapFileFailed)?; |
| 450 |
|
| 451 |
self.mappings = MappingInfo::aggregate(maps, self.auxv.get_linux_gate_address()) |
| 452 |
.map_err(InitError::AggregateMappingsFailed)?; |
| 453 |
|
| 454 |
// Although the initial executable is usually the first mapping, it's not |
| 455 |
// guaranteed (see http://crosbug.com/25355); therefore, try to use the |
| 456 |
// actual entry point to find the mapping. |
| 457 |
if let Some(entry_point_loc) = self |
| 458 |
.auxv |
| 459 |
.get_entry_address() |
| 460 |
.map(|u| usize::try_from(u).unwrap()) |
| 461 |
{ |
| 462 |
// If this module contains the entry-point, and it's not already the first |
| 463 |
// one, then we need to make it be first. This is because the minidump |
| 464 |
// format assumes the first module is the one that corresponds to the main |
| 465 |
// executable (as codified in |
| 466 |
// processor/minidump.cc:MinidumpModuleList::GetMainModule()). |
| 467 |
if let Some(entry_mapping_idx) = self.mappings.iter().position(|mapping| { |
| 468 |
(mapping.start_address..mapping.start_address + mapping.size) |
| 469 |
.contains(&entry_point_loc) |
| 470 |
}) { |
| 471 |
self.mappings.swap(0, entry_mapping_idx); |
| 472 |
} |
| 473 |
} |
| 474 |
Ok(()) |
| 475 |
} |
| 476 |
|
| 477 |
/// Read thread info from /proc/$pid/status. |
| 478 |
/// Fill out the |tgid|, |ppid| and |pid| members of |info|. If unavailable, |
| 479 |
/// these members are set to -1. Returns true if all three members are |
| 480 |
/// available. |
| 481 |
pub fn get_thread_info_by_index(&self, index: usize) -> Result<ThreadInfo, ThreadInfoError> { |
| 482 |
if index > self.threads.len() { |
| 483 |
return Err(ThreadInfoError::IndexOutOfBounds(index, self.threads.len())); |
| 484 |
} |
| 485 |
|
| 486 |
ThreadInfo::create(self.pid, self.threads[index].tid) |
| 487 |
} |
| 488 |
|
| 489 |
// Returns a valid stack pointer and the mapping that contains the stack. |
| 490 |
// The stack pointer will usually point within this mapping, but it might |
| 491 |
// not in case of stack overflows, hence the returned pointer might be |
| 492 |
// different from the one that was passed in. |
| 493 |
pub fn get_stack_info(&self, int_stack_pointer: usize) -> Result<(usize, usize), DumperError> { |
| 494 |
// Round the stack pointer to the nearest page, this will cause us to |
| 495 |
// capture data below the stack pointer which might still be relevant. |
| 496 |
let mut stack_pointer = int_stack_pointer & !(self.page_size - 1); |
| 497 |
let mut mapping = self.find_mapping(stack_pointer); |
| 498 |
|
| 499 |
// The guard page has been 1 MiB in size since kernel 4.12, older |
| 500 |
// kernels used a 4 KiB one instead. Note the saturating add, as 32-bit |
| 501 |
// processes can have a stack pointer within 1MiB of usize::MAX |
| 502 |
let guard_page_max_addr = stack_pointer.saturating_add(1024 * 1024); |
| 503 |
|
| 504 |
// If we found no mapping, or the mapping we found has no permissions |
| 505 |
// then we might have hit a guard page, try looking for a mapping in |
| 506 |
// addresses past the stack pointer. Stack grows towards lower addresses |
| 507 |
// on the platforms we care about so the stack should appear after the |
| 508 |
// guard page. |
| 509 |
while !Self::may_be_stack(mapping) && (stack_pointer <= guard_page_max_addr) { |
| 510 |
stack_pointer += self.page_size; |
| 511 |
mapping = self.find_mapping(stack_pointer); |
| 512 |
} |
| 513 |
|
| 514 |
mapping |
| 515 |
.map(|mapping| { |
| 516 |
let valid_stack_pointer = if mapping.contains_address(stack_pointer) { |
| 517 |
stack_pointer |
| 518 |
} else { |
| 519 |
mapping.start_address |
| 520 |
}; |
| 521 |
|
| 522 |
let stack_len = mapping.size - (valid_stack_pointer - mapping.start_address); |
| 523 |
(valid_stack_pointer, stack_len) |
| 524 |
}) |
| 525 |
.ok_or(DumperError::NoStackPointerMapping) |
| 526 |
} |
| 527 |
|
| 528 |
fn may_be_stack(mapping: Option<&MappingInfo>) -> bool { |
| 529 |
if let Some(mapping) = mapping { |
| 530 |
return mapping |
| 531 |
.permissions |
| 532 |
.intersects(MMPermissions::READ | MMPermissions::WRITE); |
| 533 |
} |
| 534 |
|
| 535 |
false |
| 536 |
} |
| 537 |
|
| 538 |
pub fn sanitize_stack_copy( |
| 539 |
&self, |
| 540 |
stack_copy: &mut [u8], |
| 541 |
stack_pointer: usize, |
| 542 |
sp_offset: usize, |
| 543 |
) -> Result<(), DumperError> { |
| 544 |
// We optimize the search for containing mappings in three ways: |
| 545 |
// 1) We expect that pointers into the stack mapping will be common, so |
| 546 |
// we cache that address range. |
| 547 |
// 2) The last referenced mapping is a reasonable predictor for the next |
| 548 |
// referenced mapping, so we test that first. |
| 549 |
// 3) We precompute a bitfield based upon bits 32:32-n of the start and |
| 550 |
// stop addresses, and use that to short circuit any values that can |
| 551 |
// not be pointers. (n=11) |
| 552 |
let defaced; |
| 553 |
#[cfg(target_pointer_width = "64")] |
| 554 |
{ |
| 555 |
defaced = 0x0defaced0defacedusize.to_ne_bytes(); |
| 556 |
} |
| 557 |
#[cfg(target_pointer_width = "32")] |
| 558 |
{ |
| 559 |
defaced = 0x0defacedusize.to_ne_bytes(); |
| 560 |
}; |
| 561 |
// the bitfield length is 2^test_bits long. |
| 562 |
let test_bits = 11; |
| 563 |
// byte length of the corresponding array. |
| 564 |
let array_size: usize = 1 << (test_bits - 3); |
| 565 |
let array_mask = array_size - 1; |
| 566 |
// The amount to right shift pointers by. This captures the top bits |
| 567 |
// on 32 bit architectures. On 64 bit architectures this would be |
| 568 |
// uninformative so we take the same range of bits. |
| 569 |
let shift = 32 - 11; |
| 570 |
// let MappingInfo* last_hit_mapping = nullptr; |
| 571 |
// let MappingInfo* hit_mapping = nullptr; |
| 572 |
let stack_mapping = self.find_mapping_no_bias(stack_pointer); |
| 573 |
let mut last_hit_mapping: Option<&MappingInfo> = None; |
| 574 |
// The magnitude below which integers are considered to be to be |
| 575 |
// 'small', and not constitute a PII risk. These are included to |
| 576 |
// avoid eliding useful register values. |
| 577 |
let small_int_magnitude: isize = 4096; |
| 578 |
|
| 579 |
let mut could_hit_mapping = vec![0; array_size]; |
| 580 |
// Initialize the bitfield such that if the (pointer >> shift)'th |
| 581 |
// bit, modulo the bitfield size, is not set then there does not |
| 582 |
// exist a mapping in mappings that would contain that pointer. |
| 583 |
for mapping in &self.mappings { |
| 584 |
if !mapping.is_executable() { |
| 585 |
continue; |
| 586 |
} |
| 587 |
// For each mapping, work out the (unmodulo'ed) range of bits to |
| 588 |
// set. |
| 589 |
let mut start = mapping.start_address; |
| 590 |
let mut end = start + mapping.size; |
| 591 |
start >>= shift; |
| 592 |
end >>= shift; |
| 593 |
for bit in start..=end { |
| 594 |
// Set each bit in the range, applying the modulus. |
| 595 |
could_hit_mapping[(bit >> 3) & array_mask] |= 1 << (bit & 7); |
| 596 |
} |
| 597 |
} |
| 598 |
|
| 599 |
// Zero memory that is below the current stack pointer. |
| 600 |
let offset = |
| 601 |
(sp_offset + std::mem::size_of::<usize>() - 1) & !(std::mem::size_of::<usize>() - 1); |
| 602 |
for x in &mut stack_copy[0..offset] { |
| 603 |
*x = 0; |
| 604 |
} |
| 605 |
let mut chunks = stack_copy[offset..].chunks_exact_mut(std::mem::size_of::<usize>()); |
| 606 |
|
| 607 |
// Apply sanitization to each complete pointer-aligned word in the |
| 608 |
// stack. |
| 609 |
for sp in &mut chunks { |
| 610 |
let addr = usize::from_ne_bytes(sp.to_vec().as_slice().try_into()?); |
| 611 |
let addr_signed = isize::from_ne_bytes(sp.to_vec().as_slice().try_into()?); |
| 612 |
|
| 613 |
if addr <= small_int_magnitude as usize && addr_signed >= -small_int_magnitude { |
| 614 |
continue; |
| 615 |
} |
| 616 |
|
| 617 |
if let Some(stack_map) = stack_mapping { |
| 618 |
if stack_map.contains_address(addr) { |
| 619 |
continue; |
| 620 |
} |
| 621 |
} |
| 622 |
if let Some(last_hit) = last_hit_mapping { |
| 623 |
if last_hit.contains_address(addr) { |
| 624 |
continue; |
| 625 |
} |
| 626 |
} |
| 627 |
|
| 628 |
let test = addr >> shift; |
| 629 |
if could_hit_mapping[(test >> 3) & array_mask] & (1 << (test & 7)) != 0 { |
| 630 |
if let Some(hit_mapping) = self.find_mapping_no_bias(addr) { |
| 631 |
if hit_mapping.is_executable() { |
| 632 |
last_hit_mapping = Some(hit_mapping); |
| 633 |
continue; |
| 634 |
} |
| 635 |
} |
| 636 |
} |
| 637 |
sp.copy_from_slice(&defaced); |
| 638 |
} |
| 639 |
// Zero any partial word at the top of the stack, if alignment is |
| 640 |
// such that that is required. |
| 641 |
for sp in chunks.into_remainder() { |
| 642 |
*sp = 0; |
| 643 |
} |
| 644 |
Ok(()) |
| 645 |
} |
| 646 |
|
| 647 |
// Find the mapping which the given memory address falls in. |
| 648 |
pub fn find_mapping(&self, address: usize) -> Option<&MappingInfo> { |
| 649 |
self.mappings |
| 650 |
.iter() |
| 651 |
.find(|map| address >= map.start_address && address - map.start_address < map.size) |
| 652 |
} |
| 653 |
|
| 654 |
// Find the mapping which the given memory address falls in. Uses the |
| 655 |
// unadjusted mapping address range from the kernel, rather than the |
| 656 |
// biased range. |
| 657 |
pub fn find_mapping_no_bias(&self, address: usize) -> Option<&MappingInfo> { |
| 658 |
self.mappings.iter().find(|map| { |
| 659 |
address >= map.system_mapping_info.start_address |
| 660 |
&& address < map.system_mapping_info.end_address |
| 661 |
}) |
| 662 |
} |
| 663 |
|
| 664 |
pub fn from_process_memory_for_index<T: module_reader::ReadFromModule>( |
| 665 |
&mut self, |
| 666 |
idx: usize, |
| 667 |
) -> Result<T, DumperError> { |
| 668 |
assert!(idx < self.mappings.len()); |
| 669 |
|
| 670 |
Self::from_process_memory_for_mapping(&self.mappings[idx], self.pid) |
| 671 |
} |
| 672 |
|
| 673 |
pub fn from_process_memory_for_mapping<T: module_reader::ReadFromModule>( |
| 674 |
mapping: &MappingInfo, |
| 675 |
pid: Pid, |
| 676 |
) -> Result<T, DumperError> { |
| 677 |
Ok(T::read_from_module( |
| 678 |
module_reader::ProcessReader::new(pid, mapping.start_address).into(), |
| 679 |
)?) |
| 680 |
} |
| 681 |
} |