syd 3.58.0

rock-solid application kernel
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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
//
// Syd: rock-solid application kernel
// src/proc/maps.rs: proc(5) memory maps and PROCMAP_QUERY
//
// Copyright (c) 2023, 2024, 2025, 2026 Ali Polatel <alip@chesswob.org>
// PROCMAP_QUERY ioctl(2) interface is based on <linux/fs.h> which is:
//   SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note
//
// SPDX-License-Identifier: GPL-3.0

// SAFETY: procmap_query uses ioctl(2) which calls into libc therefore needs unsafe.
// Use deny rather than forbid so we can allow this case.
#![deny(unsafe_code)]

use std::{
    ffi::CStr,
    fmt,
    io::BufReader,
    num::NonZeroUsize,
    os::{
        fd::{AsFd, AsRawFd},
        unix::ffi::OsStrExt,
    },
    ptr::NonNull,
};

use bitflags::bitflags;
use memchr::memchr;
use nix::{errno::Errno, unistd::Pid};
use procfs_core::{
    process::{MMPermissions, MMapPath, MemoryMaps, SmapsRollup},
    FromBufRead,
};
use serde::{ser::SerializeMap, Serialize, Serializer};

use super::util::safe_open_proc;
use crate::{
    config::*,
    confine::SydMemoryMap,
    cookie::{CookieIdx, SYSCOOKIE_POOL},
    err::{proc_errno, proc_error_to_errno},
    fd::SafeOwnedFd,
    imap::SydIndexSet,
    path::{XPathBuf, PATH_MAX},
    XPath,
};

bitflags! {
    /// VMA permission flags.
    ///
    /// Can be used as part of `ProcmapQueryFlags` to look up only VMAs
    /// satisfying specified subset of permissions. E.g., specifying
    /// `PROCMAP_QUERY_VMA_READABLE` only will return both readable and
    /// read/write VMAs, while having `PROCMAP_QUERY_VMA_READABLE |
    /// PROCMAP_QUERY_VMA_WRITABLE` will only return read/write VMAs,
    /// though both executable/non-executable and private/shared will be
    /// ignored.
    ///
    /// `PROCMAP_QUERY_VMA_*` flags are also returned in `vma_flags`
    /// field to specify actual VMA permissions.
    #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
    pub struct ProcmapQueryFlags: u64 {
        /// query-readable flag
        const VMA_READABLE = 0x01;
        /// query-writable flag
        const VMA_WRITABLE = 0x02;
        /// query-executable flag
        const VMA_EXECUTABLE = 0x04;
        /// query-shared flag
        const VMA_SHARED = 0x08;

        /// Query modifier flags.
        ///
        /// By default VMA that covers provided address is returned,
        /// or `-ENOENT` is returned. With `PROCMAP_QUERY_COVERING_OR_NEXT_VMA`
        /// flag set, closest VMA with `vma_start > addr` will be returned if
        /// no covering VMA is found.
        ///
        /// `PROCMAP_QUERY_FILE_BACKED_VMA` instructs query to consider only
        /// VMAs that have file backing. Can be combined with
        /// `PROCMAP_QUERY_COVERING_OR_NEXT_VMA` to iterate all VMAs with
        /// file backing.
        const COVERING_OR_NEXT_VMA = 0x10;
        /// query-file-backed flag
        const FILE_BACKED_VMA = 0x20;
    }
}

impl fmt::Display for ProcmapQueryFlags {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.contains(Self::VMA_READABLE) {
            f.write_str("r")?;
        } else {
            f.write_str("-")?;
        }
        if self.contains(Self::VMA_WRITABLE) {
            f.write_str("w")?;
        } else {
            f.write_str("-")?;
        }
        if self.contains(Self::VMA_EXECUTABLE) {
            f.write_str("x")?;
        } else {
            f.write_str("-")?;
        }
        if self.contains(Self::VMA_SHARED) {
            f.write_str("s")?;
        } else {
            f.write_str("p")?;
        }
        Ok(())
    }
}

impl Serialize for ProcmapQueryFlags {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.collect_str(self)
    }
}

impl From<MMPermissions> for ProcmapQueryFlags {
    fn from(perms: MMPermissions) -> Self {
        let mut flags = Self::empty();

        if perms.contains(MMPermissions::READ) {
            flags.insert(Self::VMA_READABLE);
        }

        if perms.contains(MMPermissions::WRITE) {
            flags.insert(Self::VMA_WRITABLE);
        }

        if perms.contains(MMPermissions::EXECUTE) {
            flags.insert(Self::VMA_EXECUTABLE);
        }

        if perms.contains(MMPermissions::SHARED) {
            flags.insert(Self::VMA_SHARED);
        }

        flags
    }
}

