Skip to main content

etw_wrapper/
field.rs

1//! Serialization primitives that turn typed values into [`EventDataDescriptor`] instances.
2
3use 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
12/// A fixed-size value that ETW serializes by copying its bytes.
13///
14/// This trait is sealed and implemented only for the Rust types that the manifest's fixed-size
15/// input types map to. Bounding [`scalar`] and [`slice()`] by it prevents strings, booleans, and
16/// custom types with padding from being copied into an event with the wrong representation.
17pub 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
28// `bool` is deliberately absent: ETW encodes win:Boolean as a 32-bit value, so generated code
29// widens it to `i32` before building a descriptor.
30impl_scalar!(
31    i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, usize, Guid, FileTime, SystemTime,
32);
33
34#[repr(transparent)]
35#[derive(Default)]
36/// A borrowed ETW payload descriptor.
37///
38/// The descriptor remains valid only while the data it references is allocated and readable.
39pub struct EventDataDescriptor<'a> {
40    inner: EVENT_DATA_DESCRIPTOR,
41    _marker: marker::PhantomData<&'a ()>,
42}
43
44impl<'a> EventDataDescriptor<'a> {
45    /// Creates a descriptor over a raw memory region.
46    ///
47    /// # Safety
48    ///
49    /// If `size` is nonzero, `ptr` must point to a readable memory region of at least `size`
50    /// bytes. That region must remain allocated and readable for the entire lifetime `'a`, and it
51    /// must not be mutated in a way that races with an event write using this descriptor.
52    #[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/// Creates a descriptor over a single [`Scalar`] value.
66#[must_use]
67#[inline]
68pub fn scalar<T: Scalar>(v: &T) -> EventDataDescriptor<'_> {
69    // SAFETY: the descriptor borrows `v`, which remains readable for the returned lifetime.
70    unsafe { EventDataDescriptor::new(v as *const T as u64, size_of::<T>() as u32) }
71}
72
73/// Creates a descriptor over a contiguous slice of [`Scalar`] values.
74#[must_use]
75#[inline]
76pub fn slice<T: Scalar>(values: &[T]) -> EventDataDescriptor<'_> {
77    // SAFETY: the descriptor borrows `values`, which remains readable for the returned lifetime.
78    unsafe { EventDataDescriptor::new(values.as_ptr() as u64, size_of_val(values) as u32) }
79}
80
81/// Creates a descriptor over an ANSI string (`win:AnsiString`).
82///
83/// # Errors
84///
85/// Returns [`Error::MissingNulTerminator`](crate::Error::MissingNulTerminator) if the buffer is
86/// not NUL-terminated.
87#[inline]
88pub fn str8(buf: &[u8]) -> crate::Result<EventDataDescriptor<'_>> {
89    ensure_nul_terminated(buf)?;
90    Ok(bytes(buf))
91}
92
93/// Creates a descriptor over a byte slice (win:Binary).
94#[must_use]
95#[inline]
96pub fn bytes(b: &[u8]) -> EventDataDescriptor<'_> {
97    // SAFETY: the descriptor borrows `b`, which remains readable for the returned lifetime.
98    unsafe { EventDataDescriptor::new(b.as_ptr() as u64, b.len() as u32) }
99}
100
101/// Converts a slice length into the type of another field.
102///
103/// Generated code uses this function for `win:Binary length="OtherField"`. The length field is
104/// derived from the blob's length and emitted in place without being exposed as a parameter.
105///
106/// # Errors
107///
108/// Returns [`Error::LengthOverflow`](crate::Error::LengthOverflow) if the length does not fit in
109/// `T`.
110#[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/// Returns the common length of a collection of byte slices.
117///
118/// Generated array wrappers use this for `win:Binary` fields that combine `count="..."` with a
119/// referenced `length="..."`. An empty collection has an element length of zero.
120#[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/// Validates that an encoded value has the length declared by another manifest field.
135#[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/// Validates that a string buffer ends with a NUL terminator.
146#[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/// Validates that a fixed string length has room for a NUL terminator.
157#[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/// Creates a descriptor over a UTF-16 buffer (`win:UnicodeString`).
168///
169/// # Errors
170///
171/// Returns [`Error::MissingNulTerminator`](crate::Error::MissingNulTerminator) if the buffer is
172/// not NUL-terminated.
173#[inline]
174pub fn str16(buf: &[u16]) -> crate::Result<EventDataDescriptor<'_>> {
175    if buf.last() != Some(&0) {
176        return Err(crate::Error::MissingNulTerminator);
177    }
178
179    // SAFETY: the descriptor borrows `buf`, which remains readable for the returned lifetime.
180    Ok(unsafe { EventDataDescriptor::new(buf.as_ptr() as u64, size_of_val(buf) as u32) })
181}
182
183/// Encodes `s` as NUL-terminated UTF-16.
184///
185/// Interior NUL values are replaced with spaces.
186#[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/// Encodes `s` as a fixed-length, NUL-terminated UTF-16 string for an ETW manifest field with
202/// `length="len"`.
203///
204/// The declared length includes the terminator. Content is therefore limited to `len - 1` code
205/// units without splitting a surrogate pair. Short content is padded with spaces before the
206/// terminator so the returned buffer always contains exactly `len` code units.
207///
208/// Interior NUL values are replaced with spaces.
209///
210/// # Errors
211///
212/// Returns [`Error::EmptyFixedLengthString`](crate::Error::EmptyFixedLengthString) if `len` is
213/// zero, because a fixed-length ETW string must include a NUL terminator.
214#[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/// Encodes `s` as NUL-terminated UTF-8 for a `win:AnsiString` field whose output type explicitly
239/// selects UTF-8, JSON, or XML.
240///
241/// Interior NUL values are replaced with spaces.
242#[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/// Encodes `s` as a fixed-length, NUL-terminated UTF-8 string for an ETW `win:AnsiString` field
252/// whose output type explicitly selects UTF-8, JSON, or XML and whose manifest declares
253/// `length="len"`.
254///
255/// The declared length includes the terminator. UTF-8 content is therefore limited to `len - 1`
256/// bytes without splitting an encoded character. Short content is padded with spaces before the
257/// terminator so the returned buffer always contains exactly `len` bytes.
258///
259/// Interior NUL values are replaced with spaces.
260///
261/// # Errors
262///
263/// Returns [`Error::EmptyFixedLengthString`](crate::Error::EmptyFixedLengthString) if `len` is
264/// zero, because a fixed-length ETW string must include a NUL terminator.
265#[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/// Creates a descriptor over a [`Sid`].
289#[must_use]
290#[inline]
291pub fn sid(sid: &Sid) -> EventDataDescriptor<'_> {
292    let bytes = sid.as_bytes();
293    // SAFETY: the descriptor borrows `sid` through `bytes`, which remains readable for the
294    // returned lifetime.
295    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        // The generated event methods report the same error for these inputs, so callers can
398        // apply one error policy across both APIs.
399        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        // These are the only non-primitive types `Scalar` accepts, and ETW decodes each by its
421        // exact ABI size, so a descriptor must span the whole value.
422        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}