darwin-kperf-sys 0.1.1

Raw FFI bindings to Apple's kperf and kperfdata frameworks
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
//! `repr(C)` structs, error codes, and function pointer type aliases for
//! `kperfdata.framework`.
//!
//! This module provides the Kernel Performance Event Programming (KPEP)
//! interface: the layer that sits between the raw KPC hardware registers and
//! human-readable event names like `"INST_RETIRED.ANY"` or `"Cycles"`.
//!
//! # Structs
//!
//! Three opaque-ish C structs form the core of the KPEP API:
//!
//! - [`kpep_db`] (152 bytes): a parsed PMC event database, opened via [`kpep_db_create`] from the
//!   plist files in `/usr/share/kpep/`. Contains the full catalogue of events the current CPU
//!   supports, queryable by name ([`kpep_db_event`]) or enumerated in bulk ([`kpep_db_events`]).
//!
//! - [`kpep_event`] (56 bytes): a single PMC event descriptor. Holds the event's name, description,
//!   alias, hardware selector (`number`, `mask`), and whether the event is bound to a fixed
//!   counter. Layout reverse-engineered from `kperfdata.framework` via Ghidra.
//!
//! - [`kpep_config`] (80 bytes): a mutable configuration builder. Events are added via
//!   [`kpep_config_add_event`], then [`kpep_config_kpc`] and [`kpep_config_kpc_map`] extract the
//!   register values and counter-to-event mapping that
//!   [`kpc_set_config`](crate::kperf::kpc_set_config) expects.
//!
//! All three structs have compile-time layout assertions that verify size,
//! alignment, and field offsets.
//!
//! # `VTable`
//!
//! Because the framework is private, symbols are not available at link time.
//! [`VTable::load`] resolves all function pointers eagerly from a [`LibraryHandle`] at runtime,
//! failing immediately if any symbol is missing.

#![expect(non_camel_case_types)]
use core::{
    ffi::{c_char, c_int, c_void},
    fmt,
};

use crate::{
    kperf::kpc_config_t,
    load::{LibraryHandle, LibrarySymbol, LoadError},
};

// -----------------------------------------------------------------------------
// KPEP architecture constants
// -----------------------------------------------------------------------------

pub const KPEP_ARCH_I386: u32 = 0;
pub const KPEP_ARCH_X86_64: u32 = 1;
pub const KPEP_ARCH_ARM: u32 = 2;
pub const KPEP_ARCH_ARM64: u32 = 3;

// -----------------------------------------------------------------------------
// Types
// -----------------------------------------------------------------------------

/// KPEP event (56 bytes on 64-bit).
///
/// Layout reverse-engineered from `kperfdata.framework` via Ghidra
/// disassembly of `_event_init`, `_event_free`, and `_event_cmp`.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct kpep_event {
    /// Unique name of an event, such as `"INST_RETIRED.ANY"`.
    pub name: *const c_char,
    /// Description for this event.
    pub description: *const c_char,
    /// Errata, currently NULL.
    pub errata: *const c_char,
    /// Alias name, such as `"Instructions"`, `"Cycles"`.
    pub alias: *const c_char,
    /// Fallback event name for fixed counter.
    pub fallback: *const c_char,
    /// Hardware event selector mask.
    pub mask: u32,
    /// Event number (selector value written to the PMC config register).
    pub number: u16,
    /// Intel PMC umask value, populated from the plist `"umask"` key.
    ///
    /// Only set on `x86_64`; always zero on ARM. The name is a holdover from
    /// Intel's PMC naming conventions. Despite what older references call it,
    /// this is *not* a "is this a fixed counter" flag.
    pub umask: u8,
    _pad0: u8,
    /// Bit 0: event has a fixed counter entry in the plist and must be placed
    /// in a fixed counter slot. Set during `_event_init` when the plist
    /// contains a `"fixed_counter"` key; the fallback event name (if any) is
    /// read alongside it.
    pub flags: u8,
    _pad1: [u8; 7],
}

