Skip to main content

syscall/
flag.rs

1use bitflags::bitflags as inner_bitflags;
2use core::{mem, ops::Deref, slice};
3
4macro_rules! bitflags {
5    (
6        $(#[$outer:meta])*
7        pub struct $BitFlags:ident: $T:ty {
8            $(
9                $(#[$inner:ident $($args:tt)*])*
10                const $Flag:ident = $value:expr;
11            )+
12        }
13    ) => {
14        // First, use the inner bitflags
15        inner_bitflags! {
16            #[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy, Default)]
17            $(#[$outer])*
18            pub struct $BitFlags: $T {
19                $(
20                    $(#[$inner $($args)*])*
21                    const $Flag = $value;
22                )+
23            }
24        }
25
26        impl $BitFlags {
27            #[deprecated = "use the safe `from_bits_retain` method instead"]
28            pub unsafe fn from_bits_unchecked(bits: $T) -> Self {
29                Self::from_bits_retain(bits)
30            }
31        }
32
33        // Secondly, re-export all inner constants
34        // (`pub use self::Struct::*` doesn't work)
35        $(
36            $(#[$inner $($args)*])*
37            pub const $Flag: $BitFlags = $BitFlags::$Flag;
38        )+
39    }
40}
41
42pub const CLOCK_REALTIME: usize = 1;
43pub const CLOCK_MONOTONIC: usize = 4;
44
45bitflags! {
46    pub struct EventFlags: usize {
47        const EVENT_NONE = 0;
48        const EVENT_READ = 1;
49        const EVENT_WRITE = 2;
50    }
51}
52
53pub const F_DUPFD: usize = 0;
54pub const F_GETFD: usize = 1;
55pub const F_SETFD: usize = 2;
56pub const F_GETFL: usize = 3;
57pub const F_SETFL: usize = 4;
58pub const F_GET_SCHEMEID: usize = 0x1000 | 1;
59
60pub const FUTEX_WAIT: usize = 0;
61pub const FUTEX_WAKE: usize = 1;
62pub const FUTEX_REQUEUE: usize = 2;
63pub const FUTEX_WAIT64: usize = 3;
64
65// TODO: Split SendFdFlags into caller flags and flags that the scheme receives?
66bitflags::bitflags! {
67    #[derive(Clone, Copy, Debug)]
68    pub struct SendFdFlags: usize {
69        /// If set, the kernel will enforce that the file descriptors are exclusively owned.
70        ///
71        /// That is, there will no longer exist any other reference to those FDs when removed from
72        /// the file table (sendfd always removes the FDs from the file table, but without this
73        /// flag, it can be retained by SYS_DUPing them first).
74        const EXCLUSIVE = 1;
75
76        /// If set, the file descriptors will be cloned and *not* removed from the sender's file table.
77        /// By default, `SYS_SENDFD` moves the file descriptors, removing them from the sender.
78        const CLONE = 2;
79    }
80}
81bitflags::bitflags! {
82    #[derive(Clone, Copy, Debug)]
83    pub struct FobtainFdFlags: usize {
84        /// If set, the SYS_CALL payload specifies the destination file descriptor slots, otherwise the lowest
85        /// available slots will be selected, and placed in the usize pointed to by SYS_CALL
86        /// payload.
87        const MANUAL_FD = 1;
88
89        /// If set, the file descriptors received are guaranteed to be exclusively owned (by the file
90        /// table the obtainer is running in).
91        const EXCLUSIVE = 2;
92
93        /// If set, the file descriptors received will be placed into the *upper* file table.
94        const UPPER_TBL = 4;
95
96        /// If set, the received file descriptors are marked as close-on-exec.
97        const CLOEXEC = 8;
98
99        // No, cloexec won't be stored in the kernel in the future, when the stable ABI is moved to
100        // relibc, so no flag for that!
101    }
102}
103bitflags::bitflags! {
104    #[derive(Clone, Copy, Debug)]
105    pub struct RecvFdFlags: usize {
106        /// If set, the SYS_CALL payload specifies the destination file descriptor slots, otherwise the lowest
107        /// available slots will be selected, and placed in the usize pointed to by SYS_CALL
108        /// payload.
109        const MANUAL_FD = 1;
110
111        /// If set, the file descriptors received will be placed into the *upper* file table.
112        const UPPER_TBL = 2;
113
114        /// If set, the received file descriptors are marked as close-on-exec.
115        const CLOEXEC = 4;
116    }
117}
118bitflags::bitflags! {
119    #[derive(Clone, Copy, Debug)]
120    pub struct FmoveFdFlags: usize {
121        /// If set, the kernel will enforce that the file descriptors are exclusively owned.
122        ///
123        /// That is, there will no longer exist any other reference to those FDs when removed from
124        /// the file table (SYS_CALL always removes the FDs from the file table, but without this
125        /// flag, it can be retained by SYS_DUPing them first).
126        const EXCLUSIVE = 1;
127
128        /// If set, the file descriptors will be cloned and *not* removed from the sender's file table.
129        /// By default, sendfd moves the file descriptors, removing them from the sender.
130        const CLONE = 2;
131    }
132}
133
134bitflags! {
135    pub struct MapFlags: usize {
136        // TODO: Downgrade PROT_NONE to global constant? (bitflags specifically states zero flags
137        // can cause buggy behavior).
138        const PROT_NONE = 0x0000_0000;
139
140        const PROT_EXEC = 0x0001_0000;
141        const PROT_WRITE = 0x0002_0000;
142        const PROT_READ = 0x0004_0000;
143
144        const MAP_SHARED = 0x0001;
145        const MAP_PRIVATE = 0x0002;
146
147        const MAP_FIXED = 0x0004;
148        const MAP_FIXED_NOREPLACE = 0x000C;
149
150        /// For *userspace-backed mmaps*, return from the mmap call before all pages have been
151        /// provided by the scheme. This requires the scheme to be trusted, as the current context
152        /// can block indefinitely, if the scheme does not respond to the page fault handler's
153        /// request, as it tries to map the page by requesting it from the scheme.
154        ///
155        /// In some cases however, such as the program loader, the data needs to be trusted as much
156        /// with or without MAP_LAZY, and if so, mapping lazily will not cause insecureness by
157        /// itself.
158        ///
159        /// For kernel-backed mmaps, this flag has no effect at all. It is unspecified whether
160        /// kernel mmaps are lazy or not.
161        const MAP_LAZY = 0x0010;
162    }
163}
164bitflags! {
165    pub struct MunmapFlags: usize {
166        /// Indicates whether the funmap call must implicitly do an msync, for the changes to
167        /// become visible later.
168        ///
169        /// This flag will currently be set if and only if MAP_SHARED | PROT_WRITE are set.
170        const NEEDS_SYNC = 1;
171    }
172}
173
174pub const MODE_TYPE: u16 = 0xF000;
175pub const MODE_DIR: u16 = 0x4000;
176pub const MODE_FILE: u16 = 0x8000;
177pub const MODE_SYMLINK: u16 = 0xA000;
178pub const MODE_FIFO: u16 = 0x1000;
179pub const MODE_CHR: u16 = 0x2000;
180pub const MODE_SOCK: u16 = 0xC000;
181
182pub const MODE_PERM: u16 = 0x0FFF;
183pub const MODE_SETUID: u16 = 0o4000;
184pub const MODE_SETGID: u16 = 0o2000;
185
186pub const O_RDONLY: usize = 0x0001_0000;
187pub const O_WRONLY: usize = 0x0002_0000;
188pub const O_RDWR: usize = 0x0003_0000;
189pub const O_NONBLOCK: usize = 0x0004_0000;
190pub const O_APPEND: usize = 0x0008_0000;
191pub const O_SHLOCK: usize = 0x0010_0000;
192pub const O_EXLOCK: usize = 0x0020_0000;
193pub const O_ASYNC: usize = 0x0040_0000;
194pub const O_FSYNC: usize = 0x0080_0000;
195pub const O_CREAT: usize = 0x0200_0000;
196pub const O_TRUNC: usize = 0x0400_0000;
197pub const O_EXCL: usize = 0x0800_0000;
198pub const O_DIRECTORY: usize = 0x1000_0000;
199pub const O_STAT: usize = 0x2000_0000;
200pub const O_SYMLINK: usize = 0x4000_0000;
201pub const O_NOFOLLOW: usize = 0x8000_0000;
202pub const O_ACCMODE: usize = O_RDONLY | O_WRONLY | O_RDWR;
203pub const O_FCNTL_MASK: usize = O_NONBLOCK | O_APPEND | O_ASYNC | O_FSYNC;
204
205/// Remove directory instead of unlinking file.
206pub const AT_REMOVEDIR: usize = 0x200;
207
208// The top 48 bits of PTRACE_* are reserved, for now
209
210// NOT ABI STABLE!
211#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
212#[repr(usize)]
213pub enum ContextStatus {
214    Runnable,
215    Blocked,
216    NotYetStarted,
217    Dead,
218    ForceKilled,
219    Stopped,
220    UnhandledExcp,
221    #[default]
222    Other, // reserved
223}
224
225#[derive(Clone, Copy, Debug, Eq, PartialEq)]
226#[repr(usize)]
227#[allow(clippy::enum_clike_unportable_variant)]
228pub enum ContextVerb {
229    Stop = 1,
230    Unstop = 2,
231    Interrupt = 3,
232    // XXX: false positive: https://github.com/rust-lang/rust-clippy/issues/8043
233    ForceKill = usize::MAX,
234}
235impl ContextVerb {
236    pub fn try_from_raw(raw: usize) -> Option<Self> {
237        Some(match raw {
238            1 => Self::Stop,
239            2 => Self::Unstop,
240            3 => Self::Interrupt,
241            usize::MAX => Self::ForceKill,
242            _ => return None,
243        })
244    }
245}
246
247// NOT ABI STABLE!
248#[derive(Clone, Copy, Debug, Eq, PartialEq)]
249#[repr(u8)]
250pub enum AddrSpaceVerb {
251    MmapMin = 255,
252}
253impl AddrSpaceVerb {
254    pub fn try_from_raw(verb: u8) -> Option<Self> {
255        Some(match verb {
256            255 => Self::MmapMin,
257
258            _ => return None,
259        })
260    }
261}
262
263// NOT ABI STABLE!
264#[derive(Clone, Copy, Debug, Eq, PartialEq)]
265#[repr(u8)]
266pub enum ProcSchemeVerb {
267    RegsInt = 250,
268    RegsFloat = 251,
269    RegsEnv = 252,
270    SchedAffinity = 253,
271    Start = 254,
272    Iopl = 255,
273}
274impl ProcSchemeVerb {
275    pub fn try_from_raw(verb: u8) -> Option<Self> {
276        Some(match verb {
277            250 => Self::RegsInt,
278            251 => Self::RegsFloat,
279            252 => Self::RegsEnv,
280            253 => Self::SchedAffinity,
281            254 => Self::Start,
282            255 => Self::Iopl,
283            _ => return None,
284        })
285    }
286}
287
288#[derive(Clone, Copy, Debug, Eq, PartialEq)]
289pub enum FileTableVerb {
290    Close = 1,
291    Dup2 = 2,
292    Reserved1 = 3,
293    Resize = 4,
294    Refresh = 5,
295    Move = 6,
296    Swap = 7,
297}
298impl FileTableVerb {
299    pub fn try_from_raw(value: u8) -> Option<Self> {
300        Some(match value {
301            1 => Self::Close,
302            2 => Self::Dup2,
303            3 => Self::Reserved1,
304            4 => Self::Resize,
305            5 => Self::Refresh,
306            6 => Self::Move,
307            7 => Self::Swap,
308            _ => return None,
309        })
310    }
311}
312
313/// NOT ABI-STABLE!
314#[derive(Clone, Copy, Debug, Eq, PartialEq)]
315#[repr(u64)]
316pub enum AcpiVerb {
317    // copies the rsdt/xsdt to the payload buffer (the number of bytes that fit), and returns the
318    // rsdt/xsdt length regardless
319    ReadRxsdt = 1,
320    // no payload, just returns 0 or 1
321    CheckShutdown = 2,
322    // reads and/or writes from/to an MSR specified in metadata[1], where the data is passed in
323    // `payload`.
324    Msr = 3,
325}
326impl AcpiVerb {
327    pub const fn try_from_raw(value: u64) -> Option<Self> {
328        Some(match value {
329            1 => Self::ReadRxsdt,
330            2 => Self::CheckShutdown,
331            3 => Self::Msr,
332            _ => return None,
333        })
334    }
335}
336
337#[derive(Clone, Copy, Debug, Eq, PartialEq)]
338pub enum NumaVerb {
339    MemPolicy = 1,
340}
341impl NumaVerb {
342    pub fn try_from_raw(value: u64) -> Option<Self> {
343        Some(match value {
344            1 => Self::MemPolicy,
345            _ => return None,
346        })
347    }
348}
349
350#[derive(Clone, Copy, Debug, Eq, PartialEq)]
351#[repr(usize)]
352pub enum SchemeSocketCall {
353    ObtainFd = 0,
354    MoveFd = 1,
355}
356impl SchemeSocketCall {
357    pub fn try_from_raw(raw: usize) -> Option<Self> {
358        Some(match raw {
359            0 => Self::ObtainFd,
360            1 => Self::MoveFd,
361            _ => return None,
362        })
363    }
364}
365
366#[derive(Clone, Copy, Debug, Eq, PartialEq)]
367#[repr(usize)]
368#[non_exhaustive]
369pub enum FsCall {
370    Connect = 0,
371}
372impl FsCall {
373    pub fn try_from_raw(raw: usize) -> Option<Self> {
374        Some(match raw {
375            0 => Self::Connect,
376            _ => return None,
377        })
378    }
379}
380
381bitflags! {
382    pub struct PtraceFlags: u64 {
383        /// Stop before a syscall is handled. Send PTRACE_FLAG_IGNORE to not
384        /// handle the syscall.
385        const PTRACE_STOP_PRE_SYSCALL = 0x0000_0000_0000_0001;
386        /// Stop after a syscall is handled.
387        const PTRACE_STOP_POST_SYSCALL = 0x0000_0000_0000_0002;
388        /// Stop after exactly one instruction. TODO: This may not handle
389        /// fexec/signal boundaries. Should it?
390        const PTRACE_STOP_SINGLESTEP = 0x0000_0000_0000_0004;
391        /// Stop before a signal is handled. Send PTRACE_FLAG_IGNORE to not
392        /// handle signal.
393        const PTRACE_STOP_SIGNAL = 0x0000_0000_0000_0008;
394        /// Stop on a software breakpoint, such as the int3 instruction for
395        /// x86_64.
396        const PTRACE_STOP_BREAKPOINT = 0x0000_0000_0000_0010;
397        /// Stop just before exiting for good.
398        const PTRACE_STOP_EXIT = 0x0000_0000_0000_0020;
399
400        const PTRACE_STOP_MASK = 0x0000_0000_0000_00FF;
401
402
403        /// Sent when a child is cloned, giving you the opportunity to trace it.
404        /// If you don't catch this, the child is started as normal.
405        const PTRACE_EVENT_CLONE = 0x0000_0000_0000_0100;
406
407        /// Sent when current-addrspace is changed, allowing the tracer to reopen the memory file.
408        const PTRACE_EVENT_ADDRSPACE_SWITCH = 0x0000_0000_0000_0200;
409
410        const PTRACE_EVENT_MASK = 0x0000_0000_0000_0F00;
411
412        /// Special meaning, depending on the event. Usually, when fired before
413        /// an action, it will skip performing that action.
414        const PTRACE_FLAG_IGNORE = 0x0000_0000_0000_1000;
415
416        const PTRACE_FLAG_MASK = 0x0000_0000_0000_F000;
417    }
418}
419impl Deref for PtraceFlags {
420    type Target = [u8];
421    fn deref(&self) -> &Self::Target {
422        // Same as to_ne_bytes but in-place
423        unsafe {
424            slice::from_raw_parts(&self.bits() as *const _ as *const u8, mem::size_of::<u64>())
425        }
426    }
427}
428
429pub const SEEK_SET: usize = 0;
430pub const SEEK_CUR: usize = 1;
431pub const SEEK_END: usize = 2;
432
433pub const SIGCHLD: usize = 17;
434pub const SIGTSTP: usize = 20;
435pub const SIGTTIN: usize = 21;
436pub const SIGTTOU: usize = 22;
437
438pub const ADDRSPACE_OP_MMAP: usize = 0;
439pub const ADDRSPACE_OP_MUNMAP: usize = 1;
440pub const ADDRSPACE_OP_MPROTECT: usize = 2;
441pub const ADDRSPACE_OP_TRANSFER: usize = 3;
442
443bitflags! {
444    pub struct MremapFlags: usize {
445        const FIXED = 1;
446        const FIXED_REPLACE = 3;
447        /// Alias's memory region at `old_address` to `new_address` such that both regions share
448        /// the same frames.
449        const KEEP_OLD = 1 << 2;
450        // TODO: MAYMOVE, DONTUNMAP
451    }
452}
453bitflags! {
454    pub struct RwFlags: u32 {
455        const NONBLOCK = 1;
456        const APPEND = 2;
457        // TODO: sync/dsync
458        // TODO: O_DIRECT?
459    }
460}
461bitflags! {
462    pub struct SigcontrolFlags: usize {
463        /// Prevents the kernel from jumping the context to the signal trampoline, but otherwise
464        /// has absolutely no effect on which signals are blocked etc. Meant to be used for
465        /// short-lived critical sections inside libc.
466        const INHIBIT_DELIVERY = 1;
467        /// Indicates userspace is running an exception handler, which means any new synchronous
468        /// exception will result in the termination of the current context ("double fault").
469        const HANDLING_EXCEPTION = 2;
470    }
471}
472bitflags! {
473    pub struct CallFlags: usize {
474        // reserved
475        const RSVD0 = 1 << 0;
476        const RSVD1 = 1 << 1;
477        const RSVD2 = 1 << 2;
478        const RSVD3 = 1 << 3;
479        const RSVD4 = 1 << 4;
480        const RSVD5 = 1 << 5;
481        const RSVD6 = 1 << 6;
482        const RSVD7 = 1 << 7;
483
484        /// Remove the fd from the caller's file table before sending the message.
485        const CONSUME = 1 << 8;
486
487        const WRITE = 1 << 9;
488        const READ = 1 << 10;
489
490        /// Indicates the request is a bulk fd passing request.
491        const FD = 1 << 11;
492        /// Flags for the fd passing request.
493        const FD_EXCLUSIVE = 1 << 12;
494        const FD_CLONE = 1 << 13;
495        const FD_UPPER = 1 << 14;
496        const FD_CLOEXEC = 1 << 15;
497
498        /// Call is a standard fs call, with metadata defined in `StdFsCallMeta`
499        const STD_FS = 1 << 16;
500
501        // reserved: 1 << 17
502
503        /// Allow current timeslice to be lent out to the callee, which will have a preference of
504        /// switching back to this context until the current timeslice is exhausted, after which
505        /// the scheduler will continue as if it was switching away from this context.
506        const ALLOW_DIRECT_SWITCH = 1 << 18;
507
508        /// Call is taking multiple fds, syscall5 variant.
509        const MULTIPLE_FDS2 = 1 << 19;
510    }
511}
512
513#[repr(u8)]
514#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
515pub enum StdFsCallKind {
516    // TODO: remove old syscalls
517    Fchmod = 1,
518    Fchown = 2,
519    Getdents = 3,
520    Fstat = 4,
521    Fstatvfs = 5,
522    Fsync = 6,
523    Ftruncate = 7,
524    Futimens = 8,
525    // 9 reserved in fscall RFC
526    Unlinkat = 10,
527    Relpathat = 11,
528    Lock = 12,
529    Unlock = 13,
530    GetLock = 14,
531    Frenameat = 15,
532    Flinkat = 16,
533}
534
535impl StdFsCallKind {
536    pub fn try_from_raw(raw: u8) -> Option<Self> {
537        use StdFsCallKind::*;
538
539        // TODO: Use a library where this match can be automated.
540        Some(match raw {
541            1 => Fchmod,
542            2 => Fchown,
543            3 => Getdents,
544            4 => Fstat,
545            5 => Fstatvfs,
546            6 => Fsync,
547            7 => Ftruncate,
548            8 => Futimens,
549            // 9 reserved in fscall RFC
550            10 => Unlinkat,
551            11 => Relpathat,
552            12 => Lock,
553            13 => Unlock,
554            14 => GetLock,
555            15 => Frenameat,
556            16 => Flinkat,
557            _ => return None,
558        })
559    }
560}
561
562/// The tag for the fd number in the upper file descriptor table.
563pub const UPPER_FDTBL_TAG: usize = 1 << (usize::BITS - 2);
564
565/// The identifier for registering event timeout
566pub const EVENT_TIMEOUT_ID: usize = usize::MAX - 2;