I am trying to enumerate windows processes using EnumProcesses function provided by Win32 (psapi). Life is smooth, so I am using Rust instead of C++. Below is the code –
cargo.toml
[dependencies.windows]
features = [
"Win32_Foundation",
"Win32_System_ProcessStatus"
]
main.rs
use windows::Win32::System::ProcessStatus::*;
fn main() {
unsafe{
let mut cb_needed: u32 = 0;
let mut a_processes: Vec<u32> = Vec::with_capacity(1024);
let result: windows::Win32::Foundation::BOOL = EnumProcesses(a_processes.as_mut_ptr(), 1024*4, &mut cb_needed);
let mut _c_processes: u32 = 0;
_c_processes = cb_needed / 4;
println!("{:?}",_c_processes);
let mut count: u32 = 0;
while count < _c_processes {
println!("{:?}",a_processes[count as usize]);
count += 1;
}
}
}
When I debug the code, variable a_processes is showing length of zero. However variable cb_needed (which as per Microsoft document shows the bytes returned) is returning non-zero (almost 200). The value of variable result is 1, which is expected if the operation is successful.
When I am trying to access a_processes[count as usize], it fails with "index out of bounds". I tried it by executing it as admin, it still fails. Any idea, why a_processes is not being updated with process ids.
I am learning Rust for Windows from https://kennykerr.ca/rust-getting-started/. I went through the samples present in https://github.com/microsoft/windows-rs/tree/0.48.0/crates/samples. I also followed blogs https://chuongdong.com/malware%20development/2020/06/09/rust-ransomware1/ & https://lonami.dev/blog/woce-1/. They are using different cargo package, but the call to EnumProcesses will have same signature.
>Solution :
You are creating the vector with a capacity of 1024. You give EnumProcesses the memory to write to. Then you calculate the number of elements written – but nobody is telling the poor Vec, so it still thinks it has no elements.
Use set_len to tell the Vec that it now contains initialized elements.