/// Input/output argument structure passed into the _ioctl_(2) call. It can
/// be used to query a set of VMAs (Virtual Memory Areas) of a process.
///
/// Each field can be one of three kinds, marked in a short comment to the
/// right of the field:
///   - "in", input argument, user has to provide this value, kernel doesn't modify it;
///   - "out", output argument, kernel sets this field with VMA data;
///   - "in/out", input and output argument; user provides initial value
///     (used to specify maximum allowable buffer size), and kernel sets it
///     to actual amount of data written (or zero, if there is no data).
///
/// If matching VMA is found (according to criteria specified by
/// `query_addr`/`query_flags`), all the out fields are filled out, and
/// _ioctl_(2) returns `0`. If there is no matching VMA, `Err(Errno::ENOENT)` will be
/// returned. In case of any other error, a negative error code other than
/// `Err(Errno::ENOENT)` is returned.
///
/// Most of the data is similar to the one returned as text in
/// _proc_pid_maps_(5), but `procmap_query` provides more querying flexibility.
/// There are no consistency guarantees between subsequent _ioctl_(2) calls,
/// but data returned for a matched VMA is self-consistent.
#[repr(C)]
#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ProcmapQuery {
    /// Query struct size, for backwards/forward compatibility.
    pub size: u64,

    /// Query flags, a combination of `ProcmapQueryFlags` values.
    /// Defines query filtering and behavior.
    /// (in)
    pub query_flags: u64,

    /// Query address. By default, VMA that covers this address will be looked up.
    /// Modifier flags further adjust behavior.
    /// (in)
    pub query_addr: u64,

    /// VMA starting (inclusive) address, if VMA is found.
    /// (out)
    pub vma_start: u64,

    /// VMA ending (exclusive) address, if VMA is found.
    /// (out)
    pub vma_end: u64,

    /// VMA permissions flags. A combination of `ProcmapQueryFlags::PROCMAP_QUERY_VMA_*`.
    /// (out)
    pub vma_flags: u64,

    /// VMA backing page size granularity.
    /// (out)
    pub vma_page_size: u64,

    /// VMA file offset within the backing file. Zero if no backing file.
    /// (out)
    pub vma_offset: u64,

    /// Backing file's inode number, or zero if no backing file.
    /// (out)
    pub inode: u64,

    /// Backing file's device major number, or zero if no backing file.
    /// (out)
    pub dev_major: u32,

    /// Backing file's device minor number, or zero if no backing file.
    /// (out)
    pub dev_minor: u32,

    /// Maximum/returned size of the VMA name buffer.
    /// Kernel sets to actual bytes written (including terminating NUL).
    /// (in/out)
    pub vma_name_size: u32,

    /// Maximum/returned size of the build ID buffer.
    /// Kernel sets to actual bytes written.
    /// (in/out)
    pub build_id_size: u32,

    /// User-space address of the buffer for VMA name, or zero if unused.
    /// (in)
    pub vma_name_addr: u64,

    /// User-space address of the buffer for build ID, or zero if unused.
    /// (in)
    pub build_id_addr: u64,
}

impl Default for ProcmapQuery {
    fn default() -> Self {
        Self {
            size: size_of::<Self>() as u64,
            query_flags: 0,
            query_addr: 0,
            vma_start: 0,
            vma_end: 0,
            vma_flags: 0,
            vma_page_size: 0,
            vma_offset: 0,
            inode: 0,
            dev_major: 0,
            dev_minor: 0,
            vma_name_size: 0,
            build_id_size: 0,
            vma_name_addr: 0,
            build_id_addr: 0,
        }
    }
}

/// 'f' is the magic number for _procfs_(5) ioctls.
pub const PROCFS_IOCTL_MAGIC: u32 = b'f' as u32;

/// _ioctl_(2) request number for _proc_pid_maps_(5) PROCMAP_QUERY.
pub const PROCMAP_QUERY: libc::c_ulong =
    libc::_IOWR::<ProcmapQuery>(PROCFS_IOCTL_MAGIC, 17) as libc::c_ulong;

/// Safe wrapper around the _proc_pid_maps_(5) PROCMAP_QUERY ioctl(2).
///
/// # Arguments
///
/// * `fd`: Descriptor for _proc_pid_maps_(5)
/// * `flags`: `ProcmapQueryFlags` controlling query filtering and iteration.
/// * `query_addr`: Address to probe; interpretation depends on `flags`.
/// * `name_buf`: Optional buffer to receive the VMA's name (including trailing NUL byte).
/// * `build_id_buf`: Optional buffer to receive the VMA's ELF build ID.
///
/// # Returns
///
/// On success, returns the populated `ProcmapQuery` struct.
/// On error, returns the corresponding `Errno`.
pub fn procmap_query<Fd: AsFd>(
    fd: Fd,
    flags: ProcmapQueryFlags,
    query_addr: u64,
    name_buf: Option<&mut [u8]>,
    build_id_buf: Option<&mut [u8]>,
) -> Result<ProcmapQuery, Errno> {
    let mut q = ProcmapQuery {
        query_addr,
        query_flags: flags.bits(),
        ..Default::default()
    };

    if let Some(buf) = name_buf {
        q.vma_name_size = u32::try_from(buf.len()).or(Err(Errno::EINVAL))?;
        q.vma_name_addr = buf.as_mut_ptr() as u64;
    }

    if let Some(buf) = build_id_buf {
        q.build_id_size = u32::try_from(buf.len()).or(Err(Errno::EINVAL))?;
        q.build_id_addr = buf.as_mut_ptr() as u64;
    }

    // SAFETY:
    // 1. "q" is #[repr(C)] and fully initialized;
    // 2. Buffers live at least until ioctl(2) returns.
    // 3. Trailing arguments are syscall argument cookies.
    #[expect(unsafe_code)]
    Errno::result(unsafe {
        libc::syscall(
            libc::SYS_ioctl,
            fd.as_fd().as_raw_fd(),
            PROCMAP_QUERY,
            &mut q,
            SYSCOOKIE_POOL.get(CookieIdx::ProcmapQueryArg3),
            SYSCOOKIE_POOL.get(CookieIdx::ProcmapQueryArg4),
            SYSCOOKIE_POOL.get(CookieIdx::ProcmapQueryArg5),
        )
    })
    .map(|_| q)
}

