Custom libc wrapper: added fork function

This commit is contained in:
Elnath 2025-05-19 22:13:58 +02:00
parent 123ec6e7d7
commit f9bba6c990
3 changed files with 32 additions and 4 deletions

26
src/clibwrap/fork.rs Normal file
View File

@ -0,0 +1,26 @@
use crate::clibwrap::{ErrnoError, Pid};
mod external {
use crate::clibwrap::Pid;
unsafe extern "C" {
pub fn fork() -> Pid;
}
}
#[derive(Debug)]
pub enum ForkResult {
Parent { child_pid: Pid },
Child,
}
pub unsafe fn fork() -> Result<ForkResult, ErrnoError> {
let return_value = unsafe { external::fork() };
if return_value == -1 {
unsafe { Err(ErrnoError::from_current_errno()) }
} else if return_value == 0 {
Ok(ForkResult::Child)
} else {
Ok(ForkResult::Parent { child_pid: return_value })
}
}

View File

@ -1,7 +1,8 @@
use std::ffi::{c_char, c_int, CStr}; use std::ffi::{c_char, c_int, CStr};
pub mod ptrace; pub mod ptrace;
pub mod fork;
type Pid = i32; pub type Pid = i32;
unsafe extern "C" { unsafe extern "C" {
fn __errno_location() -> *mut c_int; fn __errno_location() -> *mut c_int;

View File

@ -3,9 +3,10 @@ mod syscall_info;
mod clibwrap; mod clibwrap;
use crate::debug_target::{ExitedTarget, StoppedTarget}; use crate::debug_target::{ExitedTarget, StoppedTarget};
use clibwrap::fork::{fork, ForkResult};
use color_eyre::eyre::eyre; use color_eyre::eyre::eyre;
use either::Either; use either::Either;
use nix::unistd::{fork, ForkResult}; use nix::unistd::Pid;
use std::ffi::CString; use std::ffi::CString;
#[allow(dead_code)] #[allow(dead_code)]
@ -52,10 +53,10 @@ fn main() -> color_eyre::Result<()> {
nix::unistd::execv(&child_exec_path, &[&child_exec_path])?; nix::unistd::execv(&child_exec_path, &[&child_exec_path])?;
unreachable!(); unreachable!();
} }
Ok(ForkResult::Parent { child: child_pid }) => { Ok(ForkResult::Parent { child_pid }) => {
println!("✔️ Created child {child_pid}"); println!("✔️ Created child {child_pid}");
let mut target = StoppedTarget::new(child_pid)?; let mut target = StoppedTarget::new(Pid::from_raw(child_pid))?;
println!("✔️ Child ready!"); println!("✔️ Child ready!");
let breakpoint1 = 0x40101b; let breakpoint1 = 0x40101b;