Skip to main content

etw_wrapper/
field.rs

1//! Serialization primitives that turn typed values into [`EVENT_DATA_DESCRIPTOR`] instances.
2
3use 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    /// Creates a descriptor over a raw memory region.
17    ///
18    /// # Safety
19    ///
20    /// If `size` is nonzero, `ptr` must point to a readable memory region of at least `size`
21    /// bytes. That region must remain allocated and readable for the entire lifetime `'a`, and it
22    /// must not be mutated in a way that races with an event write using this descriptor.
23    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/// Creates a descriptor over a `Copy` scalar.
36#[inline]
37pub fn scalar<T: Copy>(v: &T) -> EventDataDescriptor<'_> {
38    // SAFETY: the descriptor borrows `v`, which remains readable for the returned lifetime.
39    unsafe { EventDataDescriptor::new(v as *const T as u64, size_of::<T>() as u32) }
40}
41
42/// Creates a descriptor over a contiguous slice of `Copy` values.
43#[inline]
44pub fn slice<T: Copy>(values: &[T]) -> EventDataDescriptor<'_> {
45    // SAFETY: the descriptor borrows `values`, which remains readable for the returned lifetime.
46    unsafe { EventDataDescriptor::new(values.as_ptr() as u64, size_of_val(values) as u32) }
47}
48
49/// Creates a descriptor over an ANSI string (win:AnsiString).
50///
51/// # Panics
52///
53/// Panics if the buffer is not NUL-terminated.
54#[inline]
55pub fn str8(buf: &[u8]) -> EventDataDescriptor<'_> {
56    assert_eq!(buf.last(), Some(&0));
57    bytes(buf)
58}
59
60/// Creates a descriptor over a byte slice (win:Binary).
61#[inline]
62pub fn bytes(b: &[u8]) -> EventDataDescriptor<'_> {
63    // SAFETY: the descriptor borrows `b`, which remains readable for the returned lifetime.
64    unsafe { EventDataDescriptor::new(b.as_ptr() as u64, b.len() as u32) }
65}
66
67/// Converts a slice length into the type of another field.
68///
69/// Generated code uses this function for `win:Binary length="OtherField"`. The length field is
70/// derived from the blob's length and emitted in place without being exposed as a parameter.
71/// Returns `ERROR_ARITHMETIC_OVERFLOW` if the length does not fit in `T`.
72#[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/// Returns the common length of a collection of byte slices.
82///
83/// Generated array wrappers use this for `win:Binary` fields that combine `count="..."` with a
84/// referenced `length="..."`. An empty collection has an element length of zero.
85#[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/// Validates that an encoded value has the length declared by another manifest field.
102#[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/// Validates that a string buffer ends with a NUL terminator.
115#[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/// Validates that a fixed string length has room for a NUL terminator.
128#[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/// Creates a descriptor over a UTF-16 buffer (win:UnicodeString).
141///
142/// # Panics
143///
144/// Panics if the buffer is not NUL-terminated.
145#[inline]
146pub fn str16(buf: &[u16]) -> EventDataDescriptor<'_> {
147    assert_eq!(buf.last(), Some(&0));
148
149    // SAFETY: the descriptor borrows `buf`, which remains readable for the returned lifetime.
150    unsafe { EventDataDescriptor::new(buf.as_ptr() as u64, size_of_val(buf) as u32) }
151}
152
153/// Encodes `s` as NUL-terminated UTF-16.
154///
155/// Interior NUL values are replaced with spaces.
156#[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/// Encodes `s` as a fixed-length, NUL-terminated UTF-16 string for an ETW
171/// manifest field with `length="len"`.
172///
173/// The declared length includes the terminator. Content is therefore limited to
174/// `len - 1` code units, without splitting a surrogate pair. Short content
175/// is padded with spaces before the terminator so the returned buffer always
176/// contains exactly `len` code units.
177///
178/// Interior NUL values are replaced with spaces.
179///
180/// # Panics
181///
182/// Panics if `len` is zero because a fixed-length ETW string must include a
183/// NUL terminator.
184#[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/// Encodes `s` as NUL-terminated UTF-8 for a `win:AnsiString` field whose output type explicitly
209/// selects UTF-8, JSON, or XML.
210///
211/// Interior NUL values are replaced with spaces.
212#[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/// Encodes `s` as a fixed-length, NUL-terminated UTF-8 string for an ETW `win:AnsiString` field
221/// whose output type explicitly selects UTF-8, JSON, or XML and whose manifest declares
222/// `length="len"`.
223///
224/// The declared length includes the terminator. UTF-8 content is therefore
225/// limited to `len - 1` bytes, without splitting an encoded character. Short
226/// content is padded with spaces before the terminator so the returned buffer
227/// always contains exactly `len` bytes.
228///
229/// Interior NUL values are replaced with spaces.
230///
231/// # Panics
232///
233/// Panics if `len` is zero because a fixed-length ETW string must include a NUL
234/// terminator.
235#[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/// Creates a descriptor over a [`Sid`].
259#[inline]
260pub fn sid(sid: &Sid) -> EventDataDescriptor<'_> {
261    let bytes = sid.as_bytes();
262    // SAFETY: the descriptor borrows `sid` through `bytes`, which remains readable for the
263    // returned lifetime.
264    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}