1use crate::{EVENT_DATA_DESCRIPTOR, FileTime, Guid, SystemTime};
4use std::marker;
5
6pub use safe_sid::{Sid, SidBuf};
7
8mod sealed {
9 pub trait Sealed {}
10}
11
12pub trait Scalar: Copy + sealed::Sealed {}
18
19macro_rules! impl_scalar {
20 ($($type:ty),+ $(,)?) => {
21 $(
22 impl sealed::Sealed for $type {}
23 impl Scalar for $type {}
24 )+
25 };
26}
27
28impl_scalar!(
31 i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, usize, Guid, FileTime, SystemTime,
32);
33
34#[repr(transparent)]
35#[derive(Default)]
36pub struct EventDataDescriptor<'a> {
40 inner: EVENT_DATA_DESCRIPTOR,
41 _marker: marker::PhantomData<&'a ()>,
42}
43
44impl<'a> EventDataDescriptor<'a> {
45 #[must_use]
53 pub unsafe fn new(ptr: u64, size: u32) -> Self {
54 Self {
55 inner: EVENT_DATA_DESCRIPTOR {
56 Ptr: ptr,
57 Size: size,
58 Anonymous: Default::default(),
59 },
60 _marker: marker::PhantomData,
61 }
62 }
63}
64
65#[must_use]
67#[inline]
68pub fn scalar<T: Scalar>(v: &T) -> EventDataDescriptor<'_> {
69 unsafe { EventDataDescriptor::new(v as *const T as u64, size_of::<T>() as u32) }
71}
72
73#[must_use]
75#[inline]
76pub fn slice<T: Scalar>(values: &[T]) -> EventDataDescriptor<'_> {
77 unsafe { EventDataDescriptor::new(values.as_ptr() as u64, size_of_val(values) as u32) }
79}
80
81#[inline]
88pub fn str8(buf: &[u8]) -> crate::Result<EventDataDescriptor<'_>> {
89 ensure_nul_terminated(buf)?;
90 Ok(bytes(buf))
91}
92
93#[must_use]
95#[inline]
96pub fn bytes(b: &[u8]) -> EventDataDescriptor<'_> {
97 unsafe { EventDataDescriptor::new(b.as_ptr() as u64, b.len() as u32) }
99}
100
101#[doc(hidden)]
111#[inline]
112pub fn checked_len<T: TryFrom<usize>>(len: usize) -> crate::Result<T> {
113 T::try_from(len).map_err(|_| crate::Error::LengthOverflow)
114}
115
116#[doc(hidden)]
121#[inline]
122pub fn uniform_len<T: AsRef<[u8]>>(values: &[T]) -> crate::Result<usize> {
123 let Some(first) = values.first() else {
124 return Ok(0);
125 };
126 let len = first.as_ref().len();
127 if values.iter().all(|value| value.as_ref().len() == len) {
128 Ok(len)
129 } else {
130 Err(crate::Error::MismatchedArrayLengths)
131 }
132}
133
134#[doc(hidden)]
136#[inline]
137pub fn ensure_len(actual: usize, expected: usize) -> crate::Result<()> {
138 if actual == expected {
139 Ok(())
140 } else {
141 Err(crate::Error::LengthMismatch)
142 }
143}
144
145#[doc(hidden)]
147#[inline]
148pub fn ensure_nul_terminated(buf: &[u8]) -> crate::Result<()> {
149 if buf.last() == Some(&0) {
150 Ok(())
151 } else {
152 Err(crate::Error::MissingNulTerminator)
153 }
154}
155
156#[doc(hidden)]
158#[inline]
159pub fn ensure_nonzero_length(len: usize) -> crate::Result<()> {
160 if len > 0 {
161 Ok(())
162 } else {
163 Err(crate::Error::EmptyFixedLengthString)
164 }
165}
166
167#[inline]
174pub fn str16(buf: &[u16]) -> crate::Result<EventDataDescriptor<'_>> {
175 if buf.last() != Some(&0) {
176 return Err(crate::Error::MissingNulTerminator);
177 }
178
179 Ok(unsafe { EventDataDescriptor::new(buf.as_ptr() as u64, size_of_val(buf) as u32) })
181}
182
183#[must_use]
187#[inline]
188pub fn to_u16cstring(s: &str) -> Vec<u16> {
189 let mut buf = Vec::with_capacity(s.len() + 1);
190 let mut units = [0u16; 2];
191
192 for ch in s.chars() {
193 let ch = if ch == '\0' { ' ' } else { ch };
194 buf.extend_from_slice(ch.encode_utf16(&mut units));
195 }
196
197 buf.push(0);
198 buf
199}
200
201#[inline]
215pub fn to_u16cstring_fixed_len(s: &str, len: usize) -> crate::Result<Vec<u16>> {
216 ensure_nonzero_length(len)?;
217
218 let content_limit = len - 1;
219 let mut buf = Vec::with_capacity(len);
220 let mut units = [0u16; 2];
221
222 for ch in s.chars() {
223 let ch = if ch == '\0' { ' ' } else { ch };
224 let width = ch.len_utf16();
225
226 if buf.len() + width > content_limit {
227 break;
228 }
229
230 buf.extend_from_slice(ch.encode_utf16(&mut units));
231 }
232
233 buf.resize(content_limit, b' ' as u16);
234 buf.push(0);
235 Ok(buf)
236}
237
238#[must_use]
243#[inline]
244pub fn to_cstring(s: &str) -> Vec<u8> {
245 s.bytes()
246 .map(|byte| if byte == 0 { b' ' } else { byte })
247 .chain(std::iter::once(0))
248 .collect()
249}
250
251#[inline]
266pub fn to_cstring_fixed_len(s: &str, len: usize) -> crate::Result<Vec<u8>> {
267 ensure_nonzero_length(len)?;
268
269 let content_limit = len - 1;
270 let mut buf = Vec::with_capacity(len);
271 let mut bytes = [0u8; 4];
272
273 for ch in s.chars() {
274 let ch = if ch == '\0' { ' ' } else { ch };
275 let width = ch.len_utf8();
276 if buf.len() + width > content_limit {
277 break;
278 }
279
280 buf.extend_from_slice(ch.encode_utf8(&mut bytes).as_bytes());
281 }
282
283 buf.resize(content_limit, b' ');
284 buf.push(0);
285 Ok(buf)
286}
287
288#[must_use]
290#[inline]
291pub fn sid(sid: &Sid) -> EventDataDescriptor<'_> {
292 let bytes = sid.as_bytes();
293 unsafe { EventDataDescriptor::new(bytes.as_ptr() as u64, bytes.len() as u32) }
296}
297
298#[cfg(test)]
299mod tests {
300 use super::*;
301
302 #[test]
303 fn to_u16cstring_replaces_interior_nul_with_space() {
304 assert_eq!(
305 to_u16cstring("a\0b"),
306 vec![b'a' as u16, b' ' as u16, b'b' as u16, 0]
307 );
308 assert_eq!(to_u16cstring("hi"), vec![b'h' as u16, b'i' as u16, 0]);
309 }
310
311 #[test]
312 fn to_u16cstring_fixed_len_matches_etw_layout() {
313 assert_eq!(
314 to_u16cstring_fixed_len("hello", 3).unwrap(),
315 vec![b'h' as u16, b'e' as u16, 0]
316 );
317 assert_eq!(
318 to_u16cstring_fixed_len("hello", 10).unwrap(),
319 vec![
320 b'h' as u16,
321 b'e' as u16,
322 b'l' as u16,
323 b'l' as u16,
324 b'o' as u16,
325 b' ' as u16,
326 b' ' as u16,
327 b' ' as u16,
328 b' ' as u16,
329 0,
330 ]
331 );
332 assert_eq!(
333 to_u16cstring_fixed_len("a\u{1F600}b", 3).unwrap(),
334 vec![b'a' as u16, b' ' as u16, 0]
335 );
336 assert_eq!(
337 to_u16cstring_fixed_len("a\u{1F600}b", 4).unwrap(),
338 vec![b'a' as u16, 0xD83D, 0xDE00, 0]
339 );
340 assert_eq!(
341 to_u16cstring_fixed_len("a\0b", 3).unwrap(),
342 vec![b'a' as u16, b' ' as u16, 0]
343 );
344 assert_eq!(to_u16cstring_fixed_len("ignored", 1).unwrap(), vec![0]);
345 }
346
347 #[test]
348 fn to_u16cstring_fixed_len_rejects_zero_length() {
349 assert!(matches!(
350 to_u16cstring_fixed_len("", 0),
351 Err(crate::Error::EmptyFixedLengthString)
352 ));
353 }
354
355 #[test]
356 fn to_cstring_replaces_interior_nul_with_space() {
357 assert_eq!(to_cstring("a\0b"), b"a b\0");
358 assert_eq!(to_cstring("hi"), b"hi\0");
359 }
360
361 #[test]
362 fn to_cstring_fixed_len_matches_etw_layout() {
363 assert_eq!(to_cstring_fixed_len("hello", 3).unwrap(), b"he\0");
364 assert_eq!(to_cstring_fixed_len("hello", 10).unwrap(), b"hello \0");
365 assert_eq!(to_cstring_fixed_len("a\u{00E9}b", 3).unwrap(), b"a \0");
366 assert_eq!(
367 to_cstring_fixed_len("a\u{00E9}b", 4).unwrap(),
368 b"a\xC3\xA9\0"
369 );
370 assert_eq!(to_cstring_fixed_len("a\0b", 3).unwrap(), b"a \0");
371 assert_eq!(to_cstring_fixed_len("ignored", 1).unwrap(), b"\0");
372 }
373
374 #[test]
375 fn to_cstring_fixed_len_rejects_zero_length() {
376 assert!(matches!(
377 to_cstring_fixed_len("", 0),
378 Err(crate::Error::EmptyFixedLengthString)
379 ));
380 }
381
382 #[test]
383 fn string_descriptors_cover_the_whole_buffer() {
384 let utf16 = to_u16cstring("hi");
385 let descriptor = str16(&utf16).unwrap();
386 assert_eq!(descriptor.inner.Size, size_of_val(utf16.as_slice()) as u32);
387 assert_eq!(descriptor.inner.Ptr, utf16.as_ptr() as u64);
388
389 let ansi = to_cstring("hi");
390 let descriptor = str8(&ansi).unwrap();
391 assert_eq!(descriptor.inner.Size, ansi.len() as u32);
392 assert_eq!(descriptor.inner.Ptr, ansi.as_ptr() as u64);
393 }
394
395 #[test]
396 fn string_descriptors_reject_unterminated_buffers() {
397 for buf in [[b'h' as u16, b'i' as u16].as_slice(), [].as_slice()] {
400 assert!(matches!(
401 str16(buf),
402 Err(crate::Error::MissingNulTerminator)
403 ));
404 }
405 for buf in [b"hi".as_slice(), b"".as_slice()] {
406 assert!(matches!(str8(buf), Err(crate::Error::MissingNulTerminator)));
407 }
408 }
409
410 #[test]
411 fn slice_uses_the_full_contiguous_size() {
412 let values = [1u32, 2, 3];
413 let descriptor = slice(&values);
414 assert_eq!(descriptor.inner.Size, 3 * size_of::<u32>() as u32);
415 assert_eq!(descriptor.inner.Ptr, values.as_ptr() as u64);
416 }
417
418 #[test]
419 fn scalar_covers_the_abi_struct_types() {
420 let guid = Guid::from_u128(0);
423 assert_eq!(scalar(&guid).inner.Size, 16);
424
425 let filetime = FileTime::default();
426 assert_eq!(scalar(&filetime).inner.Size, 8);
427
428 let systemtime = SystemTime::default();
429 assert_eq!(scalar(&systemtime).inner.Size, 16);
430 }
431
432 #[test]
433 fn uniform_len_accepts_empty_and_equal_slices() {
434 let empty: [&[u8]; 0] = [];
435 assert_eq!(uniform_len(&empty).unwrap(), 0);
436 assert_eq!(
437 uniform_len(&[b"abc".as_slice(), b"def".as_slice()]).unwrap(),
438 3
439 );
440 }
441
442 #[test]
443 fn uniform_len_rejects_mixed_lengths() {
444 assert!(uniform_len(&[b"a".as_slice(), b"bc".as_slice()]).is_err());
445 }
446
447 #[test]
448 fn ensure_len_rejects_mismatches() {
449 assert!(ensure_len(3, 3).is_ok());
450 assert!(ensure_len(2, 3).is_err());
451 }
452
453 #[test]
454 fn string_input_validation_rejects_invalid_buffers_and_lengths() {
455 assert!(ensure_nul_terminated(b"valid\0").is_ok());
456 assert!(ensure_nul_terminated(b"invalid").is_err());
457 assert!(ensure_nul_terminated(b"").is_err());
458 assert!(ensure_nonzero_length(1).is_ok());
459 assert!(ensure_nonzero_length(0).is_err());
460 }
461}