/// Return the memory maps of the given process.
pub fn proc_maps(pid: Pid) -> Result<Vec<SydMemoryMap>, Errno> {
    proc_maps_read(proc_maps_open(pid)?)
}

/// Open a FD to _proc_pid_maps_(5) and return a SafeOwnedFd.
pub fn proc_maps_open(pid: Pid) -> Result<SafeOwnedFd, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"maps")?;

    safe_open_proc(&path).map_err(proc_errno)
}

/// Return the memory maps of the given process from the given Fd.
pub fn proc_maps_read(fd: SafeOwnedFd) -> Result<Vec<SydMemoryMap>, Errno> {
    let maps = MemoryMaps::from_buf_read(BufReader::new(fd))
        .map_err(|err| proc_error_to_errno(&err).unwrap_or(Errno::ENOSYS))
        .map_err(proc_errno)?;

    let mut vec = Vec::new();
    vec.try_reserve_exact(maps.0.len()).or(Err(Errno::ENOMEM))?;
    for map in maps.0 {
        vec.push(SydMemoryMap(map));
    }

    Ok(vec)
}

/// Return the memory maps of the given process.
pub fn proc_smaps(pid: Pid) -> Result<Vec<SydMemoryMap>, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"smaps")?;

    // Safely open proc(5) file.
    let reader = safe_open_proc(&path)
        .map(BufReader::new)
        .map_err(proc_errno)?;

    let maps = MemoryMaps::from_buf_read(reader)
        .map_err(|err| proc_error_to_errno(&err).unwrap_or(Errno::ENOSYS))
        .map_err(proc_errno)?;

    let mut vec = Vec::new();
    vec.try_reserve_exact(maps.0.len()).or(Err(Errno::ENOMEM))?;
    for map in maps.0 {
        vec.push(SydMemoryMap(map));
    }

    Ok(vec)
}

/// Return the rollup memory map of the given process.
///
/// This is more efficient than using `proc_smaps` and iterating over maps.
/// See: https://www.kernel.org/doc/Documentation/ABI/testing/procfs-smaps_rollup
pub fn proc_smaps_rollup(pid: Pid) -> Result<SydMemoryMap, Errno> {
    let mut path = XPathBuf::from_pid(pid)?;
    path.try_push(b"smaps_rollup")?;

    // Safely open proc(5) file.
    let reader = safe_open_proc(&path)
        .map(BufReader::new)
        .map_err(proc_errno)?;

    SmapsRollup::from_buf_read(reader)
        .map_err(|err| proc_error_to_errno(&err).unwrap_or(Errno::ENOSYS))
        .map_err(proc_errno)
        .and_then(|maps| {
            maps.memory_map_rollup
                .into_iter()
                .next()
                .map(SydMemoryMap)
                .ok_or(Errno::ENOMEM)
        })
}

/// Calculate total memory usage of a process using _proc_pid_smaps_rollup(5).
///
/// See: https://www.kernel.org/doc/Documentation/ABI/testing/procfs-smaps_rollup
pub fn proc_mem(pid: Pid) -> Result<u64, Errno> {
    let map = proc_smaps_rollup(pid)?;
    let mut sum = 0u64;
    for key in ["Pss", "Private_Dirty", "Shared_Dirty"] {
        let val = map.0.extension.map.get(key).copied().unwrap_or(0);
        sum = sum.saturating_add(val);
    }

    Ok(sum)
}

/// Represents an executable file record from proc_pid_maps(5).
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd, Hash)]
pub struct SydExecMap {
    /// Path to the executable
    pub path: XPathBuf,
    /// Inode of the executable
    pub inode: u64,
    /// Major device ID of the executable
    pub dev_major: i32,
    /// Minor device ID of the executable
    pub dev_minor: i32,
}

/// Collects all unique paths with executable permissions from the
/// memory maps of a process.
///
/// # Returns
///
/// A `Result` containing a vector of `SydExecMap` objects
/// for all unique paths with executable permissions along with their
/// device ID and inode. On error, it returns an `Errno`. If no executable
/// is found in maps, returns `Errno::ENOEXEC`.
pub fn proc_executables(pid: Pid) -> Result<Vec<SydExecMap>, Errno> {
    if *crate::config::HAVE_PROCMAP_QUERY {
        // Use the efficient PROCMAP_QUERY ioctl(2) on Linux>=6.11.
        return procmap_query_executables(pid);
    }

    let maps = proc_maps(pid)?;

    // Create a SydIndexSet to store unique executable paths while
    // preserving insertion order.
    let mut set: SydIndexSet<SydExecMap> = SydIndexSet::default();

    // Iterate over each memory map entry.
    for map in maps {
        // Match on the pathname to extract the path.
        if let MMapPath::Path(path) = map.0.pathname {
            // Check if the map has executable permissions.
            if map.0.perms.contains(MMPermissions::EXECUTE) {
                // Insert the path into the SydIndexSet.
                let exe = SydExecMap {
                    path: path.into(),
                    inode: map.0.inode,
                    dev_major: map.0.dev.0,
                    dev_minor: map.0.dev.1,
                };
                set.try_insert(exe)?;
            }
        }
    }

    // Check for no match.
    if set.is_empty() {
        return Err(Errno::ENOEXEC);
    }

    // Convert the SydIndexSet to a vector and return.
    let mut vec = Vec::new();
    vec.try_reserve_exact(set.len()).or(Err(Errno::ENOMEM))?;
    for exe in set {
        vec.push(exe);
    }

    Ok(vec)
}