const _: () = {
    assert!(core::mem::size_of::<kpep_event>() == 56);
    assert!(core::mem::align_of::<kpep_event>() == 8);
    assert!(core::mem::offset_of!(kpep_event, name) == 0);
    assert!(core::mem::offset_of!(kpep_event, description) == 8);
    assert!(core::mem::offset_of!(kpep_event, errata) == 16);
    assert!(core::mem::offset_of!(kpep_event, alias) == 24);
    assert!(core::mem::offset_of!(kpep_event, fallback) == 32);
    assert!(core::mem::offset_of!(kpep_event, mask) == 40);
    assert!(core::mem::offset_of!(kpep_event, number) == 44);
    assert!(core::mem::offset_of!(kpep_event, umask) == 46);
    assert!(core::mem::offset_of!(kpep_event, flags) == 48);
};

/// KPEP database (152 bytes on 64-bit).
///
/// Layout reverse-engineered from `kperfdata.framework` via Ghidra
/// disassembly of `_kpep_db_createx`, `_kpep_db_free`, and `_init_db_from_plist`.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct kpep_db {
    /// Database name from the plist `"name"` key (internal identifier).
    pub name: *const c_char,
    /// CPU identifier string, such as `"cpu_7_8_10b282dc"`.
    pub cpu_id: *const c_char,
    /// Marketing name, such as `"Apple M1"`.
    ///
    /// This is what [`kpep_db_name`] returns.
    pub marketing_name: *const c_char,
    /// Serialized plist in binary format v1.0 (`CFDataRef`). Created lazily by
    /// `kpep_db_serialize`.
    pub plist_data: *mut c_void,
    /// All events keyed by event name (`CFDictionaryRef`: `CFString → *mut kpep_event`).
    pub event_map: *mut c_void,
    /// Contiguous event array (`sizeof(kpep_event) * event_count`).
    pub event_arr: *mut kpep_event,
    /// Fixed counter event pointers (`sizeof(kpep_event *) * fixed_counter_count`).
    pub fixed_event_arr: *mut *mut kpep_event,
    /// All aliases keyed by alias name (`CFDictionaryRef`: `CFString → *mut kpep_event`). Searched
    /// first by [`kpep_db_event`].
    pub alias_map: *mut c_void,
    _reserved0: usize,
    _reserved1: usize,
    _reserved2: usize,
    /// Total number of events in [`event_arr`](kpep_db::event_arr).
    pub event_count: usize,
    pub alias_count: usize,
    /// `popcount(fixed_counter_bits)`.
    pub fixed_counter_count: usize,
    /// `popcount(config_counter_bits)`.
    pub config_counter_count: usize,
    /// `popcount(power_counter_bits)`.
    pub power_counter_count: usize,
    /// See `KPEP_ARCH_*` constants.
    pub archtecture: u32,
    /// Bitmap of available fixed counters.
    pub fixed_counter_bits: u32,
    /// Bitmap of available configurable counters.
    pub config_counter_bits: u32,
    /// Bitmap of available power counters.
    pub power_counter_bits: u32,
    /// Search flags passed to `kpep_db_createx`.
    pub create_flags: u32,
    /// Whether the database contains Apple-internal events.
    pub is_internal: u8,
    /// Whether [`is_internal`](kpep_db::is_internal) has been populated.
    pub internal_known: u8,
    _pad: [u8; 2],
}

