mxc-sdk 1.0.1

Importable library for starting MXC sandboxes in-process, with streaming stdio.
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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! Windows runtime FFI for the `processmodel.dll` Learning Mode trace exports.
//!
//! Availability is gated by `IsApiSetImplemented` for the Learning Mode trace
//! API set. The option-aware start export is preferred; the legacy access-only
//! start export is accepted when it is unavailable. Stop and Close remain
//! required for either start path.
//! `processmodel.dll` is intentionally never freed: it is a system DLL that
//! stays resident for the process lifetime, so the module handle is used only to
//! resolve exports and then dropped without `FreeLibrary`.

use std::path::Path;
use std::ptr;
use std::sync::OnceLock;
use std::time::Duration;

use crate::mxc_common::api_set::is_api_set_implemented;
use crate::mxc_common::string_util;
use windows::Win32::Foundation::{
    GetLastError, ERROR_BUSY, ERROR_LOCK_VIOLATION, ERROR_RETRY, ERROR_SHARING_VIOLATION, HANDLE,
};
use windows::Win32::System::LibraryLoader::{
    GetProcAddress, LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32,
};
use windows_core::{HRESULT, PCSTR, PCWSTR};

use crate::learning_mode_windows::LearningModeError;

/// System DLL that hosts the flat Learning Mode trace exports.
const PROCESSMODEL_DLL: &str = "processmodel.dll";
/// API-set contract for the Learning Mode trace exports.
pub const LEARNING_MODE_API_SET: &core::ffi::CStr =
    c"api-win-appmodel-processmodel~learningmodetrace";

/// `LEARNING_MODE_TRACE_SOURCE_OPTIONS` is a C enum used as a bitmask.
type LearningModeTraceSourceOptions = i32;

const LEARNING_MODE_TRACE_SOURCE_OPTION_ACCESS: LearningModeTraceSourceOptions = 0x1;
const LEARNING_MODE_TRACE_SOURCE_OPTION_NETWORK: LearningModeTraceSourceOptions = 0x2;
const REQUIRED_TRACE_SOURCE_OPTIONS: LearningModeTraceSourceOptions =
    LEARNING_MODE_TRACE_SOURCE_OPTION_ACCESS | LEARNING_MODE_TRACE_SOURCE_OPTION_NETWORK;

/// `HRESULT StartLearningModeTraceWithOptions(HANDLE securityEnvironment,
/// LEARNING_MODE_TRACE_SOURCE_OPTIONS options, HLEARNINGMODE_TRACE* trace)`.
type PfnStartLearningModeTraceWithOptions = unsafe extern "system" fn(
    process_security_environment: HANDLE,
    options: LearningModeTraceSourceOptions,
    trace_out: *mut HANDLE,
) -> HRESULT;

/// `HRESULT StartLearningModeTrace(HANDLE securityEnvironment, HLEARNINGMODE_TRACE* trace)`.
///
/// `HLEARNINGMODE_TRACE` is a `typedef HANDLE`; the export surfaces it through the
/// out-parameter.
type PfnStartLearningModeTrace = unsafe extern "system" fn(
    process_security_environment: HANDLE,
    trace_out: *mut HANDLE,
) -> HRESULT;

#[derive(Clone, Copy)]
enum LearningModeStart {
    WithOptions(PfnStartLearningModeTraceWithOptions),
    Legacy(PfnStartLearningModeTrace),
}

impl LearningModeStart {
    fn name(self) -> &'static str {
        match self {
            Self::WithOptions(_) => "StartLearningModeTraceWithOptions",
            Self::Legacy(_) => "StartLearningModeTrace",
        }
    }

    fn sources(self) -> LearningModeTraceSources {
        match self {
            Self::WithOptions(_) => LearningModeTraceSources::AccessAndNetwork,
            Self::Legacy(_) => LearningModeTraceSources::AccessOnly,
        }
    }
}

/// Event sources collected by a successfully started Learning Mode trace.
///
/// Legacy hosts collect access events only. Hosts exposing the option-aware
/// start export collect both access and network events.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LearningModeTraceSources {
    /// The legacy trace contains access events but no network decisions.
    AccessOnly,
    /// The option-aware trace contains access and network events.
    AccessAndNetwork,
}

impl LearningModeTraceSources {
    /// Whether the trace includes network decision events.
    #[must_use]
    pub fn includes_network(self) -> bool {
        matches!(self, Self::AccessAndNetwork)
    }
}