/// Collects all unique paths with executable permissions from the
/// memory maps of a process, using the PROCMAP_QUERY _ioctl_(2).
///
/// # Returns
///
/// A `Result` containing a vector of `SydExecMap` objects
/// for all unique paths with executable permissions along with their
/// inode and device numbers. On error, returns an `Errno`. If no executable
/// mappings are found, returns `Errno::ENOEXEC`.
pub fn procmap_query_executables(pid: Pid) -> Result<Vec<SydExecMap>, Errno> {
    // Open /proc/$pid/maps.
    let maps = proc_maps_open(pid)?;

    // Only file-backed, executable VMAs, iterating cover/next.
    let flags = ProcmapQueryFlags::COVERING_OR_NEXT_VMA
        | ProcmapQueryFlags::FILE_BACKED_VMA
        | ProcmapQueryFlags::VMA_EXECUTABLE;

    let mut path = [0u8; PATH_MAX];
    let mut addr = 0u64;
    let mut set: SydIndexSet<SydExecMap> = SydIndexSet::default();

    loop {
        match procmap_query(&maps, flags, addr, Some(&mut path), None) {
            Ok(q) => {
                let name_len = q.vma_name_size as usize;
                if name_len == 0 {
                    addr = q.vma_end;
                    continue;
                }

                // SAFETY: ioctl filled buf[..name_len] including trailing NUL.
                let path = CStr::from_bytes_with_nul(&path[..name_len])
                    .map(|cstr| cstr.to_bytes())
                    .or(Err(Errno::EINVAL))
                    .and_then(XPathBuf::try_from)?;
                #[expect(clippy::cast_possible_wrap)]
                let exe = SydExecMap {
                    path,
                    inode: q.inode,
                    dev_major: q.dev_major as i32,
                    dev_minor: q.dev_minor as i32,
                };
                set.try_insert(exe)?;

                addr = q.vma_end;
            }
            Err(Errno::ENOENT) => break,
            Err(errno) => return Err(errno),
        }
    }

    // Check for no match.
    if set.is_empty() {
        return Err(Errno::ENOEXEC);
    }

    // Convert the SydIndexSet to a vector and return.
    let mut vec = Vec::new();
    vec.try_reserve_exact(set.len()).or(Err(Errno::ENOMEM))?;
    for exe in set {
        vec.push(exe);
    }

    Ok(vec)
}

/// This data structure represents a Virtual Memory Area.
pub struct Vma {
    // VMA address
    ptr: NonNull<libc::c_void>,

    // VMA length
    len: NonZeroUsize,

    // VMA flags
    flags: ProcmapQueryFlags,

    // VMA name
    name: [u8; PATH_MAX],
}

impl Vma {
    fn new(
        ptr: NonNull<libc::c_void>,
        len: NonZeroUsize,
        flags: ProcmapQueryFlags,
        name: [u8; PATH_MAX],
    ) -> Self {
        Self {
            ptr,
            len,
            flags,
            name,
        }
    }

    /// Return VMA address.
    pub fn addr(&self) -> usize {
        self.ptr.as_ptr() as usize
    }

    /// Return VMA pointer.
    pub fn as_ptr(&self) -> NonNull<libc::c_void> {
        self.ptr
    }

    /// Return VMA length.
    pub fn len(&self) -> NonZeroUsize {
        self.len
    }

    /// Return VMA flags.
    pub fn flags(&self) -> ProcmapQueryFlags {
        self.flags
    }

    /// Return VMA name as `XPath`.
    pub fn name(&self) -> &XPath {
        XPath::from_bytes(self.name_bytes())
    }

    /// Return VMA name as bytes.
    pub fn name_bytes(&self) -> &[u8] {
        let len = memchr(0, &self.name).unwrap_or(PATH_MAX);
        &self.name[..len]
    }
}

impl TryFrom<SydMemoryMap> for Vma {
    type Error = Errno;

    fn try_from(map: SydMemoryMap) -> Result<Self, Self::Error> {
        let map = map.0;
        let (start, end) = (map.address.0, map.address.1);
        let ptr = NonNull::new(start as *mut _).ok_or(Errno::EINVAL)?;
        let len = end
            .checked_sub(start)
            .ok_or(Errno::EINVAL)
            .map(usize::try_from)?
            .or(Err(Errno::EINVAL))
            .map(NonZeroUsize::new)?
            .ok_or(Errno::EINVAL)?;

        let mut name = [0u8; PATH_MAX];
        match &map.pathname {
            MMapPath::Path(path) => {
                let bytes = path.as_os_str().as_bytes();
                let len = bytes.len().min(PATH_MAX);
                name[..len].copy_from_slice(&bytes[..len]);
            }
            MMapPath::Heap => {
                name[..7].copy_from_slice(b"[heap]\0");
            }
            MMapPath::Stack => {
                name[..8].copy_from_slice(b"[stack]\0");
            }
            MMapPath::TStack(tid) => {
                use std::io::Write;
                let _ = write!(&mut name[..], "[stack:{tid}]\0");
            }
            MMapPath::Vdso => {
                name[..7].copy_from_slice(b"[vdso]\0");
            }
            MMapPath::Vvar => {
                name[..7].copy_from_slice(b"[vvar]\0");
            }
            MMapPath::Vsyscall => {
                name[..11].copy_from_slice(b"[vsyscall]\0");
            }
            MMapPath::Rollup | MMapPath::Vsys(_) | MMapPath::Other(_) | MMapPath::Anonymous => {}
        }

        Ok(Self::new(ptr, len, map.perms.into(), name))
    }
}