const _: () = {
    assert!(core::mem::size_of::<kpep_db>() == 152);
    assert!(core::mem::align_of::<kpep_db>() == 8);
    assert!(core::mem::offset_of!(kpep_db, name) == 0);
    assert!(core::mem::offset_of!(kpep_db, cpu_id) == 8);
    assert!(core::mem::offset_of!(kpep_db, marketing_name) == 16);
    assert!(core::mem::offset_of!(kpep_db, plist_data) == 24);
    assert!(core::mem::offset_of!(kpep_db, event_map) == 32);
    assert!(core::mem::offset_of!(kpep_db, event_arr) == 40);
    assert!(core::mem::offset_of!(kpep_db, fixed_event_arr) == 48);
    assert!(core::mem::offset_of!(kpep_db, alias_map) == 56);
    assert!(core::mem::offset_of!(kpep_db, event_count) == 88);
    assert!(core::mem::offset_of!(kpep_db, alias_count) == 96);
    assert!(core::mem::offset_of!(kpep_db, fixed_counter_count) == 104);
    assert!(core::mem::offset_of!(kpep_db, config_counter_count) == 112);
    assert!(core::mem::offset_of!(kpep_db, power_counter_count) == 120);
    assert!(core::mem::offset_of!(kpep_db, archtecture) == 128);
    assert!(core::mem::offset_of!(kpep_db, fixed_counter_bits) == 132);
    assert!(core::mem::offset_of!(kpep_db, config_counter_bits) == 136);
    assert!(core::mem::offset_of!(kpep_db, power_counter_bits) == 140);
    assert!(core::mem::offset_of!(kpep_db, create_flags) == 144);
    assert!(core::mem::offset_of!(kpep_db, is_internal) == 148);
    assert!(core::mem::offset_of!(kpep_db, internal_known) == 149);
};

/// KPEP config (80 bytes on 64-bit).
///
/// Layout reverse-engineered from `kperfdata.framework` via Ghidra
/// disassembly of `_kpep_config_create`, `_kpep_config_add_event`,
/// `_kpep_config_kpc_map`, and `_kpep_config_force_counters`.
#[repr(C)]
#[derive(Debug, Copy, Clone)]
pub struct kpep_config {
    pub db: *mut kpep_db,
    /// Event pointers (`sizeof(kpep_event *) * counter_count`), init NULL.
    pub events: *mut *mut kpep_event,
    /// Maps event index → absolute counter slot (`sizeof(usize) *
    /// counter_count`), init 0. [`kpep_config_kpc_map`] copies from this
    /// array, optionally subtracting `fixed_counter_count` to produce
    /// class-relative indices.
    pub event_map: *mut usize,
    /// Maps counter slot → event index (`sizeof(usize) * counter_count`),
    /// init `usize::MAX` (−1). Inverse of [`event_map`](Self::event_map).
    pub event_indices: *mut usize,
    /// Per-counter flags (`sizeof(u32) * counter_count`), init 0.
    pub flags: *mut u32,
    /// KPC sampling periods (`sizeof(u64) * counter_count`), init 0.
    pub kpc_periods: *mut u64,
    /// Number of events added via [`kpep_config_add_event`].
    pub event_count: usize,
    /// Total number of hardware counters (fixed + configurable), set from
    /// `kpep_db_counters_count(db, FIXED | CONFIGURABLE)` at creation.
    pub counter_count: usize,
    /// Active counter class mask (see `KPC_CLASS_*_MASK` constants). Built
    /// incrementally by [`kpep_config_add_event`].
    pub classes: u32,
    /// Bitmask of occupied counter slots. Bit `i` is set when counter slot
    /// `i` has an event assigned.
    pub occupied_counters: u32,
    /// Bit 0: [`kpep_config_force_counters`] has been called.
    pub force_flags: u8,
    _pad: [u8; 7],
}

const _: () = {
    assert!(core::mem::size_of::<kpep_config>() == 80);
    assert!(core::mem::align_of::<kpep_config>() == 8);
    assert!(core::mem::offset_of!(kpep_config, db) == 0);
    assert!(core::mem::offset_of!(kpep_config, events) == 8);
    assert!(core::mem::offset_of!(kpep_config, event_map) == 16);
    assert!(core::mem::offset_of!(kpep_config, event_indices) == 24);
    assert!(core::mem::offset_of!(kpep_config, flags) == 32);
    assert!(core::mem::offset_of!(kpep_config, kpc_periods) == 40);
    assert!(core::mem::offset_of!(kpep_config, event_count) == 48);
    assert!(core::mem::offset_of!(kpep_config, counter_count) == 56);
    assert!(core::mem::offset_of!(kpep_config, classes) == 64);
    assert!(core::mem::offset_of!(kpep_config, occupied_counters) == 68);
    assert!(core::mem::offset_of!(kpep_config, force_flags) == 72);
};