/// `HRESULT StopLearningModeTrace(HLEARNINGMODE_TRACE trace, LPCWSTR outputEtlPath)`.
///
/// A non-null `output_path` names a file the export opens under the caller's own
/// identity; the broker seals and copies the ETL into it. A null `output_path`
/// stops without delivery. The handle remains valid so the caller may retry
/// delivery until it closes the trace.
type PfnStopLearningModeTrace =
    unsafe extern "system" fn(trace: HANDLE, output_path: *const u16) -> HRESULT;

/// `void CloseLearningModeTrace(HLEARNINGMODE_TRACE trace)`.
type PfnCloseLearningModeTrace = unsafe extern "system" fn(trace: HANDLE);
type RawExport = unsafe extern "system" fn() -> isize;

/// Opaque handle to an in-progress Learning Mode trace (`HLEARNINGMODE_TRACE`).
///
/// Obtained from [`start_trace`] or [`LearningModeApi::start_trace`]. The handle
/// owns the stop and close entry points needed for the remainder of its lifecycle.
/// Dropping or explicitly closing it releases all broker state; closing without
/// stopping discards the trace.
pub struct LearningModeTraceHandle {
    raw: HANDLE,
    stop: PfnStopLearningModeTrace,
    close: PfnCloseLearningModeTrace,
    sources: LearningModeTraceSources,
}

impl LearningModeTraceHandle {
    const STOP_DELIVERY_ATTEMPTS: usize = 3;
    const STOP_RETRY_DELAYS: [Duration; 2] = [Duration::from_millis(25), Duration::from_millis(75)];

    fn new(
        raw: HANDLE,
        stop: PfnStopLearningModeTrace,
        close: PfnCloseLearningModeTrace,
        sources: LearningModeTraceSources,
    ) -> Self {
        Self {
            raw,
            stop,
            close,
            sources,
        }
    }

    /// Event sources collected by this trace.
    #[must_use]
    pub fn sources(&self) -> LearningModeTraceSources {
        self.sources
    }

    /// Stop the trace, sealing and copying the ETL into `output_path`. Passing
    /// `None` stops without delivery.
    pub fn stop(&self, output_path: Option<&Path>) -> Result<(), LearningModeError> {
        let wide_path = encode_output_path(output_path)?;
        let path_ptr = wide_path
            .as_deref()
            .map_or(ptr::null(), |path| path.as_ptr());

        // SAFETY: `stop` was resolved from the same API surface that created
        // `raw`; `path_ptr` is null or points to a live null-terminated buffer.
        let result = unsafe { (self.stop)(self.raw, path_ptr) };
        if result.is_err() {
            return Err(LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code: result.0,
            });
        }
        Ok(())
    }

    /// Stop and deliver the trace, retrying transient output-delivery failures.
    pub fn stop_with_retry(&self, output_path: Option<&Path>) -> Result<(), LearningModeError> {
        for attempt in 0..Self::STOP_DELIVERY_ATTEMPTS {
            match self.stop(output_path) {
                Err(error)
                    if attempt + 1 < Self::STOP_DELIVERY_ATTEMPTS
                        && is_retryable_stop_error(&error) =>
                {
                    std::thread::sleep(Self::STOP_RETRY_DELAYS[attempt]);
                }
                result => return result,
            }
        }
        unreachable!("STOP_DELIVERY_ATTEMPTS is non-zero")
    }

    /// Close the trace and release all service-managed state.
    pub fn close(mut self) {
        self.close_inner();
    }

    fn close_inner(&mut self) {
        if !self.raw.0.is_null() {
            // SAFETY: `raw` was returned by one of the supported start exports,
            // and `close` was resolved from the same processmodel.dll contract.
            unsafe { (self.close)(self.raw) };
            self.raw = HANDLE(ptr::null_mut());
        }
    }
}

impl std::fmt::Debug for LearningModeTraceHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("LearningModeTraceHandle")
            .field(&self.raw)
            .field(&self.sources)
            .finish()
    }
}

impl Drop for LearningModeTraceHandle {
    fn drop(&mut self) {
        self.close_inner();
    }
}

/// Resolved Learning Mode trace exports from `processmodel.dll`.
///
/// Construct with [`LearningModeApi::load`]. Cloning is cheap (the struct holds three
/// function pointers into the resident system DLL).
#[derive(Clone, Copy)]
pub struct LearningModeApi {
    start: LearningModeStart,
    stop: PfnStopLearningModeTrace,
    close: PfnCloseLearningModeTrace,
}