impl TryFrom<(ProcmapQuery, [u8; PATH_MAX])> for Vma {
    type Error = Errno;

    fn try_from((q, name): (ProcmapQuery, [u8; PATH_MAX])) -> Result<Self, Self::Error> {
        let ptr = NonNull::new(q.vma_start as *mut _).ok_or(Errno::EINVAL)?;
        let len = q
            .vma_end
            .checked_sub(q.vma_start)
            .ok_or(Errno::EINVAL)
            .map(usize::try_from)?
            .or(Err(Errno::EINVAL))
            .map(NonZeroUsize::new)?
            .ok_or(Errno::EINVAL)?;
        let flags = ProcmapQueryFlags::from_bits_retain(q.vma_flags);
        Ok(Self::new(ptr, len, flags, name))
    }
}

impl fmt::Display for Vma {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let start = self.addr();
        let end = start.saturating_add(self.len().get());
        let flags = self.flags();
        let name = self.name();
        write!(f, "{start:x}-{end:x} {flags} {name}")
    }
}

impl Serialize for Vma {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let start = self.addr();
        let end = start.saturating_add(self.len().get());
        let mut map = serializer.serialize_map(Some(3))?;
        map.serialize_entry("addr", &[start, end])?;
        map.serialize_entry("perm", &self.flags())?;
        map.serialize_entry("name", &self.name())?;
        map.end()
    }
}

/// Get the VMA covering `addr` in process `pid`.
///
/// Tries the ioctl(2)-based fast path on Linux>=6.11,
/// otherwise falls back to parsing _proc_pid_maps_(5).
///
/// On success returns `Vma`.
/// If no VMA covers `addr`, returns `Err(Errno::ENOENT)`.
pub fn proc_get_vma(pid: Pid, addr: u64) -> Result<Vma, Errno> {
    if *HAVE_PROCMAP_QUERY {
        // Use the efficient PROCMAP_QUERY ioctl(2) on Linux>=6.11.
        return procmap_query_get_vma(pid, addr);
    }

    // Fallback: Sequentially scan /proc/$pid/maps.
    let maps = proc_maps(pid)?;

    for map in maps {
        let (start, end) = (map.0.address.0, map.0.address.1);
        if (start..end).contains(&addr) {
            return Vma::try_from(map);
        }
    }

    // Nothing found.
    Err(Errno::ENOENT)
}

fn procmap_query_get_vma(pid: Pid, addr: u64) -> Result<Vma, Errno> {
    // Open /proc/$pid/maps.
    let maps = proc_maps_open(pid)?;

    let flags = ProcmapQueryFlags::COVERING_OR_NEXT_VMA;

    // Call PROCMAP_QUERY ioctl(2).
    //
    // No name or build-id buffers needed.
    let mut name = [0u8; PATH_MAX];
    let q = procmap_query(&maps, flags, addr, Some(&mut name), None)?;

    Vma::try_from((q, name))
}

/// Get all VMAs matching `flags` in process `pid`.
///
/// Tries the ioctl(2)-based fast path on Linux>=6.11,
/// otherwise falls back to parsing _proc_pid_maps_(5).
///
/// On success returns `Vec<Vma>`.
pub fn proc_find_vma(pid: Pid, flags: ProcmapQueryFlags) -> Result<Vec<Vma>, Errno> {
    if *HAVE_PROCMAP_QUERY {
        // Use the efficient PROCMAP_QUERY ioctl(2) on Linux>=6.11.
        return procmap_query_find_vma(pid, flags);
    }

    // Fallback: Sequentially scan /proc/$pid/maps.
    let maps = proc_maps(pid)?;
    let mut vmas = Vec::new();

    for map in maps {
        let perms = ProcmapQueryFlags::from(map.0.perms);

        if flags.contains(ProcmapQueryFlags::VMA_READABLE)
            && !perms.contains(ProcmapQueryFlags::VMA_READABLE)
        {
            continue;
        }

        if flags.contains(ProcmapQueryFlags::VMA_WRITABLE)
            && !perms.contains(ProcmapQueryFlags::VMA_WRITABLE)
        {
            continue;
        }

        if flags.contains(ProcmapQueryFlags::VMA_EXECUTABLE)
            && !perms.contains(ProcmapQueryFlags::VMA_EXECUTABLE)
        {
            continue;
        }

        if flags.contains(ProcmapQueryFlags::VMA_SHARED)
            && !perms.contains(ProcmapQueryFlags::VMA_SHARED)
        {
            continue;
        }

        if flags.contains(ProcmapQueryFlags::FILE_BACKED_VMA)
            && !matches!(map.0.pathname, MMapPath::Path(_))
        {
            continue;
        }

        vmas.push(Vma::try_from(map)?);
    }

    Ok(vmas)
}