// -----------------------------------------------------------------------------
// Error codes
// -----------------------------------------------------------------------------

pub const KPEP_CONFIG_ERROR_NONE: c_int = 0;
pub const KPEP_CONFIG_ERROR_INVALID_ARGUMENT: c_int = 1;
pub const KPEP_CONFIG_ERROR_OUT_OF_MEMORY: c_int = 2;
pub const KPEP_CONFIG_ERROR_IO: c_int = 3;
pub const KPEP_CONFIG_ERROR_BUFFER_TOO_SMALL: c_int = 4;
pub const KPEP_CONFIG_ERROR_CUR_SYSTEM_UNKNOWN: c_int = 5;
pub const KPEP_CONFIG_ERROR_DB_PATH_INVALID: c_int = 6;
pub const KPEP_CONFIG_ERROR_DB_NOT_FOUND: c_int = 7;
pub const KPEP_CONFIG_ERROR_DB_ARCH_UNSUPPORTED: c_int = 8;
pub const KPEP_CONFIG_ERROR_DB_VERSION_UNSUPPORTED: c_int = 9;
pub const KPEP_CONFIG_ERROR_DB_CORRUPT: c_int = 10;
pub const KPEP_CONFIG_ERROR_EVENT_NOT_FOUND: c_int = 11;
pub const KPEP_CONFIG_ERROR_CONFLICTING_EVENTS: c_int = 12;
pub const KPEP_CONFIG_ERROR_COUNTERS_NOT_FORCED: c_int = 13;
pub const KPEP_CONFIG_ERROR_EVENT_UNAVAILABLE: c_int = 14;
pub const KPEP_CONFIG_ERROR_ERRNO: c_int = 15;

// -----------------------------------------------------------------------------
// Function pointer types
// -----------------------------------------------------------------------------

/// Creates a new configuration builder for the given database.
///
/// - `db`: a database handle previously obtained from [`kpep_db_create`].
/// - `cfg_ptr`: receives the newly allocated config. Free with [`kpep_config_free`].
///
/// Returns 0 on success.
pub type kpep_config_create =
    unsafe extern "C" fn(db: *mut kpep_db, cfg_ptr: *mut *mut kpep_config) -> c_int;

/// Frees a config previously allocated by [`kpep_config_create`].
pub type kpep_config_free = unsafe extern "C" fn(cfg: *mut kpep_config);

/// Adds an event to the configuration.
///
/// - `cfg`: the config to modify.
/// - `ev_ptr`: pointer to the event pointer (obtained from [`kpep_db_event`]).
/// - `flag`: 0 to count in all modes, 1 for user space only.
/// - `err`: optional error bitmap pointer. If the return value is `CONFLICTING_EVENTS`, this bitmap
///   indicates which event indices conflict (e.g. `1 << 2` means index 2).
///
/// Returns 0 on success.
pub type kpep_config_add_event = unsafe extern "C" fn(
    cfg: *mut kpep_config,
    ev_ptr: *mut *mut kpep_event,
    flag: u32,
    err: *mut u32,
) -> c_int;

/// Removes the event at `idx` from the configuration. Returns 0 on success.
pub type kpep_config_remove_event =
    unsafe extern "C" fn(cfg: *mut kpep_config, idx: usize) -> c_int;

/// Marks the configuration as needing force-acquired counters.
///
/// After calling this, [`kpep_config_kpc`] will produce register values that
/// require `kpc_force_all_ctrs_set(1)` to have been called first. Returns 0
/// on success.
pub type kpep_config_force_counters = unsafe extern "C" fn(cfg: *mut kpep_config) -> c_int;

/// Gets the number of events added to this config. Returns 0 on success.
pub type kpep_config_events_count =
    unsafe extern "C" fn(cfg: *mut kpep_config, count_ptr: *mut usize) -> c_int;

