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/// Creates a descriptor over a UTF-16 buffer (win:UnicodeString).
115///
116/// # Panics
117///
118/// Panics if the buffer is not NUL-terminated.
119#[inline]
120pub fn str16(buf: &[u16]) -> EventDataDescriptor<'_> {
121    assert_eq!(buf.last(), Some(&0));
122
123    // SAFETY: the descriptor borrows `buf`, which remains readable for the returned lifetime.
124    unsafe { EventDataDescriptor::new(buf.as_ptr() as u64, size_of_val(buf) as u32) }
125}
126
127/// Encodes `s` as NUL-terminated UTF-16.
128///
129/// Interior NUL values are replaced with spaces.
130#[inline]
131pub fn to_u16cstring(s: &str) -> Vec<u16> {
132    let mut buf = Vec::with_capacity(s.len() + 1);
133    let mut units = [0u16; 2];
134
135    for ch in s.chars() {
136        let ch = if ch == '\0' { ' ' } else { ch };
137        buf.extend_from_slice(ch.encode_utf16(&mut units));
138    }
139
140    buf.push(0);
141    buf
142}
143
144/// Encodes `s` as a fixed-length, NUL-terminated UTF-16 string for an ETW
145/// manifest field with `length="len"`.
146///
147/// The declared length includes the terminator. Content is therefore limited to
148/// `len - 1` code units, without splitting a surrogate pair. Short content
149/// is padded with spaces before the terminator so the returned buffer always
150/// contains exactly `len` code units.
151///
152/// Interior NUL values are replaced with spaces.
153///
154/// # Panics
155///
156/// Panics if `len` is zero because a fixed-length ETW string must include a
157/// NUL terminator.
158#[inline]
159pub fn to_u16cstring_fixed_len(s: &str, len: usize) -> Vec<u16> {
160    assert!(len > 0, "len must include space for the NUL terminator");
161
162    let content_limit = len - 1;
163    let mut buf = Vec::with_capacity(len);
164    let mut units = [0u16; 2];
165
166    for ch in s.chars() {
167        let ch = if ch == '\0' { ' ' } else { ch };
168        let width = ch.len_utf16();
169
170        if buf.len() + width > content_limit {
171            break;
172        }
173
174        buf.extend_from_slice(ch.encode_utf16(&mut units));
175    }
176
177    buf.resize(content_limit, b' ' as u16);
178    buf.push(0);
179    buf
180}
181
182/// Encodes `s` as NUL-terminated UTF-8 for a `win:AnsiString` field whose output type explicitly
183/// selects UTF-8, JSON, or XML.
184///
185/// Interior NUL values are replaced with spaces.
186#[inline]
187pub fn to_cstring(s: &str) -> Vec<u8> {
188    s.bytes()
189        .map(|byte| if byte == 0 { b' ' } else { byte })
190        .chain(std::iter::once(0))
191        .collect()
192}
193
194/// Encodes `s` as a fixed-length, NUL-terminated UTF-8 string for an ETW `win:AnsiString` field
195/// whose output type explicitly selects UTF-8, JSON, or XML and whose manifest declares
196/// `length="len"`.
197///
198/// The declared length includes the terminator. UTF-8 content is therefore
199/// limited to `len - 1` bytes, without splitting an encoded character. Short
200/// content is padded with spaces before the terminator so the returned buffer
201/// always contains exactly `len` bytes.
202///
203/// Interior NUL values are replaced with spaces.
204///
205/// # Panics
206///
207/// Panics if `len` is zero because a fixed-length ETW string must include a NUL
208/// terminator.
209#[inline]
210pub fn to_cstring_fixed_len(s: &str, len: usize) -> Vec<u8> {
211    assert!(len > 0, "len must include space for the NUL terminator");
212
213    let content_limit = len - 1;
214    let mut buf = Vec::with_capacity(len);
215    let mut bytes = [0u8; 4];
216
217    for ch in s.chars() {
218        let ch = if ch == '\0' { ' ' } else { ch };
219        let width = ch.len_utf8();
220        if buf.len() + width > content_limit {
221            break;
222        }
223
224        buf.extend_from_slice(ch.encode_utf8(&mut bytes).as_bytes());
225    }
226
227    buf.resize(content_limit, b' ');
228    buf.push(0);
229    buf
230}
231
232/// Creates a descriptor over a [`Sid`].
233#[inline]
234pub fn sid(sid: &Sid) -> EventDataDescriptor<'_> {
235    let bytes = sid.as_bytes();
236    // SAFETY: the descriptor borrows `sid` through `bytes`, which remains readable for the
237    // returned lifetime.
238    unsafe { EventDataDescriptor::new(bytes.as_ptr() as u64, bytes.len() as u32) }
239}
240
241#[cfg(test)]
242mod tests {
243    use super::*;
244
245    #[test]
246    fn to_u16cstring_replaces_interior_nul_with_space() {
247        assert_eq!(
248            to_u16cstring("a\0b"),
249            vec![b'a' as u16, b' ' as u16, b'b' as u16, 0]
250        );
251        assert_eq!(to_u16cstring("hi"), vec![b'h' as u16, b'i' as u16, 0]);
252    }
253
254    #[test]
255    fn to_u16cstring_fixed_len_matches_etw_layout() {
256        assert_eq!(
257            to_u16cstring_fixed_len("hello", 3),
258            vec![b'h' as u16, b'e' as u16, 0]
259        );
260        assert_eq!(
261            to_u16cstring_fixed_len("hello", 10),
262            vec![
263                b'h' as u16,
264                b'e' as u16,
265                b'l' as u16,
266                b'l' as u16,
267                b'o' as u16,
268                b' ' as u16,
269                b' ' as u16,
270                b' ' as u16,
271                b' ' as u16,
272                0,
273            ]
274        );
275        assert_eq!(
276            to_u16cstring_fixed_len("a\u{1F600}b", 3),
277            vec![b'a' as u16, b' ' as u16, 0]
278        );
279        assert_eq!(
280            to_u16cstring_fixed_len("a\u{1F600}b", 4),
281            vec![b'a' as u16, 0xD83D, 0xDE00, 0]
282        );
283        assert_eq!(
284            to_u16cstring_fixed_len("a\0b", 3),
285            vec![b'a' as u16, b' ' as u16, 0]
286        );
287        assert_eq!(to_u16cstring_fixed_len("ignored", 1), vec![0]);
288    }
289
290    #[test]
291    #[should_panic(expected = "len must include space for the NUL terminator")]
292    fn to_u16cstring_fixed_len_rejects_zero_length() {
293        to_u16cstring_fixed_len("", 0);
294    }
295
296    #[test]
297    fn to_cstring_replaces_interior_nul_with_space() {
298        assert_eq!(to_cstring("a\0b"), b"a b\0");
299        assert_eq!(to_cstring("hi"), b"hi\0");
300    }
301
302    #[test]
303    fn to_cstring_fixed_len_matches_etw_layout() {
304        assert_eq!(to_cstring_fixed_len("hello", 3), b"he\0");
305        assert_eq!(to_cstring_fixed_len("hello", 10), b"hello    \0");
306        assert_eq!(to_cstring_fixed_len("a\u{00E9}b", 3), b"a \0");
307        assert_eq!(to_cstring_fixed_len("a\u{00E9}b", 4), b"a\xC3\xA9\0");
308        assert_eq!(to_cstring_fixed_len("a\0b", 3), b"a \0");
309        assert_eq!(to_cstring_fixed_len("ignored", 1), b"\0");
310    }
311
312    #[test]
313    #[should_panic(expected = "len must include space for the NUL terminator")]
314    fn to_cstring_fixed_len_rejects_zero_length() {
315        to_cstring_fixed_len("", 0);
316    }
317
318    #[test]
319    fn slice_uses_the_full_contiguous_size() {
320        let values = [1u32, 2, 3];
321        let descriptor = slice(&values);
322        assert_eq!(descriptor.inner.Size, 3 * size_of::<u32>() as u32);
323        assert_eq!(descriptor.inner.Ptr, values.as_ptr() as u64);
324    }
325
326    #[test]
327    fn uniform_len_accepts_empty_and_equal_slices() {
328        let empty: [&[u8]; 0] = [];
329        assert_eq!(uniform_len(&empty).unwrap(), 0);
330        assert_eq!(
331            uniform_len(&[b"abc".as_slice(), b"def".as_slice()]).unwrap(),
332            3
333        );
334    }
335
336    #[test]
337    fn uniform_len_rejects_mixed_lengths() {
338        assert!(uniform_len(&[b"a".as_slice(), b"bc".as_slice()]).is_err());
339    }
340
341    #[test]
342    fn ensure_len_rejects_mismatches() {
343        assert!(ensure_len(3, 3).is_ok());
344        assert!(ensure_len(2, 3).is_err());
345    }
346}