/// Get all VMAs matching `flags` in process `pid` using PROCMAP_QUERY ioctl(2).
pub fn procmap_query_find_vma(pid: Pid, flags: ProcmapQueryFlags) -> Result<Vec<Vma>, Errno> {
    // Open /proc/$pid/maps.
    let maps = proc_maps_open(pid)?;

    let query_flags = flags | ProcmapQueryFlags::COVERING_OR_NEXT_VMA;

    let mut vmas = Vec::new();
    let mut addr = 0u64;

    loop {
        // Call PROCMAP_QUERY ioctl(2).
        //
        // No name or build-id buffers needed.
        let mut name = [0u8; PATH_MAX];
        match procmap_query(&maps, query_flags, addr, Some(&mut name), None) {
            Ok(q) => {
                vmas.push(Vma::try_from((q, name))?);
                addr = q.vma_end;
            }
            Err(Errno::ENOENT) => break,
            Err(errno) => return Err(errno),
        }
    }

    Ok(vmas)
}

/// Check memory range `[addr, addr+len)` of process `pid` for writing.
///
/// Tries the ioctl(2)-based fast path on Linux>=6.11,
/// otherwise falls back to parsing _proc_pid_maps_(5).
///
/// Return number of bytes not writable counted from end of range.
pub fn proc_get_fault(pid: Pid, addr: u64, len: usize) -> Result<usize, Errno> {
    ProcMaps::new(pid)?.get_fault(addr, len)
}

/// Memory maps of a process
pub enum ProcMaps {
    /// PROCMAP_QUERY ioctl(2) maps descriptor on Linux>=6.11.
    Query(SafeOwnedFd),
    /// Parsed proc_pid_maps(5) contents on Linux<6.11.
    Maps(Vec<SydMemoryMap>),
}

impl ProcMaps {
    /// Open memory maps of process `pid`.
    pub fn new(pid: Pid) -> Result<Self, Errno> {
        if *HAVE_PROCMAP_QUERY {
            Ok(Self::Query(proc_maps_open(pid)?))
        } else {
            Ok(Self::Maps(proc_maps(pid)?))
        }
    }

    /// Check memory range `[addr, addr+len)` for writing.
    ///
    /// Return number of bytes not writable counted from end of range.
    pub fn get_fault(&self, addr: u64, len: usize) -> Result<usize, Errno> {
        let lim = addr.saturating_add(u64::try_from(len).or(Err(Errno::EOVERFLOW))?);
        let mut end = addr;

        match self {
            Self::Query(maps) => {
                while end < lim {
                    match procmap_query(maps, ProcmapQueryFlags::VMA_WRITABLE, end, None, None) {
                        Ok(q) => end = q.vma_end.min(lim),
                        Err(Errno::ENOENT) => break,
                        Err(errno) => return Err(errno),
                    }
                }
            }
            Self::Maps(maps) => {
                for map in maps {
                    let (start, stop) = (map.0.address.0, map.0.address.1);
                    if end >= lim || start > end {
                        break;
                    }
                    if stop <= end {
                        continue;
                    }
                    if !map.0.perms.contains(MMPermissions::WRITE) {
                        break;
                    }
                    end = stop.min(lim);
                }
            }
        }

        #[expect(clippy::arithmetic_side_effects)]
        usize::try_from(lim - end).or(Err(Errno::EOVERFLOW))
    }
}

#[cfg(test)]
mod tests {
    use std::{fs::File, os::unix::fs::PermissionsExt};

    use super::{super::util::tests::setup, *};

    macro_rules! skip_if_procmap_query_not_supported {
        () => {
            if !*crate::config::HAVE_PROCMAP_QUERY {
                eprintln!("skipping: PROCMAP_QUERY not supported on this kernel (requires >=6.11)");
                return;
            }
        };
    }

    #[test]
    fn test_procmap_query_flags_1() {
        let flags = ProcmapQueryFlags::VMA_READABLE
            | ProcmapQueryFlags::VMA_WRITABLE
            | ProcmapQueryFlags::VMA_EXECUTABLE;
        assert_eq!(format!("{flags}"), "rwxp");
    }

    #[test]
    fn test_procmap_query_flags_2() {
        let flags = ProcmapQueryFlags::empty();
        assert_eq!(format!("{flags}"), "---p");
    }

    #[test]
    fn test_procmap_query_flags_3() {
        let flags = ProcmapQueryFlags::VMA_READABLE | ProcmapQueryFlags::VMA_SHARED;
        assert_eq!(format!("{flags}"), "r--s");
    }

    #[test]
    fn test_procmap_query_flags_4() {
        let flags = ProcmapQueryFlags::VMA_READABLE
            | ProcmapQueryFlags::VMA_WRITABLE
            | ProcmapQueryFlags::VMA_EXECUTABLE
            | ProcmapQueryFlags::VMA_SHARED;
        assert_eq!(format!("{flags}"), "rwxs");
    }

    #[test]
    fn test_procmap_query_flags_5() {
        let perms = MMPermissions::READ | MMPermissions::WRITE;
        let flags = ProcmapQueryFlags::from(perms);
        assert!(flags.contains(ProcmapQueryFlags::VMA_READABLE));
        assert!(flags.contains(ProcmapQueryFlags::VMA_WRITABLE));
        assert!(!flags.contains(ProcmapQueryFlags::VMA_EXECUTABLE));
        assert!(!flags.contains(ProcmapQueryFlags::VMA_SHARED));
    }