/// Gets all event pointers from the configuration.
///
/// - `cfg`: the config to query.
/// - `buf`: receives event pointers.
/// - `buf_size`: buffer size in bytes; should be at least `kpep_config_events_count() * sizeof(void
///   *)`.
///
/// Returns 0 on success.
pub type kpep_config_events = unsafe extern "C" fn(
    cfg: *mut kpep_config,
    buf: *mut *mut kpep_event,
    buf_size: usize,
) -> c_int;

/// Gets the KPC register configuration values.
///
/// - `cfg`: the config to query.
/// - `buf`: receives register config values.
/// - `buf_size`: buffer size in bytes; should be at least `kpep_config_kpc_count() *
///   sizeof(kpc_config_t)`.
///
/// Returns 0 on success.
pub type kpep_config_kpc =
    unsafe extern "C" fn(cfg: *mut kpep_config, buf: *mut kpc_config_t, buf_size: usize) -> c_int;

/// Gets the number of KPC register config values. Returns 0 on success.
pub type kpep_config_kpc_count =
    unsafe extern "C" fn(cfg: *mut kpep_config, count_ptr: *mut usize) -> c_int;

/// Gets the active KPC counter class mask.
///
/// `classes_ptr` receives a combination of `KPC_CLASS_*_MASK` constants.
/// Returns 0 on success.
pub type kpep_config_kpc_classes =
    unsafe extern "C" fn(cfg: *mut kpep_config, classes_ptr: *mut u32) -> c_int;

/// Gets the mapping from event index to hardware counter slot.
///
/// - `cfg`: the config to query.
/// - `buf`: receives one index per event. Each value is the hardware counter slot assigned to the
///   corresponding event.
/// - `buf_size`: buffer size in bytes; should be at least `kpep_config_events_count() *
///   sizeof(usize)`.
///
/// Returns 0 on success.
pub type kpep_config_kpc_map =
    unsafe extern "C" fn(cfg: *mut kpep_config, buf: *mut usize, buf_size: usize) -> c_int;

/// Opens a kpep database file in `/usr/share/kpep/` or `/usr/local/share/kpep/`.
///
/// - `name`: the database file name, for example `"haswell"` or `"cpu_100000c_1_92fb37c8"`. Pass
///   NULL to auto-detect the current CPU.
/// - `db_ptr`: receives the newly allocated database. Free with [`kpep_db_free`].
///
/// Returns 0 on success.
pub type kpep_db_create =
    unsafe extern "C" fn(name: *const c_char, db_ptr: *mut *mut kpep_db) -> c_int;

/// Frees a database previously allocated by [`kpep_db_create`].
pub type kpep_db_free = unsafe extern "C" fn(db: *mut kpep_db);

/// Gets the database's marketing name (e.g. `"Apple M1"`). Returns 0 on success.
pub type kpep_db_name = unsafe extern "C" fn(db: *mut kpep_db, name: *mut *const c_char) -> c_int;

/// Gets the number of event aliases in the database. Returns 0 on success.
pub type kpep_db_aliases_count = unsafe extern "C" fn(db: *mut kpep_db, count: *mut usize) -> c_int;

/// Gets all alias strings from the database.
///
/// - `db`: the database to query.
/// - `buf`: receives alias string pointers.
/// - `buf_size`: buffer size in bytes; should be at least `kpep_db_aliases_count() * sizeof(void
///   *)`.
///
/// Returns 0 on success.
pub type kpep_db_aliases =
    unsafe extern "C" fn(db: *mut kpep_db, buf: *mut *const c_char, buf_size: usize) -> c_int;

/// Gets the number of counters for the given classes.
///
/// `classes`: 1 for fixed, 2 for configurable, 3 for both. Returns 0 on success.
pub type kpep_db_counters_count =
    unsafe extern "C" fn(db: *mut kpep_db, classes: u8, count: *mut usize) -> c_int;

/// Gets the total number of events in the database. Returns 0 on success.
pub type kpep_db_events_count = unsafe extern "C" fn(db: *mut kpep_db, count: *mut usize) -> c_int;