impl std::fmt::Debug for LearningModeApi {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("LearningModeApi")
            .field("start", &self.start.name())
            .field("stop", &(self.stop as *const ()))
            .field("close", &(self.close as *const ()))
            .finish()
    }
}

impl LearningModeApi {
    /// Load `processmodel.dll` and resolve the Learning Mode trace exports.
    ///
    /// The result — success or failure — is memoized for the lifetime of the
    /// process: `processmodel.dll` is a resident system DLL whose export set does
    /// not change while the process runs, so repeated probes would only repeat the
    /// same `LoadLibraryExW`/`GetProcAddress` work and return the same answer. The
    /// cached error is cloned (see [`LearningModeError`]), preserving the original
    /// diagnostic on every call.
    ///
    /// # Errors
    /// - [`LearningModeError::ApiSetUnavailable`] if Windows does not implement
    ///   the Learning Mode trace API-set contract.
    /// - [`LearningModeError::DllLoad`] if `processmodel.dll` cannot be loaded.
    /// - [`LearningModeError::ExportMissing`] if neither compatible start export
    ///   is available, or if Stop/Close is absent. Requiring
    ///   `CloseLearningModeTrace` rejects builds that expose the incompatible
    ///   earlier two-export ABI.
    pub fn load() -> Result<Self, LearningModeError> {
        static CACHE: OnceLock<Result<LearningModeApi, LearningModeError>> = OnceLock::new();
        CACHE.get_or_init(Self::load_uncached).clone()
    }

    /// Perform the actual DLL load and export resolution, bypassing the cache.
    fn load_uncached() -> Result<Self, LearningModeError> {
        if !is_api_set_implemented(LEARNING_MODE_API_SET) {
            return Err(LearningModeError::ApiSetUnavailable {
                api: "Learning Mode trace",
                api_set: LEARNING_MODE_API_SET
                    .to_str()
                    .expect("API-set contract names must be UTF-8"),
            });
        }

        let dll = string_util::to_wide(PROCESSMODEL_DLL);

        // SAFETY: `dll` is a valid null-terminated wide string that outlives the call.
        // `LOAD_LIBRARY_SEARCH_SYSTEM32` restricts the search to System32, preventing
        // DLL-planting. The module handle is used only for `GetProcAddress` below and
        // is never freed (the DLL stays resident for the process lifetime). Each
        // resolved pointer is transmuted to a signature that matches the C
        // declaration of the corresponding export exactly.
        unsafe {
            let hmodule = LoadLibraryExW(PCWSTR(dll.as_ptr()), None, LOAD_LIBRARY_SEARCH_SYSTEM32)
                .map_err(|e| LearningModeError::DllLoad(e.to_string()))?;

            let mut lookup = |name: &'static std::ffi::CStr| {
                GetProcAddress(hmodule, PCSTR(name.as_ptr().cast()))
            };
            select_learning_mode_exports(&mut lookup, last_error)
        }
    }

    /// Construct an API surface directly from raw export pointers, bypassing the
    /// DLL load. Test-only: lets dependent backend crates inject fakes without
    /// going through the memoized [`load`](Self::load) path, so fakes never
    /// populate the process cache.
    #[cfg(any(test, feature = "test-support"))]
    #[doc(hidden)]
    pub fn from_raw_parts(
        start: PfnStartLearningModeTrace,
        stop: PfnStopLearningModeTrace,
        close: PfnCloseLearningModeTrace,
    ) -> Self {
        Self {
            start: LearningModeStart::Legacy(start),
            stop,
            close,
        }
    }

    /// Construct an option-aware API surface directly from raw export pointers.
    #[cfg(any(test, feature = "test-support"))]
    #[doc(hidden)]
    pub fn from_options_raw_parts(
        start: PfnStartLearningModeTraceWithOptions,
        stop: PfnStopLearningModeTrace,
        close: PfnCloseLearningModeTrace,
    ) -> Self {
        Self {
            start: LearningModeStart::WithOptions(start),
            stop,
            close,
        }
    }

    /// Event sources that traces started through this API will collect.
    #[must_use]
    pub fn trace_sources(&self) -> LearningModeTraceSources {
        self.start.sources()
    }

    /// Start a Learning Mode trace for the sandbox identified by
    /// `security_environment`.
    ///
    /// # Safety
    /// `security_environment` must be a live `HPROCESS_SECURITY_ENVIRONMENT` handle
    /// obtained from the sandbox launch path; the broker resolves it to the target
    /// AppContainer SID server-side.
    ///
    /// # Errors
    /// [`LearningModeError::HResultCall`] if the export returns a failing HRESULT.
    pub unsafe fn start_trace(
        &self,
        security_environment: HANDLE,
    ) -> Result<LearningModeTraceHandle, LearningModeError> {
        let mut trace = HANDLE(ptr::null_mut());
        // SAFETY: `self.start` contains a function pointer resolved from the matching
        // `processmodel.dll` export; `trace` is a valid out-pointer. The caller
        // upholds the validity of `security_environment` per this method's safety
        // contract.
        let result = match self.start {
            LearningModeStart::WithOptions(start) => start(
                security_environment,
                REQUIRED_TRACE_SOURCE_OPTIONS,
                &mut trace,
            ),
            LearningModeStart::Legacy(start) => start(security_environment, &mut trace),
        };
        let function = self.start.name();
        if result.is_err() {
            return Err(LearningModeError::HResultCall {
                function,
                code: result.0,
            });
        }
        if trace.0.is_null() {
            return Err(LearningModeError::HResultCall {
                function,
                code: windows::Win32::Foundation::E_UNEXPECTED.0,
            });
        }
        Ok(LearningModeTraceHandle::new(
            trace,
            self.stop,
            self.close,
            self.start.sources(),
        ))
    }

    /// Stop `trace`, sealing and copying the ETL into `output_path`. Passing `None`
    /// stops without delivery.
    ///
    /// The handle remains live after success or failure, so callers may retry with
    /// the same or a different output path before closing it.
    ///
    /// # Errors
    /// - [`LearningModeError::InvalidInput`] if `output_path` contains an embedded NUL.
    /// - [`LearningModeError::HResultCall`] if the export returns a failing HRESULT.
    pub fn stop_trace(
        &self,
        trace: &LearningModeTraceHandle,
        output_path: Option<&Path>,
    ) -> Result<(), LearningModeError> {
        trace.stop(output_path)
    }

    /// Stop and deliver the trace, retrying only transient output-delivery
    /// failures. The trace remains live throughout the attempts and is still
    /// owned by the caller when this method returns.
    pub fn stop_trace_with_retry(
        &self,
        trace: &LearningModeTraceHandle,
        output_path: Option<&Path>,
    ) -> Result<(), LearningModeError> {
        trace.stop_with_retry(output_path)
    }
}