    #[test]
    fn test_procmap_query_flags_6() {
        let perms = MMPermissions::READ | MMPermissions::EXECUTE | MMPermissions::SHARED;
        let flags = ProcmapQueryFlags::from(perms);
        assert!(flags.contains(ProcmapQueryFlags::VMA_READABLE));
        assert!(flags.contains(ProcmapQueryFlags::VMA_EXECUTABLE));
        assert!(flags.contains(ProcmapQueryFlags::VMA_SHARED));
    }

    #[test]
    fn test_procmap_query_flags_7() {
        let perms = MMPermissions::empty();
        let flags = ProcmapQueryFlags::from(perms);
        assert!(flags.is_empty());
    }

    #[test]
    fn test_procmap_query_flags_8() {
        let flags = ProcmapQueryFlags::VMA_READABLE | ProcmapQueryFlags::VMA_WRITABLE;
        let json = serde_json::to_string(&flags).unwrap();
        assert_eq!(json, "\"rw-p\"");
    }

    #[test]
    fn test_procmap_query_1() {
        let q = ProcmapQuery::default();
        assert_eq!(q.size as usize, size_of::<ProcmapQuery>());
        assert_eq!(q.query_flags, 0);
        assert_eq!(q.query_addr, 0);
        assert_eq!(q.vma_start, 0);
        assert_eq!(q.vma_end, 0);
        assert_eq!(q.vma_flags, 0);
        assert_eq!(q.vma_page_size, 0);
        assert_eq!(q.vma_offset, 0);
        assert_eq!(q.inode, 0);
        assert_eq!(q.dev_major, 0);
        assert_eq!(q.dev_minor, 0);
        assert_eq!(q.vma_name_size, 0);
        assert_eq!(q.build_id_size, 0);
        assert_eq!(q.vma_name_addr, 0);
        assert_eq!(q.build_id_addr, 0);
    }

