dbgscope 0.3.0

Typed WinDbg/DbgEng debug sessions, with kernel pool and user heap walkers built on them.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
//! Opt-in KDNET attach experiment. The announcement is observed DbgEng text, not an API contract.
use super::*;
use windows::Win32::System::Diagnostics::Debug::Extensions::{
    DEBUG_STATUS_BREAK, IDebugOutputCallbacksWide, IDebugOutputCallbacksWide_Impl,
};
use windows::core::implement;

impl DebugEngine {
    /// Experimental attach for a known-running KDNET lab target.
    ///
    /// Requests one break upon the English `Connected to target ` output prefix, without
    /// INITIAL_BREAK or the default attach's extra `g`. This text is NOT a Microsoft readiness
    /// contract. Missing/changed output, interruption, and timeout fail without a fallback break.
    /// An unconnected transport may still block indefinitely; use an isolated worker process.
    ///
    /// Call the returned guard's `wait()` immediately. Dropping it restores the previous output
    /// callback but does not cancel the transport claim. Existing output callbacks are forwarded
    /// through DbgEng's wide interface without retaining their text. No reconnect auto-break is armed
    /// after the first announcement. An already-stopped target is not a validated use case.
    pub fn attach_kernel_announcement_begin(
        &self,
        connection_string: &str,
    ) -> Result<PendingTarget<'_>, DbgEngError> {
        if !connection_string
            .as_bytes()
            .get(..4)
            .is_some_and(|p| p.eq_ignore_ascii_case(b"net:"))
        {
            return Err(DbgEngError::ExperimentalKernelAttach(
                "KDNET connection required",
            ));
        }
        let connection =
            CString::new(connection_string).map_err(|_| DbgEngError::InvalidCommand)?;
        let observer = AnnouncementGuard::install(self)?;
        unsafe {
            self.control
                .RemoveEngineOptions(DEBUG_ENGOPT_INITIAL_BREAK)
                .map_err(DbgEngError::CommandFailed)?;
            self.client
                .AttachKernel(
                    DEBUG_ATTACH_KERNEL_CONNECTION,
                    PCSTR(connection.as_ptr().cast()),
                )
                .map_err(DbgEngError::AttachFailed)?;
        }
        self.retain_deferred_input(TargetInput::Ansi(connection));
        self.forget_the_previous_session();
        Ok(PendingTarget::new(
            self,
            WaitKind::KernelAnnouncement(observer),
        ))
    }
}

#[derive(Default)]
struct Notice {
    matched: usize,
    skip_line: bool,
    fired: bool,
}
impl Notice {
    fn feed(&mut self, mask: u32, bytes: &[u8]) -> bool {
        const PREFIX: &[u8] = b"Connected to target ";
        if mask != DEBUG_OUTPUT_NORMAL || self.fired {
            return false;
        }
        for &byte in bytes {
            if byte == b'\n' {
                self.matched = 0;
                self.skip_line = false;
            } else if !self.skip_line {
                if byte == PREFIX[self.matched] {
                    self.matched += 1;
                    if self.matched == PREFIX.len() {
                        self.fired = true;
                        return true;
                    }
                } else {
                    self.matched = 0;
                    self.skip_line = true;
                }
            }
        }
        false
    }
}

#[derive(Default)]
struct Observation {
    notice: Notice,
    requested: Option<HRESULT>,
}