/// Load the Learning Mode API and start a trace for `security_environment`.
///
/// # Safety
/// `security_environment` must be a live `HPROCESS_SECURITY_ENVIRONMENT`.
pub unsafe fn start_trace(
    security_environment: HANDLE,
) -> Result<LearningModeTraceHandle, LearningModeError> {
    LearningModeApi::load()?.start_trace(security_environment)
}

fn is_retryable_stop_error(error: &LearningModeError) -> bool {
    let LearningModeError::HResultCall {
        function: "StopLearningModeTrace",
        code,
    } = error
    else {
        return false;
    };

    [
        ERROR_SHARING_VIOLATION,
        ERROR_LOCK_VIOLATION,
        ERROR_BUSY,
        ERROR_RETRY,
    ]
    .into_iter()
    .any(|win32| *code == HRESULT::from_win32(win32.0).0)
}

fn encode_output_path(output_path: Option<&Path>) -> Result<Option<Vec<u16>>, LearningModeError> {
    output_path
        .map(|path| {
            string_util::os_str_to_wide(path.as_os_str()).map_err(|_| {
                LearningModeError::InvalidInput {
                    parameter: "output_path",
                    detail: "path contains an embedded NUL".to_string(),
                }
            })
        })
        .transpose()
}

/// Select the preferred compatible Learning Mode ABI from an export lookup.
///
/// # Safety
/// Every non-null procedure returned by `lookup` must have the signature
/// associated with its requested export name.
unsafe fn select_learning_mode_exports(
    lookup: &mut impl FnMut(&'static std::ffi::CStr) -> Option<RawExport>,
    get_last_error: impl Fn() -> u32,
) -> Result<LearningModeApi, LearningModeError> {
    let start = match lookup(START_WITH_OPTIONS_NAME) {
        Some(proc) => {
            let start_with_options: PfnStartLearningModeTraceWithOptions =
                unsafe { std::mem::transmute(proc) };
            LearningModeStart::WithOptions(start_with_options)
        }
        None => {
            let Some(legacy) = lookup(START_NAME) else {
                return Err(LearningModeError::ExportMissing {
                    api: "Learning Mode trace",
                    export: START_EXPORTS_DESCRIPTION,
                    detail: format!(
                        "GetProcAddress returned NULL for both compatible start exports \
                         (final legacy lookup GetLastError = {})",
                        get_last_error()
                    ),
                });
            };
            LearningModeStart::Legacy(unsafe {
                std::mem::transmute::<RawExport, PfnStartLearningModeTrace>(legacy)
            })
        }
    };
    let stop: PfnStopLearningModeTrace = unsafe {
        std::mem::transmute(resolve_required_export(lookup, STOP_NAME, &get_last_error)?)
    };
    let close: PfnCloseLearningModeTrace = unsafe {
        std::mem::transmute(resolve_required_export(
            lookup,
            CLOSE_NAME,
            &get_last_error,
        )?)
    };

    Ok(LearningModeApi { start, stop, close })
}

fn resolve_required_export(
    lookup: &mut impl FnMut(&'static std::ffi::CStr) -> Option<RawExport>,
    name: &'static std::ffi::CStr,
    get_last_error: &impl Fn() -> u32,
) -> Result<RawExport, LearningModeError> {
    match lookup(name) {
        Some(proc) => Ok(proc),
        None => Err(LearningModeError::ExportMissing {
            api: "Learning Mode trace",
            export: name.to_str().unwrap_or("<non-utf8 export>"),
            detail: format!(
                "GetProcAddress returned NULL (GetLastError = {})",
                get_last_error()
            ),
        }),
    }
}

/// Capture `GetLastError` as a plain `u32`.
fn last_error() -> u32 {
    // SAFETY: `GetLastError` has no preconditions and no side effects beyond reading
    // the calling thread's last-error slot.
    unsafe { GetLastError().0 }
}

/// Undecorated names used to select the preferred start ABI and the required
/// Stop/Close lifecycle exports.
const START_WITH_OPTIONS_NAME: &core::ffi::CStr = c"StartLearningModeTraceWithOptions";
const START_NAME: &core::ffi::CStr = c"StartLearningModeTrace";
const START_EXPORTS_DESCRIPTION: &str =
    "StartLearningModeTraceWithOptions or StartLearningModeTrace";
const STOP_NAME: &core::ffi::CStr = c"StopLearningModeTrace";
const CLOSE_NAME: &core::ffi::CStr = c"CloseLearningModeTrace";

/// Read-only capability probe for the Learning Mode trace API-set contract.
#[must_use]
pub fn is_learning_mode_api_available() -> bool {
    is_api_set_implemented(LEARNING_MODE_API_SET)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::ffi::OsString;
    use std::os::windows::ffi::OsStringExt;
    use std::path::PathBuf;
    use std::sync::atomic::{AtomicBool, AtomicI32, AtomicUsize, Ordering};
    use std::sync::Mutex;
    use windows::Win32::Foundation::{E_FAIL, S_FALSE, S_OK};

    static TEST_LOCK: Mutex<()> = Mutex::new(());
    static START_RESULT: AtomicI32 = AtomicI32::new(S_OK.0);
    static START_CALLS: AtomicUsize = AtomicUsize::new(0);
    static WRITE_START_HANDLE: AtomicBool = AtomicBool::new(true);
    static START_OPTIONS: AtomicI32 = AtomicI32::new(0);
    static STOP_RESULT: AtomicI32 = AtomicI32::new(S_OK.0);
    static STOP_FAILURE_RESULT: AtomicI32 = AtomicI32::new(E_FAIL.0);
    static STOP_FAILURES_REMAINING: AtomicUsize = AtomicUsize::new(0);
    static STOP_CALLS: AtomicUsize = AtomicUsize::new(0);
    static CLOSE_CALLS: AtomicUsize = AtomicUsize::new(0);

    unsafe extern "system" fn fake_start(_: HANDLE, trace_out: *mut HANDLE) -> HRESULT {
        START_CALLS.fetch_add(1, Ordering::SeqCst);
        let result = HRESULT(START_RESULT.load(Ordering::SeqCst));
        if result.is_ok() && WRITE_START_HANDLE.load(Ordering::SeqCst) {
            unsafe {
                *trace_out = HANDLE(std::ptr::dangling_mut::<std::ffi::c_void>());
            }
        }
        result
    }

    unsafe extern "system" fn fake_start_with_options(
        _: HANDLE,
        options: LearningModeTraceSourceOptions,
        trace_out: *mut HANDLE,
    ) -> HRESULT {
        START_CALLS.fetch_add(1, Ordering::SeqCst);
        START_OPTIONS.store(options, Ordering::SeqCst);
        let result = HRESULT(START_RESULT.load(Ordering::SeqCst));
        if result.is_ok() && WRITE_START_HANDLE.load(Ordering::SeqCst) {
            unsafe {
                *trace_out = HANDLE(std::ptr::dangling_mut::<std::ffi::c_void>());
            }
        }
        result
    }

    unsafe extern "system" fn fake_stop(_: HANDLE, _: *const u16) -> HRESULT {
        STOP_CALLS.fetch_add(1, Ordering::SeqCst);
        if STOP_FAILURES_REMAINING
            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |remaining| {
                remaining.checked_sub(1)
            })
            .is_ok()
        {
            return HRESULT(STOP_FAILURE_RESULT.load(Ordering::SeqCst));
        }
        HRESULT(STOP_RESULT.load(Ordering::SeqCst))
    }

    unsafe extern "system" fn fake_close(_: HANDLE) {
        CLOSE_CALLS.fetch_add(1, Ordering::SeqCst);
    }

    fn fake_api() -> LearningModeApi {
        LearningModeApi::from_raw_parts(fake_start, fake_stop, fake_close)
    }

    fn fake_options_api() -> LearningModeApi {
        LearningModeApi::from_options_raw_parts(fake_start_with_options, fake_stop, fake_close)
    }

    fn fake_environment() -> HANDLE {
        HANDLE(std::ptr::dangling_mut::<std::ffi::c_void>())
    }

    fn reset_fakes() {
        START_RESULT.store(S_OK.0, Ordering::SeqCst);
        START_CALLS.store(0, Ordering::SeqCst);
        WRITE_START_HANDLE.store(true, Ordering::SeqCst);
        START_OPTIONS.store(0, Ordering::SeqCst);
        STOP_RESULT.store(S_OK.0, Ordering::SeqCst);
        STOP_FAILURE_RESULT.store(E_FAIL.0, Ordering::SeqCst);
        STOP_FAILURES_REMAINING.store(0, Ordering::SeqCst);
        STOP_CALLS.store(0, Ordering::SeqCst);
        CLOSE_CALLS.store(0, Ordering::SeqCst);
    }

    fn select_from_exports(
        available: &[&'static std::ffi::CStr],
    ) -> Result<LearningModeApi, LearningModeError> {
        let mut lookup = |name: &'static std::ffi::CStr| {
            available.contains(&name).then(|| {
                // SAFETY: Each fake is converted only for its matching export name;
                // selection converts it back to that export's declared signature.
                unsafe {
                    if name == START_WITH_OPTIONS_NAME {
                        std::mem::transmute::<PfnStartLearningModeTraceWithOptions, RawExport>(
                            fake_start_with_options,
                        )
                    } else if name == START_NAME {
                        std::mem::transmute::<PfnStartLearningModeTrace, RawExport>(fake_start)
                    } else if name == STOP_NAME {
                        std::mem::transmute::<PfnStopLearningModeTrace, RawExport>(fake_stop)
                    } else if name == CLOSE_NAME {
                        std::mem::transmute::<PfnCloseLearningModeTrace, RawExport>(fake_close)
                    } else {
                        unreachable!("selection requests only known export names")
                    }
                }
            })
        };
        // SAFETY: The lookup returns the correctly typed fake for every known name.
        unsafe { select_learning_mode_exports(&mut lookup, || 127) }
    }

    #[test]
    fn export_selection_prefers_option_aware_start_without_requiring_legacy() {
        for available in [
            vec![START_WITH_OPTIONS_NAME, STOP_NAME, CLOSE_NAME],
            vec![START_WITH_OPTIONS_NAME, START_NAME, STOP_NAME, CLOSE_NAME],
        ] {
            let api = select_from_exports(&available)
                .expect("the preferred ABI should work with or without legacy start");

            assert_eq!(api.start.name(), "StartLearningModeTraceWithOptions");
            assert_eq!(
                api.trace_sources(),
                LearningModeTraceSources::AccessAndNetwork
            );
        }
    }

    #[test]
    fn export_selection_falls_back_only_when_option_aware_start_is_absent() {
        let api = select_from_exports(&[START_NAME, STOP_NAME, CLOSE_NAME])
            .expect("the complete legacy ABI should remain supported");

        assert_eq!(api.start.name(), "StartLearningModeTrace");
        assert_eq!(api.trace_sources(), LearningModeTraceSources::AccessOnly);
    }

    #[test]
    fn selected_export_pointers_drive_the_full_lifecycle() {
        let _guard = TEST_LOCK.lock().unwrap();
        for (available, expected_sources, expected_options) in [
            (
                vec![START_WITH_OPTIONS_NAME, STOP_NAME, CLOSE_NAME],
                LearningModeTraceSources::AccessAndNetwork,
                REQUIRED_TRACE_SOURCE_OPTIONS,
            ),
            (
                vec![START_NAME, STOP_NAME, CLOSE_NAME],
                LearningModeTraceSources::AccessOnly,
                0,
            ),
        ] {
            reset_fakes();
            let api = select_from_exports(&available).expect("complete ABI should be selected");
            let trace = unsafe {
                api.start_trace(fake_environment())
                    .expect("selected start pointer should succeed")
            };

            assert_eq!(trace.sources(), expected_sources);
            assert_eq!(START_CALLS.load(Ordering::SeqCst), 1);
            assert_eq!(START_OPTIONS.load(Ordering::SeqCst), expected_options);

            api.stop_trace(&trace, None)
                .expect("selected stop pointer should succeed");
            trace.close();
            assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 1);
            assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
        }
    }

    #[test]
    fn export_selection_rejects_missing_required_lifecycle_exports() {
        for (available, expected_missing) in [
            (
                vec![START_WITH_OPTIONS_NAME, CLOSE_NAME],
                "StopLearningModeTrace",
            ),
            (
                vec![START_WITH_OPTIONS_NAME, STOP_NAME],
                "CloseLearningModeTrace",
            ),
            (vec![START_NAME, CLOSE_NAME], "StopLearningModeTrace"),
            (vec![START_NAME, STOP_NAME], "CloseLearningModeTrace"),
            (vec![STOP_NAME, CLOSE_NAME], START_EXPORTS_DESCRIPTION),
        ] {
            let error = select_from_exports(&available).expect_err("ABI must be incomplete");
            assert!(matches!(
                &error,
                LearningModeError::ExportMissing { export, .. } if *export == expected_missing
            ));
            if expected_missing == START_EXPORTS_DESCRIPTION {
                let message = error.to_string();
                assert!(message.contains("StartLearningModeTraceWithOptions"));
                assert!(message.contains("StartLearningModeTrace"));
                assert!(message.contains("final legacy lookup GetLastError = 127"));
            }
        }
    }

    #[test]
    fn api_set_probe_does_not_panic() {
        let available = is_learning_mode_api_available();
        if !available {
            assert!(matches!(
                LearningModeApi::load(),
                Err(LearningModeError::ApiSetUnavailable { .. })
            ));
        }
    }

    #[test]
    fn load_failure_is_graceful_when_api_absent() {
        // Where the API is unavailable, `load()` must return a typed error rather
        // than panicking. Where it is available this is vacuously satisfied.
        match LearningModeApi::load() {
            Ok(api) => {
                // Smoke: the resolved struct is Debug-formattable.
                let _ = format!("{api:?}");
            }
            Err(e) => {
                let msg = e.to_string();
                assert!(
                    matches!(
                        e,
                        LearningModeError::ApiSetUnavailable { .. }
                            | LearningModeError::DllLoad(_)
                            | LearningModeError::ExportMissing { .. }
                    ),
                    "unexpected error variant: {msg}"
                );
            }
        }
    }

    #[test]
    fn output_path_rejects_embedded_nul() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let path = PathBuf::from(OsString::from_wide(&['a' as u16, 0, 'b' as u16]));
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        let error = api
            .stop_trace(&trace, Some(&path))
            .expect_err("embedded NUL must be rejected");

        assert!(matches!(
            error,
            LearningModeError::InvalidInput {
                parameter: "output_path",
                ..
            }
        ));
        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 0);
        drop(trace);
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn successful_hresult_starts_retryable_trace() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        START_RESULT.store(S_FALSE.0, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe {
            api.start_trace(fake_environment())
                .expect("non-failing HRESULT should succeed")
        };

        api.stop_trace(&trace, None).unwrap();
        api.stop_trace(&trace, None).unwrap();
        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 2);

        trace.close();
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn option_aware_start_requests_access_and_network() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let api = fake_options_api();

        let trace = unsafe {
            api.start_trace(fake_environment())
                .expect("option-aware start should succeed")
        };

        assert_eq!(
            START_OPTIONS.load(Ordering::SeqCst),
            REQUIRED_TRACE_SOURCE_OPTIONS
        );
        trace.close();
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn failed_hresult_keeps_trace_live_until_close() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };
        STOP_RESULT.store(E_FAIL.0, Ordering::SeqCst);

        let error = api.stop_trace(&trace, None).unwrap_err();
        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code
            } if code == E_FAIL.0
        ));

        drop(trace);
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn transient_stop_failure_is_retried() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        STOP_FAILURE_RESULT.store(
            HRESULT::from_win32(ERROR_SHARING_VIOLATION.0).0,
            Ordering::SeqCst,
        );
        STOP_FAILURES_REMAINING.store(2, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        api.stop_trace_with_retry(&trace, None).unwrap();

        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 3);
        trace.close();
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn permanent_stop_failure_is_not_retried() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        STOP_RESULT.store(E_FAIL.0, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        let error = api.stop_trace_with_retry(&trace, None).unwrap_err();

        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code
            } if code == E_FAIL.0
        ));
        assert_eq!(STOP_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn exhausted_transient_stop_retries_preserve_hresult() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let retry_hresult = HRESULT::from_win32(ERROR_LOCK_VIOLATION.0).0;
        STOP_FAILURE_RESULT.store(retry_hresult, Ordering::SeqCst);
        STOP_FAILURES_REMAINING.store(3, Ordering::SeqCst);
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        let error = api.stop_trace_with_retry(&trace, None).unwrap_err();

        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StopLearningModeTrace",
                code
            } if code == retry_hresult
        ));
        assert_eq!(
            STOP_CALLS.load(Ordering::SeqCst),
            LearningModeTraceHandle::STOP_DELIVERY_ATTEMPTS
        );
    }

    #[test]
    fn failed_start_preserves_hresult_and_does_not_close() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        START_RESULT.store(E_FAIL.0, Ordering::SeqCst);
        let api = fake_api();

        let error = unsafe { api.start_trace(fake_environment()).unwrap_err() };

        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StartLearningModeTrace",
                code
            } if code == E_FAIL.0
        ));
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn failed_option_aware_start_identifies_selected_export() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        START_RESULT.store(E_FAIL.0, Ordering::SeqCst);
        let api = fake_options_api();

        let error = unsafe { api.start_trace(fake_environment()).unwrap_err() };

        assert!(matches!(
            error,
            LearningModeError::HResultCall {
                function: "StartLearningModeTraceWithOptions",
                code
            } if code == E_FAIL.0
        ));
        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 0);
    }

    #[test]
    fn successful_start_with_null_handle_identifies_selected_export() {
        let _guard = TEST_LOCK.lock().unwrap();
        for (api, expected_function) in [
            (fake_api(), "StartLearningModeTrace"),
            (fake_options_api(), "StartLearningModeTraceWithOptions"),
        ] {
            reset_fakes();
            WRITE_START_HANDLE.store(false, Ordering::SeqCst);

            let error = unsafe { api.start_trace(fake_environment()).unwrap_err() };

            assert!(matches!(
                error,
                LearningModeError::HResultCall { function, code }
                    if function == expected_function
                        && code == windows::Win32::Foundation::E_UNEXPECTED.0
            ));
            assert_eq!(START_CALLS.load(Ordering::SeqCst), 1);
            assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 0);
        }
    }

    #[test]
    fn explicit_close_is_exactly_once() {
        let _guard = TEST_LOCK.lock().unwrap();
        reset_fakes();
        let api = fake_api();
        let trace = unsafe { api.start_trace(fake_environment()).unwrap() };

        trace.close();

        assert_eq!(CLOSE_CALLS.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn load_result_is_memoized_and_consistent() {
        // `load` memoizes success or failure for the process. Repeated calls
        // must agree and never panic regardless of host support.
        let first = LearningModeApi::load().is_ok();
        let second = LearningModeApi::load().is_ok();
        assert_eq!(first, second);
    }
}