Skip to main content

etw_wrapper/
context.rs

1//! Provider registration, enablement tracking, and event writing.
2
3use std::ffi::c_void;
4use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering};
5
6use crate::bindings::{
7    EVENT_CONTROL_CODE_DISABLE_PROVIDER, EVENT_CONTROL_CODE_ENABLE_PROVIDER,
8    EVENT_FILTER_DESCRIPTOR, EventRegister, EventUnregister, EventWriteTransfer, GUID as RAW_GUID,
9    REGHANDLE,
10};
11use crate::error::win32_result;
12use crate::field::EventDataDescriptor;
13use crate::{EVENT_DATA_DESCRIPTOR, EventDescriptor, Guid, Result};
14
15/// A registered ETW provider.
16///
17/// The provider is unregistered when this is dropped.
18pub struct EtwLogger {
19    ctx: Box<EtwContext>,
20}
21
22impl EtwLogger {
23    /// Registers the provider with the given GUID.
24    ///
25    /// # Errors
26    ///
27    /// Returns [`Error::Windows`](crate::Error::Windows) if Windows cannot register the provider.
28    pub fn register(guid: &Guid) -> Result<Self> {
29        Ok(EtwLogger {
30            ctx: EtwContext::register(guid)?,
31        })
32    }
33
34    /// Returns whether an active ETW session accepts the specified level and keyword.
35    #[must_use]
36    #[inline]
37    pub fn enabled(&self, level: u8, keyword: u64) -> bool {
38        self.ctx.enabled(level, keyword)
39    }
40
41    /// Writes an event with its payload descriptors in manifest-template order.
42    ///
43    /// This method does not call [`EtwLogger::enabled`] first.
44    ///
45    /// # Errors
46    ///
47    /// Returns [`Error::Windows`](crate::Error::Windows) if Windows rejects the event.
48    pub fn write(&self, descriptor: &EventDescriptor, data: &[EventDataDescriptor]) -> Result<()> {
49        self.ctx.write(descriptor, data)
50    }
51}
52
53/// Tracks provider registration and enablement.
54struct EtwContext {
55    registration_handle: REGHANDLE,
56    is_enabled: AtomicU32,
57    level: AtomicU8,
58    match_any_keyword: AtomicU64,
59    match_all_keyword: AtomicU64,
60}
61
62impl EtwContext {
63    fn new() -> Self {
64        EtwContext {
65            registration_handle: 0,
66            is_enabled: AtomicU32::new(0),
67            level: AtomicU8::new(0),
68            match_any_keyword: AtomicU64::new(0),
69            match_all_keyword: AtomicU64::new(0),
70        }
71    }
72
73    /// Registers the provider with the given GUID.
74    ///
75    /// # Safety
76    ///
77    /// The context must remain in the returned [`Box`]. Moving its data would cause the ETW
78    /// callback to access an invalid pointer.
79    fn register(guid: &Guid) -> Result<Box<Self>> {
80        let mut ctx = Box::new(Self::new());
81        let ptr = ctx.as_ref() as *const Self as *const c_void;
82        let mut handle: REGHANDLE = 0;
83        // SAFETY: the crate-owned and generated GUIDs have the same `repr(C)` layout. `ptr` points
84        // to the boxed context, which remains alive until unregistration.
85        let res = unsafe {
86            EventRegister(
87                (guid as *const Guid).cast::<RAW_GUID>(),
88                Some(enable_callback),
89                ptr,
90                &mut handle,
91            )
92        };
93        win32_result(res)?;
94        ctx.registration_handle = handle;
95        Ok(ctx)
96    }
97
98    /// Returns whether the provider is enabled for the specified level and keyword.
99    #[inline]
100    fn enabled(&self, level: u8, keyword: u64) -> bool {
101        if self.is_enabled.load(Ordering::Relaxed) == 0 {
102            return false;
103        }
104        let cur_level = self.level.load(Ordering::Relaxed);
105        let any = self.match_any_keyword.load(Ordering::Relaxed);
106        let all = self.match_all_keyword.load(Ordering::Relaxed);
107        (level <= cur_level || cur_level == 0)
108            && (keyword == 0 || ((keyword & any) != 0 && (keyword & all) == all))
109    }
110
111    /// Writes a single event.
112    fn write(&self, descriptor: &EventDescriptor, data: &[EventDataDescriptor]) -> Result<()> {
113        // SAFETY: `EventDataDescriptor` transparently wraps `EVENT_DATA_DESCRIPTOR`, and the
114        // borrowed payloads outlive this call.
115        let res = unsafe {
116            EventWriteTransfer(
117                self.registration_handle,
118                descriptor,
119                std::ptr::null(),
120                std::ptr::null(),
121                data.len() as u32,
122                data.as_ptr() as *const EVENT_DATA_DESCRIPTOR,
123            )
124        };
125        win32_result(res)
126    }
127}
128
129impl Drop for EtwContext {
130    fn drop(&mut self) {
131        // `EventRegister` needs the context pointer before it returns a handle. If registration
132        // fails, the handle remains zero and must not be passed to `EventUnregister`.
133        if self.registration_handle == 0 {
134            return;
135        }
136
137        // SAFETY: the handle came from a successful `EventRegister` and is unregistered once,
138        // when the sole owning `Box` is dropped.
139        unsafe {
140            let _ = EventUnregister(self.registration_handle);
141        }
142    }
143}
144
145/// Handles an ETW enable or disable notification.
146///
147/// Mutates the context only through atomics to avoid undefined behavior. The callback provides no
148/// ordering guarantees, but a transient read is acceptable for the lightweight enablement check.
149unsafe extern "system" fn enable_callback(
150    _source_id: *const RAW_GUID,
151    is_enabled: u32,
152    level: u8,
153    match_any_keyword: u64,
154    match_all_keyword: u64,
155    _filter_data: *const EVENT_FILTER_DESCRIPTOR,
156    callback_context: *mut c_void,
157) {
158    if callback_context.is_null() {
159        return;
160    }
161    let ctx = unsafe { &*(callback_context as *const EtwContext) };
162
163    match is_enabled {
164        EVENT_CONTROL_CODE_ENABLE_PROVIDER => {
165            ctx.level.store(level, Ordering::Relaxed);
166            ctx.match_any_keyword
167                .store(match_any_keyword, Ordering::Relaxed);
168            ctx.match_all_keyword
169                .store(match_all_keyword, Ordering::Relaxed);
170            ctx.is_enabled
171                .store(EVENT_CONTROL_CODE_ENABLE_PROVIDER, Ordering::Relaxed);
172        }
173        EVENT_CONTROL_CODE_DISABLE_PROVIDER => {
174            ctx.is_enabled
175                .store(EVENT_CONTROL_CODE_DISABLE_PROVIDER, Ordering::Relaxed);
176            ctx.level.store(0, Ordering::Relaxed);
177            ctx.match_any_keyword.store(0, Ordering::Relaxed);
178            ctx.match_all_keyword.store(0, Ordering::Relaxed);
179        }
180        _ => {}
181    }
182}