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
//! Linux system call interface
//!
//! This module provides a safe, cross-architecture abstraction over Linux system calls.
//! Architecture-specific details are handled transparently.

use core::fmt;
use core::mem;
use thiserror::Error;

// Architecture-specific modules
#[cfg(target_arch = "x86_64")]
#[path = "arch_x86_64.rs"]
pub mod arch_x86_64;

#[cfg(target_arch = "aarch64")]
#[path = "arch_aarch64.rs"]
pub mod arch_aarch64;

// Architecture alias for current platform
#[cfg(target_arch = "x86_64")]
use arch_x86_64 as arch;

#[cfg(target_arch = "aarch64")]
use arch_aarch64 as arch;

// Re-export architecture-specific items
pub use arch::SysCall;

// Re-export syscall macro from architecture module
use arch::syscall;

// Platform constants
pub mod constants {
    /// Memory page size for the current architecture
    pub const PAGE_SIZE: usize = 4096;

    /// Terminal ioctl constants
    pub const TCGETS: u64 = 0x5401;
    pub const TCSETS: u64 = 0x5402;
}

/// Type alias for syscall results
pub type Result<T> = core::result::Result<T, SyscallError>;

/// System call error
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("{errno}")]
pub struct SyscallError {
    errno: Errno,
}

impl SyscallError {
    #[inline]
    pub const fn new(errno: Errno) -> Self {
        Self { errno }
    }

    #[inline]
    pub const fn errno(&self) -> Errno {
        self.errno
    }

    #[inline]
    pub const fn raw(&self) -> i32 {
        self.errno as i32
    }
}

impl From<Errno> for SyscallError {
    #[inline]
    fn from(errno: Errno) -> Self {
        Self { errno }
    }
}

/// Linux error numbers
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
pub enum Errno {
    /// Operation not permitted
    Perm = 1,
    /// No such file or directory
    NoEnt = 2,
    /// No such process
    Srch = 3,
    /// Interrupted system call
    Intr = 4,
    /// I/O error
    Io = 5,
    /// No such device or address
    NxIo = 6,
    /// Argument list too long
    TooBig = 7,
    /// Exec format error
    NoExec = 8,
    /// Bad file descriptor
    BadF = 9,
    /// No child processes
    Child = 10,
    /// Try again / Would block
    Again = 11,
    /// Out of memory
    NoMem = 12,
    /// Permission denied
    Acces = 13,
    /// Bad address
    Fault = 14,
    /// Block device required
    NotBlk = 15,
    /// Device or resource busy
    Busy = 16,
    /// File exists
    Exist = 17,
    /// Cross-device link
    XDev = 18,
    /// No such device
    NoDev = 19,
    /// Not a directory
    NotDir = 20,
    /// Is a directory
    IsDir = 21,
    /// Invalid argument
    Inval = 22,
    /// File table overflow
    NFile = 23,
    /// Too many open files
    MFile = 24,
    /// Not a typewriter
    NotTy = 25,
    /// Text file busy
    TxtBsy = 26,
    /// File too large
    FBig = 27,
    /// No space left on device
    NoSpc = 28,
    /// Illegal seek
    SPipe = 29,
    /// Read-only file system
    RoFs = 30,
    /// Too many links
    MLink = 31,
    /// Broken pipe
    Pipe = 32,
    /// Math argument out of domain
    Dom = 33,
    /// Math result not representable
    Range = 34,
    /// Resource deadlock would occur
    DeadLk = 35,
    /// File name too long
    NameTooLong = 36,
    /// No record locks available
    NoLck = 37,
    /// Function not implemented
    NoSys = 38,
    /// Directory not empty
    NotEmpty = 39,
    /// Too many symbolic links encountered
    Loop = 40,
    /// No message of desired type
    NoMsg = 42,
    /// Identifier removed
    IdRm = 43,
    // Network errors
    /// Network is down
    NetDown = 100,
    /// Network is unreachable
    NetUnreach = 101,
    /// Network dropped connection because of reset
    NetReset = 102,
    /// Software caused connection abort
    ConnAborted = 103,
    /// Connection reset by peer
    ConnReset = 104,
    /// No buffer space available
    NoBufs = 105,
    /// Transport endpoint is already connected
    IsConn = 106,
    /// Transport endpoint is not connected
    NotConn = 107,
    /// Cannot send after transport endpoint shutdown
    Shutdown = 108,
    /// Too many references: cannot splice
    TooManyRefs = 109,
    /// Connection timed out
    TimedOut = 110,
    /// Connection refused
    ConnRefused = 111,
    /// Host is down
    HostDown = 112,
    /// No route to host
    HostUnreach = 113,
    /// Operation already in progress
    Already = 114,
    /// Operation now in progress
    InProgress = 115,
    /// Stale file handle
    Stale = 116,
}

