Search code examples
windowswinapirustpsapiwindows-rs

EnumProcesses failing to update the Vector


I am trying to enumerate windows processes using the EnumProcesses function provided by Win32 (psapi). Life is smooth, so I am using Rust instead of C++. The code is below.

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 Kenny Kerr's getting started](https://kennykerr.ca/rust-getting-started/). I went through the samples present in Microsofts windows-rs examples. I also followed blogs of chuondong & lonami. They are using different crates, but the calls to EnumProcesses have the 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.