#[implement(IDebugOutputCallbacksWide)]
struct Observer {
    observation: Arc<Mutex<Observation>>,
    control: IDebugControl4,
    previous: Option<IDebugOutputCallbacksWide>,
    previous_mask: u32,
}
impl IDebugOutputCallbacksWide_Impl for Observer_Impl {
    fn Output(&self, mask: u32, text: &PCWSTR) -> windows::core::Result<()> {
        // SAFETY: DbgEng supplies callback text valid until this callback returns.
        let decoded = unsafe { text.to_string() }.unwrap_or_default();
        let fire = self
            .observation
            .lock()
            .unwrap_or_else(|e| e.into_inner())
            .notice
            .feed(mask, decoded.as_bytes());
        if fire {
            // SetInterrupt is documented safe at any time. No wait or other engine call is
            // reentered here; mark the notice fired before this call to reject recursive output.
            let result = unsafe { self.control.SetInterrupt(DEBUG_INTERRUPT_ACTIVE) };
            self.observation
                .lock()
                .unwrap_or_else(|e| e.into_inner())
                .requested = Some(result.err().map_or(S_OK, |e| e.code()));
        }
        if mask & self.previous_mask != 0
            && let Some(previous) = &self.previous
        {
            unsafe { previous.Output(mask, *text) }?;
        }
        Ok(())
    }
}

pub(super) struct AnnouncementGuard<'a> {
    engine: &'a DebugEngine,
    previous: Option<IDebugOutputCallbacksWide>,
    mask: u32,
    observation: Arc<Mutex<Observation>>,
    restored: RefCell<bool>,
}
impl<'a> AnnouncementGuard<'a> {
    fn install(engine: &'a DebugEngine) -> Result<Self, DbgEngError> {
        unsafe {
            // The generated getter treats S_OK + NULL (no callback) as an error. Read the
            // nullable, AddRef-owned COM result through the vtable instead.
            let mut raw = std::ptr::null_mut();
            (engine.client.vtable().GetOutputCallbacksWide)(engine.client.as_raw(), &mut raw)
                .ok()
                .map_err(DbgEngError::CommandFailed)?;
            let previous = (!raw.is_null()).then(|| IDebugOutputCallbacksWide::from_raw(raw));
            let mask = engine
                .client
                .GetOutputMask()
                .map_err(DbgEngError::CommandFailed)?;
            let observation = Arc::new(Mutex::new(Observation::default()));
            let observer: IDebugOutputCallbacksWide = Observer {
                observation: observation.clone(),
                control: engine.control.clone(),
                previous: previous.clone(),
                previous_mask: mask,
            }
            .into();
            let guard = Self {
                engine,
                previous,
                mask,
                observation,
                restored: RefCell::new(false),
            };
            engine
                .client
                .SetOutputMask(mask | DEBUG_OUTPUT_NORMAL)
                .map_err(DbgEngError::CommandFailed)?;
            engine
                .client
                .SetOutputCallbacksWide(&observer)
                .map_err(DbgEngError::CommandFailed)?;
            Ok(guard)
        }
    }

    fn restore(&self) -> Result<(), DbgEngError> {
        if *self.restored.borrow() {
            return Ok(());
        }
        unsafe {
            self.engine
                .client
                .SetOutputCallbacksWide(self.previous.as_ref())
                .map_err(DbgEngError::CommandFailed)?;
            self.engine
                .client
                .SetOutputMask(self.mask)
                .map_err(DbgEngError::CommandFailed)?;
        }
        *self.restored.borrow_mut() = true;
        Ok(())
    }

    pub(super) fn wait(&self) -> Result<(), DbgEngError> {
        self.wait_with_timeout(KERNEL_ATTACH_WAIT_MS)
    }

    fn wait_with_timeout(&self, timeout_ms: u32) -> Result<(), DbgEngError> {
        let operation = self.engine.begin_operation();
        let result = self
            .engine
            .pump(Bound::WatchdogExit(timeout_ms), &operation);
        self.restore()?;
        let observation = self.observation.lock().unwrap_or_else(|e| e.into_inner());
        validate_observation(observation.requested)?;
        if !matches!(result?, WaitOutcome::Stopped { .. }) {
            return Err(DbgEngError::ExperimentalKernelAttach(
                "attach wait was interrupted or expired",
            ));
        }
        if unsafe { self.engine.control.GetExecutionStatus() }
            .map_err(DbgEngError::CommandFailed)?
            != DEBUG_STATUS_BREAK
        {
            return Err(DbgEngError::ExperimentalKernelAttach(
                "target stop was not confirmed",
            ));
        }
        Ok(())
    }
}
impl Drop for AnnouncementGuard<'_> {
    fn drop(&mut self) {
        let _ = self.restore();
    }
}