impl Errno {
    /// Convert from raw errno value using transmute for known values
    #[inline]
    pub fn from_raw(errno: i32) -> Option<Self> {
        // Check if it's a valid errno value we know about
        match errno {
            1..=40 | 42..=43 | 100..=116 => {
                // Safety: We've verified the value matches a valid discriminant
                // The repr(i32) attribute guarantees the layout
                Some(unsafe { core::mem::transmute::<i32, Errno>(errno) })
            }
            _ => None,
        }
    }

    /// Get errno as raw i32 value
    #[inline]
    pub const fn as_raw(&self) -> i32 {
        *self as i32
    }

    /// Check if this error indicates the operation should be retried
    #[inline]
    pub const fn should_retry(&self) -> bool {
        matches!(self, Self::Again | Self::Intr)
    }

    /// Check if this error is temporary
    #[inline]
    pub const fn is_temporary(&self) -> bool {
        matches!(self, Self::Again | Self::Intr | Self::InProgress)
    }
}

impl fmt::Display for Errno {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let desc = match self {
            Self::Perm => "Operation not permitted",
            Self::NoEnt => "No such file or directory",
            Self::Srch => "No such process",
            Self::Intr => "Interrupted system call",
            Self::Io => "I/O error",
            Self::NxIo => "No such device or address",
            Self::TooBig => "Argument list too long",
            Self::NoExec => "Exec format error",
            Self::BadF => "Bad file descriptor",
            Self::Child => "No child processes",
            Self::Again => "Resource temporarily unavailable",
            Self::NoMem => "Out of memory",
            Self::Acces => "Permission denied",
            Self::Fault => "Bad address",
            Self::NotBlk => "Block device required",
            Self::Busy => "Device or resource busy",
            Self::Exist => "File exists",
            Self::XDev => "Cross-device link",
            Self::NoDev => "No such device",
            Self::NotDir => "Not a directory",
            Self::IsDir => "Is a directory",
            Self::Inval => "Invalid argument",
            Self::NFile => "File table overflow",
            Self::MFile => "Too many open files",
            Self::NotTy => "Not a typewriter",
            Self::TxtBsy => "Text file busy",
            Self::FBig => "File too large",
            Self::NoSpc => "No space left on device",
            Self::SPipe => "Illegal seek",
            Self::RoFs => "Read-only file system",
            Self::MLink => "Too many links",
            Self::Pipe => "Broken pipe",
            Self::Dom => "Math argument out of domain",
            Self::Range => "Math result not representable",
            Self::DeadLk => "Resource deadlock would occur",
            Self::NameTooLong => "File name too long",
            Self::NoLck => "No record locks available",
            Self::NoSys => "Function not implemented",
            Self::NotEmpty => "Directory not empty",
            Self::Loop => "Too many symbolic links encountered",
            Self::NoMsg => "No message of desired type",
            Self::IdRm => "Identifier removed",
            Self::NetDown => "Network is down",
            Self::NetUnreach => "Network is unreachable",
            Self::NetReset => "Network dropped connection on reset",
            Self::ConnAborted => "Software caused connection abort",
            Self::ConnReset => "Connection reset by peer",
            Self::NoBufs => "No buffer space available",
            Self::IsConn => "Transport endpoint is already connected",
            Self::NotConn => "Transport endpoint is not connected",
            Self::Shutdown => "Cannot send after transport endpoint shutdown",
            Self::TooManyRefs => "Too many references: cannot splice",
            Self::TimedOut => "Connection timed out",
            Self::ConnRefused => "Connection refused",
            Self::HostDown => "Host is down",
            Self::HostUnreach => "No route to host",
            Self::Already => "Operation already in progress",
            Self::InProgress => "Operation now in progress",
            Self::Stale => "Stale file handle",
        };
        write!(f, "{} ({})", desc, *self as i32)
    }
}