    #[test]
    fn test_procmap_query_2() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let q = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA | ProcmapQueryFlags::VMA_READABLE,
            0,
            None,
            None,
        )
        .expect("basic query failed");
        assert!(q.vma_start < q.vma_end);

        let perms = ProcmapQueryFlags::from_bits_truncate(q.vma_flags);
        assert!(perms.contains(ProcmapQueryFlags::VMA_READABLE));

        assert_eq!(q.vma_name_addr, 0);
        assert_eq!(q.vma_name_size, 0);
    }

    #[test]
    fn test_procmap_query_3() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let mut buf = [0u8; PATH_MAX];
        let q = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA,
            0,
            Some(&mut buf),
            None,
        )
        .expect("query with name buffer failed");

        assert_eq!(q.vma_name_size as usize <= PATH_MAX, true);
        assert_ne!(q.vma_name_addr, 0);

        let slice = &buf[..q.vma_name_size as usize];
        let cstr = CStr::from_bytes_with_nul(slice).expect("vma name buffer not NUL terminated");
        assert!(!cstr.to_bytes().is_empty(), "empty VMA name");
    }

    #[test]
    fn test_procmap_query_4() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let mut name_buf = [0u8; 512];
        let mut build_buf = [0u8; 64];
        let q = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA | ProcmapQueryFlags::FILE_BACKED_VMA,
            0,
            Some(&mut name_buf),
            Some(&mut build_buf),
        )
        .expect("query with both buffers failed");

        assert!(q.build_id_size as usize <= build_buf.len());

        let slice = &name_buf[..q.vma_name_size as usize];
        let _ = CStr::from_bytes_with_nul(slice).expect("invalid VMA name");
    }

    #[test]
    fn test_procmap_query_5() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let flags = ProcmapQueryFlags::COVERING_OR_NEXT_VMA | ProcmapQueryFlags::FILE_BACKED_VMA;
        let mut addr = 0;
        let mut buf = [0u8; PATH_MAX];
        let mut seen = 0;

        loop {
            match procmap_query(&maps, flags, addr, Some(&mut buf), None) {
                Ok(q) => {
                    assert!(q.vma_start < q.vma_end);
                    seen += 1;
                    addr = q.vma_end;
                }
                Err(Errno::ENOENT) => break,
                Err(errno) => panic!("unexpected error during iteration: {errno}"),
            }
        }

        assert!(seen > 0, "expected to see at least one VMA!");
    }

    #[test]
    fn test_procmap_query_6() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let flags = ProcmapQueryFlags::COVERING_OR_NEXT_VMA
            | ProcmapQueryFlags::FILE_BACKED_VMA
            | ProcmapQueryFlags::VMA_EXECUTABLE;
        let mut addr = 0;
        let mut buf = [0u8; PATH_MAX];
        let mut found_exec = false;

        loop {
            match procmap_query(&maps, flags, addr, Some(&mut buf), None) {
                Ok(q) => {
                    let perms = ProcmapQueryFlags::from_bits_truncate(q.vma_flags);
                    assert!(perms.contains(ProcmapQueryFlags::VMA_EXECUTABLE));
                    found_exec = true;
                    addr = q.vma_end;
                }
                Err(Errno::ENOENT) => break,
                Err(errno) => panic!("unexpected error: {errno}"),
            }
        }

        assert!(found_exec, "no executable VMAs found!");
    }

    #[test]
    fn test_procmap_query_7() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let mut build_buf = [0u8; 64];
        let q = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA,
            0,
            None,
            Some(&mut build_buf),
        )
        .expect("query build-id only failed");

        assert_eq!(q.vma_name_addr, 0);
        assert_eq!(q.vma_name_size, 0);

        assert!(q.build_id_size as usize <= build_buf.len());

        if q.build_id_size > 0 {
            let _ = &build_buf[..q.build_id_size as usize];
        }
    }

    #[test]
    fn test_procmap_query_8() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let q = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA,
            0,
            None,
            None,
        )
        .expect("basic query failed");

        assert!(q.vma_page_size > 0);

        let vma_len = q.vma_end - q.vma_start;
        assert!(q.vma_offset <= vma_len);
    }

    #[test]
    fn test_procmap_query_9() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let flags = ProcmapQueryFlags::COVERING_OR_NEXT_VMA;
        let mut addr = 0;
        let mut seen_addrs = Vec::new();

        for _ in 0..2 {
            let q = procmap_query(&maps, flags, addr, None, None).expect("query iteration failed");
            seen_addrs.push(q.vma_start);
            addr = q.vma_end;
        }

        assert_eq!(seen_addrs.len(), 2);
        assert!(seen_addrs[0] < seen_addrs[1], "VMAs did not advance!");
    }

    #[test]
    fn test_procmap_query_10() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let mut buf = [0u8; 1];
        let err = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA | ProcmapQueryFlags::FILE_BACKED_VMA,
            0,
            Some(&mut buf),
            None,
        )
        .unwrap_err();
        assert_eq!(err, Errno::ENAMETOOLONG);
    }

    #[test]
    fn test_procmap_query_11() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let result = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA,
            u64::MAX,
            None,
            None,
        );
        assert_eq!(result.unwrap_err(), Errno::ENOENT);
    }

    #[test]
    fn test_procmap_query_12() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let q = procmap_query(
            &maps,
            ProcmapQueryFlags::COVERING_OR_NEXT_VMA,
            0,
            None,
            None,
        )
        .unwrap();
        assert_eq!(q.size as usize, size_of::<ProcmapQuery>());
    }

    #[test]
    fn test_procmap_query_13() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let flags = ProcmapQueryFlags::COVERING_OR_NEXT_VMA
            | ProcmapQueryFlags::FILE_BACKED_VMA
            | ProcmapQueryFlags::VMA_WRITABLE;
        let mut addr = 0;
        let mut count = 0;
        let mut buf = [0u8; 256];
        while let Ok(q) = procmap_query(&maps, flags, addr, Some(&mut buf), None) {
            let perms = ProcmapQueryFlags::from_bits_truncate(q.vma_flags);
            assert!(perms.contains(ProcmapQueryFlags::VMA_WRITABLE));
            count += 1;
            addr = q.vma_end;
        }
        assert!(count > 0, "expected at least one writable VMA");
    }

    #[test]
    fn test_procmap_query_14() {
        skip_if_procmap_query_not_supported!();

        let maps = File::open("/proc/self/maps").unwrap();

        let flags = ProcmapQueryFlags::COVERING_OR_NEXT_VMA | ProcmapQueryFlags::FILE_BACKED_VMA;
        let mut buf = [0u8; 512];

        let q = procmap_query(&maps, flags, 0, Some(&mut buf), None).unwrap();
        assert!(
            q.inode != 0,
            "expected inode of a file-backed VMA to be non-zero"
        );
    }

    #[test]
    fn test_proc_executables_1() {
        if !setup() {
            return;
        }

        let list = proc_executables(Pid::this()).expect("expected executables");
        assert!(!list.is_empty(), "no executables found for self");
    }

    #[test]
    fn test_proc_executables_2() {
        if !setup() {
            return;
        }

        let bins = proc_executables(Pid::this()).unwrap();
        let mut seen: SydIndexSet<XPathBuf> = SydIndexSet::default();
        for bin in &bins {
            let path = &bin.path;
            assert!(
                seen.try_insert(path.try_clone().unwrap()).unwrap(),
                "duplicate path {path}!"
            );
        }

        let collected: Vec<_> = seen.into_iter().collect();
        let returned: Vec<_> = bins
            .iter()
            .map(|bin| bin.path.try_clone().unwrap())
            .collect();
        assert_eq!(collected, returned);
    }

    #[test]
    fn test_proc_executables_3() {
        if !setup() {
            return;
        }

        let bins = proc_executables(Pid::this()).unwrap();
        for (idx, bin) in bins.into_iter().enumerate() {
            let path = bin.path;
            let md = std::fs::metadata(&path).expect("path does not exist");
            if idx == 0 {
                let perms = md.permissions().mode();
                assert!(
                    perms & 0o111 != 0,
                    "file {path} is not executable (mode {perms:o})",
                );
            }
        }
    }

    #[test]
    fn test_proc_find_vma() {
        if !setup() {
            return;
        }

        let pid = Pid::this();
        for flags in [
            ProcmapQueryFlags::VMA_READABLE,
            ProcmapQueryFlags::VMA_EXECUTABLE,
            ProcmapQueryFlags::VMA_READABLE | ProcmapQueryFlags::VMA_EXECUTABLE,
        ] {
            let vmas = proc_find_vma(pid, flags).unwrap();
            assert!(!vmas.is_empty());
            for vma in vmas {
                assert!(vma.flags().contains(flags));
            }
        }
    }
}