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 windows::Win32::Foundation::WIN32_ERROR;
7use windows::Win32::System::Diagnostics::Etw::{
8    ENABLECALLBACK_ENABLED_STATE, EVENT_CONTROL_CODE_DISABLE_PROVIDER,
9    EVENT_CONTROL_CODE_ENABLE_PROVIDER, EVENT_FILTER_DESCRIPTOR, EventRegister, EventUnregister,
10    EventWriteTransfer, REGHANDLE,
11};
12
13use crate::field::EventDataDescriptor;
14use crate::{EVENT_DATA_DESCRIPTOR, EVENT_DESCRIPTOR, GUID, Result};
15
16/// A registered ETW provider.
17///
18/// The provider is unregistered when this is dropped.
19pub struct EtwLogger {
20    ctx: Box<EtwContext>,
21}
22
23impl EtwLogger {
24    /// Registers the provider with the given GUID.
25    pub fn register(guid: &GUID) -> Result<Self> {
26        Ok(EtwLogger {
27            ctx: EtwContext::register(guid)?,
28        })
29    }
30
31    /// Returns whether the provider is enabled for the specified level and keyword.
32    #[inline]
33    pub fn enabled(&self, level: u8, keyword: u64) -> bool {
34        self.ctx.enabled(level, keyword)
35    }
36
37    /// Writes a single event.
38    pub fn write(&self, descriptor: &EVENT_DESCRIPTOR, data: &[EventDataDescriptor]) -> Result<()> {
39        self.ctx.write(descriptor, data)
40    }
41}
42
43/// Tracks provider registration and enablement.
44struct EtwContext {
45    registration_handle: REGHANDLE,
46    is_enabled: AtomicU32,
47    level: AtomicU8,
48    match_any_keyword: AtomicU64,
49    match_all_keyword: AtomicU64,
50}
51
52impl EtwContext {
53    fn new() -> Self {
54        EtwContext {
55            registration_handle: REGHANDLE::default(),
56            is_enabled: AtomicU32::new(0),
57            level: AtomicU8::new(0),
58            match_any_keyword: AtomicU64::new(0),
59            match_all_keyword: AtomicU64::new(0),
60        }
61    }
62
63    /// Registers the provider with the given GUID.
64    ///
65    /// # Safety
66    ///
67    /// The context must remain in the returned [`Box`]. Moving its data would cause the ETW
68    /// callback to access an invalid pointer.
69    fn register(guid: &GUID) -> Result<Box<Self>> {
70        let mut ctx = Box::new(Self::new());
71        let ptr = ctx.as_ref() as *const Self as *const c_void;
72        let mut handle = REGHANDLE::default();
73        // SAFETY, ptr points to the boxed context kept alive until unregistration
74        let res = unsafe { EventRegister(guid, Some(enable_callback), Some(ptr), &mut handle) };
75        WIN32_ERROR(res).ok()?;
76        ctx.registration_handle = handle;
77        Ok(ctx)
78    }
79
80    /// Returns whether the provider is enabled for the specified level and keyword.
81    #[inline]
82    fn enabled(&self, level: u8, keyword: u64) -> bool {
83        if self.is_enabled.load(Ordering::Relaxed) == 0 {
84            return false;
85        }
86        let cur_level = self.level.load(Ordering::Relaxed);
87        let any = self.match_any_keyword.load(Ordering::Relaxed);
88        let all = self.match_all_keyword.load(Ordering::Relaxed);
89        (level <= cur_level || cur_level == 0)
90            && (keyword == 0 || ((keyword & any) != 0 && (keyword & all) == all))
91    }
92
93    /// Writes a single event.
94    fn write(&self, descriptor: &EVENT_DESCRIPTOR, data: &[EventDataDescriptor]) -> Result<()> {
95        // SAFETY, EventDataDescriptor transparently wraps EVENT_DATA_DESCRIPTOR
96        let data_raw = unsafe {
97            std::slice::from_raw_parts(data.as_ptr() as *const EVENT_DATA_DESCRIPTOR, data.len())
98        };
99
100        // SAFETY, data outlives the call
101        let res = unsafe {
102            EventWriteTransfer(
103                self.registration_handle,
104                descriptor,
105                None,
106                None,
107                Some(data_raw),
108            )
109        };
110        WIN32_ERROR(res).ok()
111    }
112}
113
114impl Drop for EtwContext {
115    fn drop(&mut self) {
116        unsafe {
117            let _ = EventUnregister(self.registration_handle);
118        }
119    }
120}
121
122/// Handles an ETW enable or disable notification.
123///
124/// Mutates the context only through atomics to avoid undefined behavior. The callback provides no
125/// ordering guarantees, but a transient read is acceptable for the lightweight enablement check.
126unsafe extern "system" fn enable_callback(
127    _source_id: *const GUID,
128    is_enabled: ENABLECALLBACK_ENABLED_STATE,
129    level: u8,
130    match_any_keyword: u64,
131    match_all_keyword: u64,
132    _filter_data: *const EVENT_FILTER_DESCRIPTOR,
133    callback_context: *mut c_void,
134) {
135    if callback_context.is_null() {
136        return;
137    }
138    let ctx = unsafe { &*(callback_context as *const EtwContext) };
139
140    match is_enabled {
141        EVENT_CONTROL_CODE_ENABLE_PROVIDER => {
142            ctx.level.store(level, Ordering::Relaxed);
143            ctx.match_any_keyword
144                .store(match_any_keyword, Ordering::Relaxed);
145            ctx.match_all_keyword
146                .store(match_all_keyword, Ordering::Relaxed);
147            ctx.is_enabled
148                .store(EVENT_CONTROL_CODE_ENABLE_PROVIDER.0, Ordering::Relaxed);
149        }
150        EVENT_CONTROL_CODE_DISABLE_PROVIDER => {
151            ctx.is_enabled
152                .store(EVENT_CONTROL_CODE_DISABLE_PROVIDER.0, Ordering::Relaxed);
153            ctx.level.store(0, Ordering::Relaxed);
154            ctx.match_any_keyword.store(0, Ordering::Relaxed);
155            ctx.match_all_keyword.store(0, Ordering::Relaxed);
156        }
157        _ => {}
158    }
159}