1use crate::EVENT_DATA_DESCRIPTOR;
4use std::marker;
5
6pub use safe_sid::{Sid, SidBuf};
7
8#[repr(transparent)]
9#[derive(Default)]
10pub struct EventDataDescriptor<'a> {
11 inner: EVENT_DATA_DESCRIPTOR,
12 _marker: marker::PhantomData<&'a ()>,
13}
14
15impl<'a> EventDataDescriptor<'a> {
16 pub unsafe fn new(ptr: u64, size: u32) -> Self {
24 Self {
25 inner: EVENT_DATA_DESCRIPTOR {
26 Ptr: ptr,
27 Size: size,
28 ..Default::default()
29 },
30 _marker: marker::PhantomData,
31 }
32 }
33}
34
35#[inline]
37pub fn scalar<T: Copy>(v: &T) -> EventDataDescriptor<'_> {
38 unsafe { EventDataDescriptor::new(v as *const T as u64, size_of::<T>() as u32) }
40}
41
42#[inline]
44pub fn slice<T: Copy>(values: &[T]) -> EventDataDescriptor<'_> {
45 unsafe { EventDataDescriptor::new(values.as_ptr() as u64, size_of_val(values) as u32) }
47}
48
49#[inline]
55pub fn str8(buf: &[u8]) -> EventDataDescriptor<'_> {
56 assert_eq!(buf.last(), Some(&0));
57 bytes(buf)
58}
59
60#[inline]
62pub fn bytes(b: &[u8]) -> EventDataDescriptor<'_> {
63 unsafe { EventDataDescriptor::new(b.as_ptr() as u64, b.len() as u32) }
65}
66
67#[inline]
73pub fn checked_len<T: TryFrom<usize>>(len: usize) -> crate::Result<T> {
74 T::try_from(len).map_err(|_| {
75 windows::Win32::Foundation::ERROR_ARITHMETIC_OVERFLOW
76 .to_hresult()
77 .into()
78 })
79}
80
81#[doc(hidden)]
86#[inline]
87pub fn uniform_len<T: AsRef<[u8]>>(values: &[T]) -> crate::Result<usize> {
88 let Some(first) = values.first() else {
89 return Ok(0);
90 };
91 let len = first.as_ref().len();
92 if values.iter().all(|value| value.as_ref().len() == len) {
93 Ok(len)
94 } else {
95 Err(windows::Win32::Foundation::ERROR_INVALID_DATA
96 .to_hresult()
97 .into())
98 }
99}
100
101#[doc(hidden)]
103#[inline]
104pub fn ensure_len(actual: usize, expected: usize) -> crate::Result<()> {
105 if actual == expected {
106 Ok(())
107 } else {
108 Err(windows::Win32::Foundation::ERROR_INVALID_DATA
109 .to_hresult()
110 .into())
111 }
112}
113
114#[doc(hidden)]
116#[inline]
117pub fn ensure_nul_terminated(buf: &[u8]) -> crate::Result<()> {
118 if buf.last() == Some(&0) {
119 Ok(())
120 } else {
121 Err(windows::Win32::Foundation::ERROR_INVALID_DATA
122 .to_hresult()
123 .into())
124 }
125}
126
127#[doc(hidden)]
129#[inline]
130pub fn ensure_nonzero_length(len: usize) -> crate::Result<()> {
131 if len > 0 {
132 Ok(())
133 } else {
134 Err(windows::Win32::Foundation::ERROR_INVALID_DATA
135 .to_hresult()
136 .into())
137 }
138}
139
140#[inline]
146pub fn str16(buf: &[u16]) -> EventDataDescriptor<'_> {
147 assert_eq!(buf.last(), Some(&0));
148
149 unsafe { EventDataDescriptor::new(buf.as_ptr() as u64, size_of_val(buf) as u32) }
151}
152
153#[inline]
157pub fn to_u16cstring(s: &str) -> Vec<u16> {
158 let mut buf = Vec::with_capacity(s.len() + 1);
159 let mut units = [0u16; 2];
160
161 for ch in s.chars() {
162 let ch = if ch == '\0' { ' ' } else { ch };
163 buf.extend_from_slice(ch.encode_utf16(&mut units));
164 }
165
166 buf.push(0);
167 buf
168}
169
170#[inline]
185pub fn to_u16cstring_fixed_len(s: &str, len: usize) -> Vec<u16> {
186 assert!(len > 0, "len must include space for the NUL terminator");
187
188 let content_limit = len - 1;
189 let mut buf = Vec::with_capacity(len);
190 let mut units = [0u16; 2];
191
192 for ch in s.chars() {
193 let ch = if ch == '\0' { ' ' } else { ch };
194 let width = ch.len_utf16();
195
196 if buf.len() + width > content_limit {
197 break;
198 }
199
200 buf.extend_from_slice(ch.encode_utf16(&mut units));
201 }
202
203 buf.resize(content_limit, b' ' as u16);
204 buf.push(0);
205 buf
206}
207
208#[inline]
213pub fn to_cstring(s: &str) -> Vec<u8> {
214 s.bytes()
215 .map(|byte| if byte == 0 { b' ' } else { byte })
216 .chain(std::iter::once(0))
217 .collect()
218}
219
220#[inline]
236pub fn to_cstring_fixed_len(s: &str, len: usize) -> Vec<u8> {
237 assert!(len > 0, "len must include space for the NUL terminator");
238
239 let content_limit = len - 1;
240 let mut buf = Vec::with_capacity(len);
241 let mut bytes = [0u8; 4];
242
243 for ch in s.chars() {
244 let ch = if ch == '\0' { ' ' } else { ch };
245 let width = ch.len_utf8();
246 if buf.len() + width > content_limit {
247 break;
248 }
249
250 buf.extend_from_slice(ch.encode_utf8(&mut bytes).as_bytes());
251 }
252
253 buf.resize(content_limit, b' ');
254 buf.push(0);
255 buf
256}
257
258#[inline]
260pub fn sid(sid: &Sid) -> EventDataDescriptor<'_> {
261 let bytes = sid.as_bytes();
262 unsafe { EventDataDescriptor::new(bytes.as_ptr() as u64, bytes.len() as u32) }
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270
271 #[test]
272 fn to_u16cstring_replaces_interior_nul_with_space() {
273 assert_eq!(
274 to_u16cstring("a\0b"),
275 vec![b'a' as u16, b' ' as u16, b'b' as u16, 0]
276 );
277 assert_eq!(to_u16cstring("hi"), vec![b'h' as u16, b'i' as u16, 0]);
278 }
279
280 #[test]
281 fn to_u16cstring_fixed_len_matches_etw_layout() {
282 assert_eq!(
283 to_u16cstring_fixed_len("hello", 3),
284 vec![b'h' as u16, b'e' as u16, 0]
285 );
286 assert_eq!(
287 to_u16cstring_fixed_len("hello", 10),
288 vec![
289 b'h' as u16,
290 b'e' as u16,
291 b'l' as u16,
292 b'l' as u16,
293 b'o' as u16,
294 b' ' as u16,
295 b' ' as u16,
296 b' ' as u16,
297 b' ' as u16,
298 0,
299 ]
300 );
301 assert_eq!(
302 to_u16cstring_fixed_len("a\u{1F600}b", 3),
303 vec![b'a' as u16, b' ' as u16, 0]
304 );
305 assert_eq!(
306 to_u16cstring_fixed_len("a\u{1F600}b", 4),
307 vec![b'a' as u16, 0xD83D, 0xDE00, 0]
308 );
309 assert_eq!(
310 to_u16cstring_fixed_len("a\0b", 3),
311 vec![b'a' as u16, b' ' as u16, 0]
312 );
313 assert_eq!(to_u16cstring_fixed_len("ignored", 1), vec![0]);
314 }
315
316 #[test]
317 #[should_panic(expected = "len must include space for the NUL terminator")]
318 fn to_u16cstring_fixed_len_rejects_zero_length() {
319 to_u16cstring_fixed_len("", 0);
320 }
321
322 #[test]
323 fn to_cstring_replaces_interior_nul_with_space() {
324 assert_eq!(to_cstring("a\0b"), b"a b\0");
325 assert_eq!(to_cstring("hi"), b"hi\0");
326 }
327
328 #[test]
329 fn to_cstring_fixed_len_matches_etw_layout() {
330 assert_eq!(to_cstring_fixed_len("hello", 3), b"he\0");
331 assert_eq!(to_cstring_fixed_len("hello", 10), b"hello \0");
332 assert_eq!(to_cstring_fixed_len("a\u{00E9}b", 3), b"a \0");
333 assert_eq!(to_cstring_fixed_len("a\u{00E9}b", 4), b"a\xC3\xA9\0");
334 assert_eq!(to_cstring_fixed_len("a\0b", 3), b"a \0");
335 assert_eq!(to_cstring_fixed_len("ignored", 1), b"\0");
336 }
337
338 #[test]
339 #[should_panic(expected = "len must include space for the NUL terminator")]
340 fn to_cstring_fixed_len_rejects_zero_length() {
341 to_cstring_fixed_len("", 0);
342 }
343
344 #[test]
345 fn slice_uses_the_full_contiguous_size() {
346 let values = [1u32, 2, 3];
347 let descriptor = slice(&values);
348 assert_eq!(descriptor.inner.Size, 3 * size_of::<u32>() as u32);
349 assert_eq!(descriptor.inner.Ptr, values.as_ptr() as u64);
350 }
351
352 #[test]
353 fn uniform_len_accepts_empty_and_equal_slices() {
354 let empty: [&[u8]; 0] = [];
355 assert_eq!(uniform_len(&empty).unwrap(), 0);
356 assert_eq!(
357 uniform_len(&[b"abc".as_slice(), b"def".as_slice()]).unwrap(),
358 3
359 );
360 }
361
362 #[test]
363 fn uniform_len_rejects_mixed_lengths() {
364 assert!(uniform_len(&[b"a".as_slice(), b"bc".as_slice()]).is_err());
365 }
366
367 #[test]
368 fn ensure_len_rejects_mismatches() {
369 assert!(ensure_len(3, 3).is_ok());
370 assert!(ensure_len(2, 3).is_err());
371 }
372
373 #[test]
374 fn string_input_validation_rejects_invalid_buffers_and_lengths() {
375 assert!(ensure_nul_terminated(b"valid\0").is_ok());
376 assert!(ensure_nul_terminated(b"invalid").is_err());
377 assert!(ensure_nul_terminated(b"").is_err());
378 assert!(ensure_nonzero_length(1).is_ok());
379 assert!(ensure_nonzero_length(0).is_err());
380 }
381}