/// Gets all event pointers from the database.
///
/// - `db`: the database to query.
/// - `buf`: receives event pointers.
/// - `buf_size`: buffer size in bytes; should be at least `kpep_db_events_count() * sizeof(void
///   *)`.
///
/// Returns 0 on success.
pub type kpep_db_events =
    unsafe extern "C" fn(db: *mut kpep_db, buf: *mut *mut kpep_event, buf_size: usize) -> c_int;

/// Looks up a single event by name or alias. Returns 0 on success.
pub type kpep_db_event = unsafe extern "C" fn(
    db: *mut kpep_db,
    name: *const c_char,
    ev_ptr: *mut *mut kpep_event,
) -> c_int;

/// Gets an event's unique name (e.g. `"INST_ALL"`). Returns 0 on success.
pub type kpep_event_name =
    unsafe extern "C" fn(ev: *mut kpep_event, name_ptr: *mut *const c_char) -> c_int;

/// Gets an event's alias (e.g. `"Instructions"`), if one exists. Returns 0 on success.
pub type kpep_event_alias =
    unsafe extern "C" fn(ev: *mut kpep_event, alias_ptr: *mut *const c_char) -> c_int;

/// Gets an event's human-readable description, if available. Returns 0 on success.
pub type kpep_event_description =
    unsafe extern "C" fn(ev: *mut kpep_event, str_ptr: *mut *const c_char) -> c_int;

// -----------------------------------------------------------------------------
// VTable
// -----------------------------------------------------------------------------

macro_rules! load_sym {
    ($handle:expr, $name:ident, $cname:expr) => {{
        // SAFETY: the symbol is a function pointer with the signature declared
        // by the corresponding type alias.
        unsafe { core::mem::transmute::<LibrarySymbol, $name>($handle.symbol($cname)?) }
    }};
}

/// Eagerly-resolved function pointers for `kperfdata.framework`.
///
/// Each field is a C function pointer obtained via `dlsym` from Apple's private
/// `kperfdata.framework`. The framework provides the Kernel Performance Event
/// Programming (KPEP) interface, which sits between human-readable event names
/// (like `"INST_RETIRED.ANY"` or `"Cycles"`) and the raw KPC hardware registers.
///
/// The KPEP API is organized around three object types:
///
/// - **[`kpep_db`]**: a parsed PMC event database, opened from the plist files in
///   `/usr/share/kpep/`. Functions: [`kpep_db_create`], [`kpep_db_free`], [`kpep_db_event`],
///   [`kpep_db_events`].
///
/// - **[`kpep_event`]**: a single PMC event descriptor with its hardware selector, name, alias, and
///   fixed-counter flag. Functions: [`kpep_event_name`], [`kpep_event_alias`],
///   [`kpep_event_description`].
///
/// - **[`kpep_config`]**: a mutable configuration builder that maps events to counter registers.
///   Functions: [`kpep_config_create`], [`kpep_config_add_event`], [`kpep_config_kpc`],
///   [`kpep_config_kpc_map`].
///
/// All function pointers are resolved eagerly by [`load`](Self::load). If any
/// symbol is missing from the framework, loading fails immediately rather than
/// deferring to first use. The resolved pointers remain valid for as long as
/// the originating [`LibraryHandle`] is open.
///
/// # Safety
///
/// Every field is an `unsafe extern "C" fn`. The caller is responsible for
/// upholding the preconditions documented on each function pointer type alias:
/// buffer sizes, pointer validity, and correct lifetime management of the
/// opaque `kpep_*` objects.
#[expect(clippy::struct_field_names)]
pub struct VTable {
    pub kpep_config_create: kpep_config_create,
    pub kpep_config_free: kpep_config_free,
    pub kpep_config_add_event: kpep_config_add_event,
    pub kpep_config_remove_event: kpep_config_remove_event,
    pub kpep_config_force_counters: kpep_config_force_counters,
    pub kpep_config_events_count: kpep_config_events_count,
    pub kpep_config_events: kpep_config_events,
    pub kpep_config_kpc: kpep_config_kpc,
    pub kpep_config_kpc_count: kpep_config_kpc_count,
    pub kpep_config_kpc_classes: kpep_config_kpc_classes,
    pub kpep_config_kpc_map: kpep_config_kpc_map,
    pub kpep_db_create: kpep_db_create,
    pub kpep_db_free: kpep_db_free,
    pub kpep_db_name: kpep_db_name,
    pub kpep_db_aliases_count: kpep_db_aliases_count,
    pub kpep_db_aliases: kpep_db_aliases,
    pub kpep_db_counters_count: kpep_db_counters_count,
    pub kpep_db_events_count: kpep_db_events_count,
    pub kpep_db_events: kpep_db_events,
    pub kpep_db_event: kpep_db_event,
    pub kpep_event_name: kpep_event_name,
    pub kpep_event_alias: kpep_event_alias,
    pub kpep_event_description: kpep_event_description,
}