fn validate_observation(requested: Option<HRESULT>) -> Result<(), DbgEngError> {
    match requested {
        Some(S_OK) => Ok(()),
        Some(_) => Err(DbgEngError::ExperimentalKernelAttach(
            "one-shot interrupt request failed",
        )),
        None => Err(DbgEngError::ExperimentalKernelAttach(
            "connection announcement was not observed",
        )),
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use windows::Win32::System::Diagnostics::Debug::Extensions::DEBUG_OUTPUT_WARNING;

    #[cfg(not(miri))]
    #[implement(IDebugOutputCallbacks)]
    struct AnsiSink(Arc<Mutex<Vec<u32>>>);
    #[cfg(not(miri))]
    impl windows::Win32::System::Diagnostics::Debug::Extensions::IDebugOutputCallbacks_Impl
        for AnsiSink_Impl
    {
        fn Output(&self, mask: u32, _: &PCSTR) -> windows::core::Result<()> {
            self.0.lock().unwrap().push(mask);
            Ok(())
        }
    }

    #[test]
    #[cfg(not(miri))]
    fn test_ansi_callback_is_forwarded_only_its_original_mask_and_restored() {
        let _debuggee = super::super::tests::one_debuggee();
        use windows::Win32::System::Diagnostics::Debug::Extensions::DebugCreate;
        let client: IDebugClient6 = unsafe { DebugCreate().unwrap() };
        let engine = DebugEngine::try_from_client_interface(client.clone()).unwrap();
        let received = Arc::new(Mutex::new(Vec::new()));
        let sink: IDebugOutputCallbacks = AnsiSink(received.clone()).into();
        unsafe {
            client.SetOutputCallbacks(&sink).unwrap();
            client.SetOutputMask(DEBUG_OUTPUT_WARNING).unwrap();
        }
        {
            let _guard = AnnouncementGuard::install(&engine).unwrap();
            let active = unsafe { client.GetOutputCallbacksWide().unwrap() };
            unsafe {
                active
                    .Output(DEBUG_OUTPUT_NORMAL, windows::core::w!("unrelated\n"))
                    .unwrap();
                active
                    .Output(DEBUG_OUTPUT_WARNING, windows::core::w!("warning\n"))
                    .unwrap();
            }
        }
        unsafe {
            client
                .GetOutputCallbacksWide()
                .unwrap()
                .Output(DEBUG_OUTPUT_WARNING, windows::core::w!("after\n"))
                .unwrap();
            client.SetOutputCallbacks(None).unwrap();
        }
        assert_eq!(
            *received.lock().unwrap(),
            vec![DEBUG_OUTPUT_WARNING, DEBUG_OUTPUT_WARNING]
        );
    }

    #[test]
    fn test_notice_chunk_boundaries_and_reconnect_are_one_shot() {
        let prefix = b"Connected to target ";
        for split in 0..=prefix.len() {
            let mut notice = Notice::default();
            let a = notice.feed(DEBUG_OUTPUT_NORMAL, &prefix[..split]);
            let b = notice.feed(DEBUG_OUTPUT_NORMAL, &prefix[split..]);
            assert_eq!(usize::from(a) + usize::from(b), 1);
            assert!(!notice.feed(DEBUG_OUTPUT_NORMAL, b"\nConnected to target "));
            assert!(Notice::default().feed(DEBUG_OUTPUT_NORMAL, prefix));
        }
    }
    #[test]
    fn test_notice_anchoring_masks_and_bounded_state() {
        let mut notice = Notice::default();
        for _ in 0..100_000 {
            assert!(!notice.feed(DEBUG_OUTPUT_NORMAL, b"x"));
        }
        assert!(!notice.feed(
            DEBUG_OUTPUT_NORMAL,
            b"Connected to target \nConnected to nope\nConnected to "
        ));
        assert!(!notice.feed(DEBUG_OUTPUT_WARNING, b"other\nConnected to target "));
        assert!(notice.feed(DEBUG_OUTPUT_NORMAL, b"target "));
    }
    #[test]
    fn test_missing_or_failed_announcement_never_succeeds() {
        assert!(validate_observation(None).is_err());
        assert!(validate_observation(Some(E_FAIL)).is_err());
        assert!(validate_observation(Some(S_OK)).is_ok());
    }

    #[test]
    #[cfg(not(miri))]
    fn test_observer_restores_existing_callback_and_mask_without_a_target() {
        let _debuggee = super::super::tests::one_debuggee();
        use windows::Win32::System::Diagnostics::Debug::Extensions::DebugCreate;
        let client: IDebugClient6 = unsafe { DebugCreate().unwrap() };
        let engine = DebugEngine::try_from_client_interface(client.clone()).unwrap();
        let saved_mask = DEBUG_OUTPUT_WARNING;
        let observation = Arc::new(Mutex::new(Observation::default()));
        let previous: IDebugOutputCallbacksWide = Observer {
            observation,
            control: engine.control.clone(),
            previous: None,
            previous_mask: 0,
        }
        .into();
        unsafe {
            client.SetOutputCallbacksWide(&previous).unwrap();
            client.SetOutputMask(saved_mask).unwrap();
        }
        {
            let guard = AnnouncementGuard::install(&engine).unwrap();
            assert_eq!(
                unsafe { client.GetOutputMask().unwrap() },
                saved_mask | DEBUG_OUTPUT_NORMAL
            );
            assert!(validate_observation(guard.observation.lock().unwrap().requested).is_err());
        }
        unsafe {
            assert_eq!(client.GetOutputCallbacksWide().unwrap(), previous);
            assert_eq!(client.GetOutputMask().unwrap(), saved_mask);
            client.SetOutputCallbacksWide(None).unwrap();
        }
        // Null is a valid prior callback too, and a new attach gets fresh one-shot state.
        AnnouncementGuard::install(&engine)
            .unwrap()
            .restore()
            .unwrap();
        let mut raw = std::ptr::null_mut();
        unsafe {
            (client.vtable().GetOutputCallbacksWide)(client.as_raw(), &mut raw)
                .ok()
                .unwrap()
        };
        assert!(raw.is_null());
    }

    #[test]
    #[cfg(not(miri))]
    fn test_missing_announcement_deadline_fails_and_restores_the_callback() {
        let _debuggee = super::super::tests::one_debuggee();
        let engine = DebugEngine::new();
        engine
            .launch_process("ping.exe -n 30 127.0.0.1")
            .expect("launch failed");
        let received = Arc::new(Mutex::new(Vec::new()));
        let sink: IDebugOutputCallbacks = AnsiSink(received.clone()).into();
        unsafe {
            engine.client.SetOutputCallbacks(&sink).unwrap();
            engine.client.SetOutputMask(DEBUG_OUTPUT_WARNING).unwrap();
            engine.control.SetExecutionStatus(DEBUG_STATUS_GO).unwrap();
        }
        let guard = AnnouncementGuard::install(&engine).unwrap();
        let result = guard.wait_with_timeout(100);
        assert!(matches!(
            result,
            Err(DbgEngError::ExperimentalKernelAttach(
                "connection announcement was not observed"
            ))
        ));
        assert_eq!(guard.observation.lock().unwrap().requested, None);
        assert!(
            *guard.restored.borrow(),
            "restore must happen before guard drop"
        );
        unsafe {
            assert_eq!(engine.client.GetOutputMask().unwrap(), DEBUG_OUTPUT_WARNING);
            engine
                .client
                .GetOutputCallbacksWide()
                .unwrap()
                .Output(DEBUG_OUTPUT_WARNING, windows::core::w!("after deadline\n"))
                .unwrap();
        }
        assert_eq!(received.lock().unwrap().last(), Some(&DEBUG_OUTPUT_WARNING));
        drop(guard);
        engine.end_session().expect("test process cleanup failed");
    }
}