Debian Codegraph @

src/collection/disks/windows/bindings.rs

raw symbols SCIP
1 //! Windows bindings to get disk I/O counters.
2
3 use std::{
4 ffi::OsString,
5 io, mem,
6 os::windows::prelude::{OsStrExt, OsStringExt},
7 path::{Path, PathBuf},
8 };
9
10 use anyhow::bail;
11 use windows::Win32::{
12 Foundation::{self, CloseHandle, HANDLE},
13 Storage::FileSystem::{
14 CreateFileW, FILE_FLAGS_AND_ATTRIBUTES, FILE_SHARE_READ, FILE_SHARE_WRITE,
15 FindFirstVolumeW, FindNextVolumeW, FindVolumeClose, GetVolumeNameForVolumeMountPointW,
16 OPEN_EXISTING,
17 },
18 System::{
19 IO::DeviceIoControl,
20 Ioctl::{DISK_PERFORMANCE, IOCTL_DISK_PERFORMANCE},
21 },
22 };
23
24 /// Returns the I/O for a given volume.
25 ///
26 /// Based on [psutil's implementation](https://github.com/giampaolo/psutil/blob/52fe5517f716dedf9c9918e56325e49a49146130/psutil/arch/windows/disk.c#L78-L83)
27 /// and [heim's implementation](https://github.com/heim-rs/heim/blob/master/heim-disk/src/sys/windows/bindings/perf.rs).
28 fn volume_io(volume: &Path) -> anyhow::Result<DISK_PERFORMANCE> {
29 if volume.is_file() {
30 // We assume the volume is a directory, so bail ASAP if it isn't.
31 bail!("Expects a directory to be passed in.");
32 }
33
34 let volume = {
35 let mut wide_path = volume.as_os_str().encode_wide().collect::<Vec<_>>();
36
37 // We replace the trailing backslash and replace it with a \0.
38 wide_path.pop();
39 wide_path.push(0x0000);
40
41 wide_path
42 };
43
44 // SAFETY: API call, arguments should be correct. We must also check after the
45 // call to ensure it is valid.
46 let h_device = unsafe {
47 CreateFileW(
48 windows::core::PCWSTR(volume.as_ptr()),
49 0,
50 FILE_SHARE_READ | FILE_SHARE_WRITE,
51 None,
52 OPEN_EXISTING,
53 FILE_FLAGS_AND_ATTRIBUTES(0),
54 Some(Foundation::HANDLE::default()),
55 )?
56 };
57
58 if h_device.is_invalid() {
59 bail!("Invalid handle value: {:?}", io::Error::last_os_error());
60 }
61
62 let mut disk_performance = DISK_PERFORMANCE::default();
63 let mut bytes_returned = 0;
64
65 // SAFETY: This should be safe, we'll manually check the results and the
66 // arguments should be valid.
67 let ret = unsafe {
68 DeviceIoControl(
69 h_device,
70 IOCTL_DISK_PERFORMANCE,
71 None,
72 0,
73 Some(&mut disk_performance as *mut _ as _),
74 mem::size_of::<DISK_PERFORMANCE>() as u32,
75 Some(&mut bytes_returned),
76 None,
77 )
78 };
79
80 // SAFETY: This should be safe, we will check the result as well.
81 let handle_result = unsafe { CloseHandle(h_device) };
82 if let Err(err) = handle_result {
83 bail!("Handle error: {err:?}");
84 }
85
86 if let Err(err) = ret {
87 bail!("Device I/O error: {err:?}");
88 } else {
89 Ok(disk_performance)
90 }
91 }
92
93 fn current_volume(buffer: &[u16]) -> PathBuf {
94 let first_null = buffer.iter().position(|byte| *byte == 0x00).unwrap_or(0);
95 let path_string = OsString::from_wide(&buffer[..first_null]);
96
97 PathBuf::from(path_string)
98 }
99
100 fn close_find_handle(handle: HANDLE) -> anyhow::Result<()> {
101 // Clean up the handle.
102 // SAFETY: This should be safe, we will check the result as well.
103 let res = unsafe { FindVolumeClose(handle) };
104 Ok(res?)
105 }
106
107 /// Returns the I/O for all volumes.
108 ///
109 /// Based on [psutil's implementation](https://github.com/giampaolo/psutil/blob/52fe5517f716dedf9c9918e56325e49a49146130/psutil/arch/windows/disk.c#L78-L83)
110 /// and [heim's implementation](https://github.com/heim-rs/heim/blob/master/heim-disk/src/sys/windows/bindings/perf.rs).
111 pub(crate) fn all_volume_io() -> anyhow::Result<Vec<anyhow::Result<(DISK_PERFORMANCE, String)>>> {
112 const ERROR_NO_MORE_FILES: i32 = Foundation::ERROR_NO_MORE_FILES.0 as i32;
113 let mut ret = vec![];
114 let mut buffer = [0_u16; Foundation::MAX_PATH as usize];
115
116 // Get the first volume and add the stats needed.
117 // SAFETY: We must verify the handle is correct. If no volume is found, it will
118 // be set to `INVALID_HANDLE_VALUE`.
119 let handle = unsafe { FindFirstVolumeW(&mut buffer) }?;
120 if handle.is_invalid() {
121 bail!("Invalid handle value: {:?}", io::Error::last_os_error());
122 }
123
124 {
125 let volume = current_volume(&buffer);
126 ret.push(volume_io(&volume).map(|res| (res, volume.to_string_lossy().to_string())));
127 }
128
129 // Now iterate until there are no more volumes.
130 while unsafe { FindNextVolumeW(handle, &mut buffer) }.is_ok() {
131 let volume = current_volume(&buffer);
132 ret.push(volume_io(&volume).map(|res| (res, volume.to_string_lossy().to_string())));
133 }
134
135 let err = io::Error::last_os_error();
136 match err.raw_os_error() {
137 Some(ERROR_NO_MORE_FILES) => {
138 // Iteration completed successfully, continue on.
139 }
140 _ => {
141 // Some error occurred.
142 close_find_handle(handle)?;
143 bail!("Error while iterating over volumes: {err:?}");
144 }
145 }
146
147 close_find_handle(handle)?;
148
149 Ok(ret)
150 }
151
152 /// Returns the volume name from a mount name if possible.
153 pub(crate) fn volume_name_from_mount(mount: &str) -> anyhow::Result<String> {
154 // According to winapi docs 50 is a reasonable length to accommodate the volume
155 // path https://docs.microsoft.com/en-us/windows/win32/api/fileapi/nf-fileapi-getvolumenameforvolumemountpointw
156 const VOLUME_MAX_LEN: usize = 50;
157
158 let mount = {
159 let mount_path = Path::new(mount);
160 let mut wide_path = mount_path.as_os_str().encode_wide().collect::<Vec<_>>();
161
162 // Always push on a \0 character, without this it will occasionally break.
163 wide_path.push(0x0000);
164
165 wide_path
166 };
167 let mut buffer = [0_u16; VOLUME_MAX_LEN];
168
169 // SAFETY: API call, we must check the result for validating safety.
170 let result = unsafe {
171 GetVolumeNameForVolumeMountPointW(windows::core::PCWSTR(mount.as_ptr()), &mut buffer)
172 };
173
174 if let Err(err) = result {
175 bail!("Could not get volume name for mount point: {err:?}");
176 } else {
177 Ok(current_volume(&buffer).to_string_lossy().to_string())
178 }
179 }