Last active
November 16, 2023 02:32
-
-
Save alexng353/0a9b66565065af9814ea1179b05d80da to your computer and use it in GitHub Desktop.
[RUST] Determine current windows shell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// get the parent process info, translated from | |
// https://gist.github.com/mattn/253013/d47b90159cf8ffa4d92448614b748aa1d235ebe4 | |
fn get_parent_process_info() -> Option<(DWORD, String)> { | |
let mut pe32: PROCESSENTRY32 = unsafe { zeroed() }; | |
let pid = unsafe { GetCurrentProcessId() }; | |
let h_snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; | |
let mut ppid = 0; | |
if h_snapshot == INVALID_HANDLE_VALUE { | |
return None; | |
} | |
pe32.dwSize = std::mem::size_of::<PROCESSENTRY32>() as u32; | |
if unsafe { Process32First(h_snapshot, &mut pe32) } != 0 { | |
loop { | |
if pe32.th32ProcessID == pid { | |
ppid = pe32.th32ParentProcessID; | |
break; | |
} | |
if unsafe { Process32Next(h_snapshot, &mut pe32) } == 0 { | |
break; | |
} | |
} | |
} | |
let mut parent_process_name = None; | |
if ppid != 0 { | |
parent_process_name = get_process_name(ppid); | |
} | |
unsafe { CloseHandle(h_snapshot) }; | |
if let Some(ppname) = parent_process_name { | |
Some((ppid, ppname)) | |
} else { | |
None | |
} | |
} | |
fn get_process_name(pid: DWORD) -> Option<String> { | |
let mut pe32: PROCESSENTRY32 = unsafe { zeroed() }; | |
let h_snapshot = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) }; | |
if h_snapshot == INVALID_HANDLE_VALUE { | |
return None; | |
} | |
pe32.dwSize = std::mem::size_of::<PROCESSENTRY32>() as u32; | |
if unsafe { Process32First(h_snapshot, &mut pe32) } != 0 { | |
loop { | |
if pe32.th32ProcessID == pid { | |
let process_name_cstr = unsafe { CStr::from_ptr(pe32.szExeFile.as_ptr()) }; | |
let process_name = process_name_cstr.to_string_lossy().into_owned(); | |
unsafe { CloseHandle(h_snapshot) }; | |
return Some(process_name); | |
} | |
if unsafe { Process32Next(h_snapshot, &mut pe32) } == 0 { | |
break; | |
} | |
} | |
} | |
unsafe { CloseHandle(h_snapshot) }; | |
None | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment