starry-kernel 0.7.7

A Linux-compatible OS kernel built on ArceOS unikernel
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
use core::{future::poll_fn, task::Poll};

use ax_errno::{AxError, AxResult, LinuxError};
use ax_runtime::hal::cpu::uspace::UserContext;
use ax_task::{
    current,
    future::{self, block_on},
};
use linux_raw_sys::general::{
    MINSIGSTKSZ, SI_TKILL, SI_USER, SIG_BLOCK, SIG_SETMASK, SIG_UNBLOCK, SS_DISABLE, SS_FLAG_BITS,
    SS_ONSTACK, kernel_sigaction, siginfo, timespec,
};
use starry_process::Pid;
use starry_signal::{SignalInfo, SignalSet, SignalStack, Signo};
use starry_vm::{VmMutPtr, VmPtr};

use crate::{
    task::{
        AsThread, block_next_signal, check_signals, get_process_cred, processes,
        send_signal_to_process, send_signal_to_thread,
    },
    time::TimeValueLike,
};

pub(crate) fn check_sigset_size(size: usize) -> AxResult<()> {
    // Align with Linux raw syscall semantics (for ABI param 'sigmask'): when sigsetsize is checked,
    // it must exactly match the kernel SignalSet size (8 bytes).
    if size != size_of::<SignalSet>() {
        return Err(AxError::InvalidInput);
    }
    Ok(())
}

fn parse_signo(signo: u32) -> AxResult<Signo> {
    Signo::from_repr(signo as u8).ok_or(AxError::InvalidInput)
}

pub fn sys_rt_sigprocmask(
    how: i32,
    set: *const SignalSet,
    oldset: *mut SignalSet,
    sigsetsize: usize,
) -> AxResult<isize> {
    check_sigset_size(sigsetsize)?;

    let curr = current();
    let sig = &curr.as_thread().signal;
    let old = sig.blocked();

    if let Some(oldset) = oldset.nullable() {
        oldset.vm_write(old)?;
    }

    if let Some(set) = set.nullable() {
        let set = unsafe { set.vm_read_uninit()?.assume_init() };

        let set = match how as u32 {
            SIG_BLOCK => old | set,
            SIG_UNBLOCK => old & !set,
            SIG_SETMASK => set,
            _ => return Err(AxError::InvalidInput),
        };

        debug!("sys_rt_sigprocmask <= {set:?}");
        sig.set_blocked(set);
    }

    Ok(0)
}

pub fn sys_rt_sigaction(
    signo: u32,
    act: *const kernel_sigaction,
    oldact: *mut kernel_sigaction,
    sigsetsize: usize,
) -> AxResult<isize> {
    check_sigset_size(sigsetsize)?;

    let signo = parse_signo(signo)?;
    if matches!(signo, Signo::SIGKILL | Signo::SIGSTOP) {
        return Err(AxError::InvalidInput);
    }

    current()
        .as_thread()
        .proc_data
        .signal
        .set_action(signo, act, oldact)
}

pub fn sys_rt_sigpending(set: *mut SignalSet, sigsetsize: usize) -> AxResult<isize> {
    check_sigset_size(sigsetsize)?;
    set.vm_write(current().as_thread().signal.pending())?;
    Ok(0)
}

pub(crate) fn make_siginfo(signo: u32, code: i32) -> AxResult<Option<SignalInfo>> {
    if signo == 0 {
        return Ok(None);
    }
    let signo = parse_signo(signo)?;
    let curr = current();
    let thread = curr.as_thread();
    Ok(Some(SignalInfo::new_user(
        signo,
        code,
        thread.proc_data.proc.pid(),
        thread.cred().uid,
    )))
}

/// Check whether the current process has permission to send a signal to
/// `target_pid`.
///
/// Permission rules:
/// - Root (euid==0, approximating CAP_KILL) can signal anyone
/// - Same process is always allowed
/// - Otherwise: sender's {euid, uid} must match target's {uid, euid, suid}
///
/// TODO: SIGCONT is allowed to any process in the same session (job control).
/// Implementing this requires passing the signal number into this function
/// and checking session membership.
pub(crate) fn check_kill_permission(target_pid: Pid) -> AxResult<()> {
    let sender = current().as_thread().cred();
    if sender.euid == 0 {
        return Ok(());
    }
    let self_pid = current().as_thread().proc_data.proc.pid();
    if target_pid == self_pid {
        return Ok(());
    }
    let target_cred = get_process_cred(target_pid)?;
    // Linux checks: {sender.euid, sender.uid} × {target.uid, target.euid, target.suid}
    if sender.euid == target_cred.uid
        || sender.euid == target_cred.euid
        || sender.euid == target_cred.suid
        || sender.uid == target_cred.uid
        || sender.uid == target_cred.euid
        || sender.uid == target_cred.suid
    {
        Ok(())
    } else {
        Err(AxError::OperationNotPermitted)
    }
}

/// Send a signal to each member of a process group, checking
/// per-member permission. EPERM for individual members is swallowed
/// (matches Linux behavior).
fn kill_process_group_checked(pgid: Pid, sig: Option<SignalInfo>) -> AxResult<()> {
    let pg = crate::task::get_process_group(pgid)?;
    if let Some(sig) = sig {
        for proc in pg.processes() {
            if check_kill_permission(proc.pid()).is_ok() {
                let _ = send_signal_to_process(proc.pid(), Some(sig.clone()));
            }
        }
    }
    Ok(())
}

pub fn sys_kill(pid: i32, signo: u32) -> AxResult<isize> {
    debug!("sys_kill: pid = {pid}, signo = {signo}");
    let sig = make_siginfo(signo, SI_USER as _)?;

    match pid {
        1.. => {
            check_kill_permission(pid as _)?;
            if let Some(sig) = sig {
                let curr = current();
                let thread = curr.as_thread();
                let signo = sig.signo();
                if pid as Pid == thread.proc_data.proc.pid() && !thread.signal.signal_blocked(signo)
                {
                    // A process-directed signal may be delivered to any
                    // unblocked thread. Prefer the current thread for
                    // self-signals so `kill(getpid(), SIGSTOP)` cannot return
                    // to userspace and race into the next syscall before this
                    // thread observes the stop.
                    send_signal_to_thread(None, thread.tid() as Pid, Some(sig))?;
                } else {
                    send_signal_to_process(pid as _, Some(sig))?;
                }
            } else {
                send_signal_to_process(pid as _, None)?;
            }
        }
        0 => {
            let pgid = current().as_thread().proc_data.proc.group().pgid();
            kill_process_group_checked(pgid, sig)?;
        }
        -1 => {
            // Broadcast: send to all processes the caller may signal,
            // except init and self. EPERM is silently swallowed per Linux.
            let curr_pid = current().as_thread().proc_data.proc.pid();
            if let Some(sig) = sig {
                for proc_data in processes() {
                    if proc_data.proc.is_init() || proc_data.proc.pid() == curr_pid {
                        continue;
                    }
                    if check_kill_permission(proc_data.proc.pid()).is_ok() {
                        let _ = send_signal_to_process(proc_data.proc.pid(), Some(sig.clone()));
                    }
                }
            }
        }
        ..-1 => {
            kill_process_group_checked((-pid) as Pid, sig)?;
        }
    }
    Ok(0)
}

pub fn sys_tkill(tid: i32, signo: u32) -> AxResult<isize> {
    if tid <= 0 {
        return Err(AxError::InvalidInput);
    }
    let tid = tid as Pid;
    check_kill_permission(tid)?;
    let sig = make_siginfo(signo, SI_TKILL)?;
    send_signal_to_thread(None, tid, sig)?;
    Ok(0)
}

pub fn sys_tgkill(tgid: Pid, tid: Pid, signo: u32) -> AxResult<isize> {
    check_kill_permission(tgid)?;
    let sig = make_siginfo(signo, SI_TKILL)?;
    send_signal_to_thread(Some(tgid), tid, sig)?;
    Ok(0)
}

pub(crate) fn make_queue_signal_info(
    tgid: Pid,
    signo: u32,
    sig: *const SignalInfo,
) -> AxResult<Option<SignalInfo>> {
    if signo == 0 {
        return Ok(None);
    }

    let signo = parse_signo(signo)?;
    let mut sig = unsafe { sig.vm_read_uninit()?.assume_init() };
    sig.set_signo(signo);
    if current().as_thread().proc_data.proc.pid() != tgid
        && (sig.code() >= 0 || sig.code() == SI_TKILL)
    {
        return Err(AxError::OperationNotPermitted);
    }
    Ok(Some(sig))
}

pub fn sys_rt_sigqueueinfo(
    tgid: Pid,
    signo: u32,
    sig: *const SignalInfo,
    sigsetsize: usize,
) -> AxResult<isize> {
    check_sigset_size(sigsetsize)?;

    let sig = make_queue_signal_info(tgid, signo, sig)?;
    send_signal_to_process(tgid, sig)?;
    Ok(0)
}

pub fn sys_rt_tgsigqueueinfo(
    tgid: Pid,
    tid: Pid,
    signo: u32,
    sig: *const SignalInfo,
    sigsetsize: usize,
) -> AxResult<isize> {
    check_sigset_size(sigsetsize)?;

    let sig = make_queue_signal_info(tgid, signo, sig)?;
    send_signal_to_thread(Some(tgid), tid, sig)?;
    Ok(0)
}

pub fn sys_rt_sigreturn(uctx: &mut UserContext) -> AxResult<isize> {
    block_next_signal();
    current().as_thread().signal.restore(uctx)?;
    Ok(uctx.retval() as isize)
}

pub fn sys_rt_sigtimedwait(
    uctx: &mut UserContext,
    set: *const SignalSet,
    info: *mut siginfo,
    timeout: *const timespec,
    sigsetsize: usize,
) -> AxResult<isize> {
    check_sigset_size(sigsetsize)?;

    let set = unsafe { set.vm_read_uninit()?.assume_init() };

    let timeout = if let Some(ts) = timeout.nullable() {
        let ts = unsafe { ts.vm_read_uninit()?.assume_init() };
        Some(ts.try_into_time_value()?)
    } else {
        None
    };

    debug!("sys_rt_sigtimedwait => set = {set:?}, timeout = {timeout:?}");

    let curr = current();
    let thr = curr.as_thread();
    let signal = &thr.signal;

    let old_blocked = signal.blocked();
    // Publish sigwait_set so that send_signal skips is_ignore() for signals
    // this thread is waiting for.  We do NOT unblock the waited signals:
    // dequeue_signal(&set) can already retrieve blocked pending signals, and
    // keeping them blocked prevents check_signals from racing to dequeue and
    // discard them as default-ignore (e.g. SIGCHLD/SIGURG).
    *signal.sigwait_set.lock() = Some(set);

    uctx.set_retval(-LinuxError::EINTR.code() as usize);
    let fut = poll_fn(|cx| {
        if let Some(sig) = signal.dequeue_signal(&set) {
            Poll::Ready(Some(sig))
        } else if check_signals(thr, uctx, Some(old_blocked), None) {
            Poll::Ready(None)
        } else {
            let _ = curr.poll_interrupt(cx);
            Poll::Pending
        }
    });

    let Ok(sig) = block_on(future::timeout(timeout, fut)) else {
        // Timeout
        *signal.sigwait_set.lock() = None;
        return Err(AxError::WouldBlock);
    };
    let Some(sig) = sig else {
        // Interrupted
        *signal.sigwait_set.lock() = None;
        return Ok(0);
    };

    *signal.sigwait_set.lock() = None;

    if let Some(info) = info.nullable() {
        info.vm_write(sig.0)?;
    }

    Ok(sig.signo() as _)
}

pub fn sys_rt_sigsuspend(
    uctx: &mut UserContext,
    set: *const SignalSet,
    sigsetsize: usize,
) -> AxResult<isize> {
    check_sigset_size(sigsetsize)?;

    let curr = current();
    let thr = curr.as_thread();

    let set = unsafe { set.vm_read_uninit()?.assume_init() };
    let old_blocked = thr.signal.set_blocked(set);

    // sigsuspend always returns -EINTR when a signal is caught
    // We set this in uctx before check_signals so it's saved in SignalFrame
    uctx.set_retval(-LinuxError::EINTR.code() as usize);

    block_on(poll_fn(|cx| {
        if check_signals(thr, uctx, Some(old_blocked), None) {
            return Poll::Ready(());
        }
        let _ = curr.poll_interrupt(cx);
        Poll::Pending
    }));

    // sigsuspend always returns -EINTR
    Err(AxError::Interrupted)
}

pub fn sys_sigaltstack(ss: *const SignalStack, old_ss: *mut SignalStack) -> AxResult<isize> {
    let curr = current();
    let sig = &curr.as_thread().signal;

    if let Some(old_ss) = old_ss.nullable() {
        old_ss.vm_write(sig.stack())?;
    }

    if let Some(ss) = ss.nullable() {
        let ss = unsafe { ss.vm_read_uninit()?.assume_init() };
        if sig.stack_active() {
            return Err(AxError::OperationNotPermitted);
        }
        if ss.flags & !(SS_DISABLE | SS_ONSTACK | SS_FLAG_BITS) != 0 {
            return Err(AxError::InvalidInput);
        }
        if ss.flags & SS_DISABLE == 0 && ss.size < MINSIGSTKSZ as usize {
            return Err(AxError::NoMemory);
        }
        sig.set_stack(ss);
    }
    Ok(0)
}

#[cfg(axtest)]
pub(crate) fn signal_sigset_size_and_signo_validation_rules_hold_for_test() -> bool {
    use core::mem::size_of;

    use starry_signal::SignalSet;

    // check_sigset_size: only accepts exact size of SignalSet.
    let correct_size = size_of::<SignalSet>();
    let ok = check_sigset_size(correct_size).is_ok();
    let too_small = check_sigset_size(correct_size - 1).is_err();
    let too_big = check_sigset_size(correct_size + 1).is_err();
    let zero = check_sigset_size(0).is_err();

    // parse_signo: valid signos (1-31 typically) parse, 0 and out-of-range fail.
    // SIGKILL=9, SIGSTOP=19 on Linux x86_64.
    let valid_signo = parse_signo(9).is_ok(); // SIGKILL
    let valid_signo2 = parse_signo(19).is_ok(); // SIGSTOP
    let zero_signo = parse_signo(0).is_err(); // 0 is not a valid signo
    // Signo::from_repr uses u8, so values > 255 fail
    let overflow = parse_signo(256).is_err();

    ok && too_small && too_big && zero && valid_signo && valid_signo2 && zero_signo && overflow
}

#[cfg(axtest)]
pub(crate) fn signal_sigset_and_signo_validation_rules_hold_for_test() -> bool {
    use core::mem::size_of;

    use starry_signal::SignalSet;

    // Test check_sigset_size
    let correct_size = size_of::<SignalSet>();
    assert!(check_sigset_size(correct_size).is_ok());
    assert!(check_sigset_size(correct_size - 1).is_err());
    assert!(check_sigset_size(correct_size + 1).is_err());
    assert!(check_sigset_size(0).is_err());

    // Test parse_signo
    assert!(parse_signo(1).is_ok()); // SIGHUP
    assert!(parse_signo(9).is_ok()); // SIGKILL
    assert!(parse_signo(0).is_err()); // Invalid signo
    assert!(parse_signo(255).is_err()); // Out of range

    true
}