impl fmt::Debug for VTable {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt.debug_struct("VTable").finish_non_exhaustive()
    }
}

impl VTable {
    /// Resolves every `kperfdata.framework` symbol from `handle`.
    ///
    /// Resolution is all-or-nothing: if any of the 23 required symbols cannot
    /// be found, the call returns an error.
    ///
    /// # Errors
    ///
    /// Returns [`LoadError`] if any symbol cannot be resolved from the framework.
    pub fn load(handle: &LibraryHandle) -> Result<Self, LoadError> {
        Ok(Self {
            kpep_config_create: load_sym!(handle, kpep_config_create, c"kpep_config_create"),
            kpep_config_free: load_sym!(handle, kpep_config_free, c"kpep_config_free"),
            kpep_config_add_event: load_sym!(
                handle,
                kpep_config_add_event,
                c"kpep_config_add_event"
            ),
            kpep_config_remove_event: load_sym!(
                handle,
                kpep_config_remove_event,
                c"kpep_config_remove_event"
            ),
            kpep_config_force_counters: load_sym!(
                handle,
                kpep_config_force_counters,
                c"kpep_config_force_counters"
            ),
            kpep_config_events_count: load_sym!(
                handle,
                kpep_config_events_count,
                c"kpep_config_events_count"
            ),
            kpep_config_events: load_sym!(handle, kpep_config_events, c"kpep_config_events"),
            kpep_config_kpc: load_sym!(handle, kpep_config_kpc, c"kpep_config_kpc"),
            kpep_config_kpc_count: load_sym!(
                handle,
                kpep_config_kpc_count,
                c"kpep_config_kpc_count"
            ),
            kpep_config_kpc_classes: load_sym!(
                handle,
                kpep_config_kpc_classes,
                c"kpep_config_kpc_classes"
            ),
            kpep_config_kpc_map: load_sym!(handle, kpep_config_kpc_map, c"kpep_config_kpc_map"),
            kpep_db_create: load_sym!(handle, kpep_db_create, c"kpep_db_create"),
            kpep_db_free: load_sym!(handle, kpep_db_free, c"kpep_db_free"),
            kpep_db_name: load_sym!(handle, kpep_db_name, c"kpep_db_name"),
            kpep_db_aliases_count: load_sym!(
                handle,
                kpep_db_aliases_count,
                c"kpep_db_aliases_count"
            ),
            kpep_db_aliases: load_sym!(handle, kpep_db_aliases, c"kpep_db_aliases"),
            kpep_db_counters_count: load_sym!(
                handle,
                kpep_db_counters_count,
                c"kpep_db_counters_count"
            ),
            kpep_db_events_count: load_sym!(handle, kpep_db_events_count, c"kpep_db_events_count"),
            kpep_db_events: load_sym!(handle, kpep_db_events, c"kpep_db_events"),
            kpep_db_event: load_sym!(handle, kpep_db_event, c"kpep_db_event"),
            kpep_event_name: load_sym!(handle, kpep_event_name, c"kpep_event_name"),
            kpep_event_alias: load_sym!(handle, kpep_event_alias, c"kpep_event_alias"),
            kpep_event_description: load_sym!(
                handle,
                kpep_event_description,
                c"kpep_event_description"
            ),
        })
    }
}