/// Check syscall return value and convert to Result
#[inline]
pub fn check_ret(ret: i64) -> Result<i64> {
    if ret < 0 {
        let errno = (-ret) as i32;
        Errno::from_raw(errno)
            .map(SyscallError::from)
            .map(Err)
            .unwrap_or(Err(SyscallError::from(Errno::NoSys)))
    } else {
        Ok(ret)
    }
}

// Common flag types used across architectures

/// Generic flag trait for type-safe flag operations
pub trait Flag: Copy + Clone {
    fn as_raw(&self) -> i32;

    fn combine(self, other: Self) -> i32 {
        self.as_raw() | other.as_raw()
    }
}

/// Bitflags helper for combining multiple flags
#[derive(Debug, Clone, Copy)]
pub struct Flags<T: Flag> {
    value: i32,
    _phantom: core::marker::PhantomData<T>,
}

impl<T: Flag> Flags<T> {
    pub const fn new() -> Self {
        Self {
            value: 0,
            _phantom: core::marker::PhantomData,
        }
    }

    pub const fn from_raw(value: i32) -> Self {
        Self {
            value,
            _phantom: core::marker::PhantomData,
        }
    }

    pub fn with(mut self, flag: T) -> Self {
        self.value |= flag.as_raw();
        self
    }

    pub const fn as_raw(&self) -> i32 {
        self.value
    }

    pub fn contains(&self, flag: T) -> bool {
        (self.value & flag.as_raw()) != 0
    }
}

// Common structures (same across architectures)

/// Time specification
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct TimeSpec {
    pub tv_sec: i64,
    pub tv_nsec: i64,
}

/// I/O vector for scatter-gather I/O
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct IoVec {
    pub iov_base: *mut u8,
    pub iov_len: usize,
}

/// Socket address
#[repr(C)]
#[derive(Debug, Clone, Copy)]
pub struct SockAddr {
    pub sa_family: u16,
    pub sa_data: [u8; 14],
}

// Re-export common enums for flags

/// Open flags
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpenFlag {
    /// Open for reading only
    RdOnly = 0,
    /// Open for writing only
    WrOnly = 1,
    /// Open for reading and writing
    RdWr = 2,
    /// Create file if it doesn't exist
    Creat = 0x40,
    /// Fail if file exists
    Excl = 0x80,
    /// Don't follow symlinks
    NoFollow = 0x20000,
    /// Open in non-blocking mode
    NonBlock = 0x800,
    /// Close on exec
    CloExec = 0x80000,
}

impl Flag for OpenFlag {
    fn as_raw(&self) -> i32 {
        *self as i32
    }
}

/// Memory protection flags
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtFlag {
    /// No permissions
    None = 0,
    /// Read permission
    Read = 1,
    /// Write permission
    Write = 2,
    /// Execute permission
    Exec = 4,
}

impl Flag for ProtFlag {
    fn as_raw(&self) -> i32 {
        *self as i32
    }
}

/// Memory mapping flags
#[repr(i32)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MapFlag {
    /// Share changes
    Shared = 0x01,
    /// Changes are private
    Private = 0x02,
    /// Place at exact address
    Fixed = 0x10,
    /// Anonymous mapping
    Anonymous = 0x20,
    /// Populate page tables
    Populate = 0x8000,
}

impl Flag for MapFlag {
    fn as_raw(&self) -> i32 {
        *self as i32
    }
}

// Syscall wrapper functions

/// Read from a file descriptor
#[inline]
pub unsafe fn read(fd: i32, buf: *mut u8, count: usize) -> Result<usize> {
    check_ret(syscall!(SysCall::Read, fd, buf, count)).map(|n| n as usize)
}

/// Write to a file descriptor
#[inline]
pub unsafe fn write(fd: i32, buf: *const u8, count: usize) -> Result<usize> {
    check_ret(syscall!(SysCall::Write, fd, buf, count)).map(|n| n as usize)
}

/// Close a file descriptor
#[inline]
pub unsafe fn close(fd: i32) -> Result<()> {
    check_ret(syscall!(SysCall::Close, fd)).map(|_| ())
}

/// Map memory
#[inline]
pub unsafe fn mmap(
    addr: *mut u8,
    len: usize,
    prot: i32,
    flags: i32,
    fd: i32,
    offset: i64,
) -> Result<*mut u8> {
    let ret = syscall!(SysCall::Mmap, addr, len, prot, flags, fd, offset);
    if ret == -1 {
        Err(SyscallError::from(Errno::NoMem))
    } else {
        Ok(ret as *mut u8)
    }
}

/// Unmap memory
#[inline]
pub unsafe fn munmap(addr: *mut u8, len: usize) -> Result<()> {
    check_ret(syscall!(SysCall::Munmap, addr, len)).map(|_| ())
}

/// Advise kernel about memory usage
#[inline]
pub unsafe fn madvise(addr: *mut u8, len: usize, advice: i32) -> Result<()> {
    check_ret(syscall!(SysCall::Madvise, addr, len, advice)).map(|_| ())
}

/// io_uring setup
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
#[inline]
pub unsafe fn io_uring_setup(entries: u32, params: *mut u8) -> Result<i32> {
    check_ret(syscall!(SysCall::IoUringSetup, entries, params)).map(|fd| fd as i32)
}

/// io_uring enter
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
#[inline]
pub unsafe fn io_uring_enter(
    fd: i32,
    to_submit: u32,
    min_complete: u32,
    flags: u32,
    arg: *const u8,
    argsz: usize,
) -> Result<u32> {
    check_ret(syscall!(
        SysCall::IoUringEnter,
        fd,
        to_submit,
        min_complete,
        flags,
        arg,
        argsz
    ))
    .map(|n| n as u32)
}

/// io_uring register
#[cfg(any(target_arch = "x86_64", target_arch = "aarch64"))]
#[inline]
pub unsafe fn io_uring_register(fd: i32, opcode: u32, arg: *const u8, nr_args: u32) -> Result<()> {
    check_ret(syscall!(SysCall::IoUringRegister, fd, opcode, arg, nr_args)).map(|_| ())
}

/// Bind a socket to an address
#[inline]
pub unsafe fn bind(sockfd: i32, addr: *const SockAddr, addrlen: u32) -> Result<()> {
    check_ret(syscall!(SysCall::Bind, sockfd, addr, addrlen)).map(|_| ())
}

/// Listen for connections on a socket
#[inline]
pub unsafe fn listen(sockfd: i32, backlog: i32) -> Result<()> {
    check_ret(syscall!(SysCall::Listen, sockfd, backlog)).map(|_| ())
}

/// Truncate a file to a specified length
#[inline]
pub unsafe fn ftruncate(fd: i32, length: i64) -> Result<()> {
    check_ret(syscall!(SysCall::Ftruncate, fd, length)).map(|_| ())
}