rusty_rtos_kernel-core 0.3.3

The pure no_std core of rusty_rtos_kernel: types, traits and algorithms with no CPU, no allocator and no operating system. forbid(unsafe).
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
//! The driver behind `no_panic.rs` and the `kernel_api` fuzz target: every
//! public call, with whatever arguments an entropy source picks.
//!
//! Split out of `no_panic.rs` so the coverage-guided fuzzer and the seeded
//! test run ONE dispatcher. See `no_panic.rs` for what it is for.

#![allow(dead_code, clippy::unwrap_used, clippy::expect_used, clippy::panic)]

use core::fmt;

use rusty_rtos_core::config::{Config, PosixDemoConfig};
use rusty_rtos_core::handle::{
    EventGroupHandle, QueueHandle, StreamBufferHandle, TaskHandle, TimerHandle,
};
use rusty_rtos_core::hooks::NoTickHook;
use rusty_rtos_core::isr::Woken;
use rusty_rtos_core::port::Port;
use rusty_rtos_core::trace::{Event, Trace};
use rusty_rtos_kernel_core::kernel::NotifyAction;
use rusty_rtos_kernel_core::{Kernel, list_slots_for, lists_for};

const TASKS: usize = 8;
const QUEUES: usize = 8;
const SLOTS: usize = 32;
const BUFFERS: usize = 4;
const BYTES: usize = 256;
const TIMERS: usize = 4;
const GROUPS: usize = 4;

/// The smallest port that satisfies the seam: it counts nesting so the
/// kernel's own bookkeeping has something real to talk to, and does nothing
/// else. The sim port is deliberately *not* used — this test is about the
/// kernel, and a second port implementation is one more thing that would
/// have to be wrong in the same way to hide a panic.
#[derive(Debug, Default)]
pub struct TestPort {
    nesting: core::cell::Cell<u32>,
    in_isr: core::cell::Cell<bool>,
}

impl Port for TestPort {
    fn yield_now(&self) {}
    fn yield_from_isr(&self, _woken: Woken) {}
    fn enter_critical(&self) {
        self.nesting.set(self.nesting.get().saturating_add(1));
    }
    fn exit_critical(&self) {
        self.nesting.set(self.nesting.get().saturating_sub(1));
    }
    fn set_interrupt_mask_from_isr(&self) -> u32 {
        0
    }
    fn clear_interrupt_mask_from_isr(&self, _saved: u32) {}
    fn in_isr(&self) -> bool {
        self.in_isr.get()
    }
    fn set_in_tick_entry(&self, yes: bool) {
        self.in_isr.set(yes);
    }
}

/// A trace sink that counts and keeps nothing, so a million calls cost
/// nothing but time.
#[derive(Default)]
pub struct Counting(pub u64);

impl Trace for Counting {
    // Nothing here reads a task name, so the kernel is told not to build one.
    // Without this the trait default is `true` and every traced event costs a
    // name lookup plus a UTF-8 validation for a sink that drops it: measured
    // at 3.86x on one row (2026-09-21).
    const WANTS_NAMES: bool = false;

    fn event(&mut self, _tick: u64, _event: Event<'_>) {
        self.0 = self.0.wrapping_add(1);
    }
}

impl fmt::Debug for Counting {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Counting({})", self.0)
    }
}

pub type K = Kernel<
    PosixDemoConfig,
    TestPort,
    Counting,
    NoTickHook,
    TASKS,
    {
        list_slots_for(
            TASKS,
            TIMERS,
            lists_for(<PosixDemoConfig as Config>::MAX_PRIORITIES, QUEUES, GROUPS),
        )
    },
    { lists_for(<PosixDemoConfig as Config>::MAX_PRIORITIES, QUEUES, GROUPS) },
    QUEUES,
    SLOTS,
    BUFFERS,
    BYTES,
    TIMERS,
    GROUPS,
    { <PosixDemoConfig as ::rusty_rtos_core::config::Config>::TIMER_QUEUE_LENGTH },
>;

/// A fixed-size list of handles that are (probably) still live, so the
/// generator can aim at real objects as well as invented ones.
struct Live<T: Copy, const N: usize> {
    items: [T; N],
    len: usize,
}

impl<T: Copy, const N: usize> Live<T, N> {
    fn new(empty: T) -> Self {
        Self {
            items: [empty; N],
            len: 0,
        }
    }

    fn push(&mut self, item: T) {
        if let Some(slot) = self.items.get_mut(self.len) {
            *slot = item;
            self.len = self.len.saturating_add(1);
        }
    }

    fn all(&self) -> &[T] {
        self.items.get(..self.len).unwrap_or(&[])
    }
}

/// Where the driver's choices come from.
///
/// The test feeds it a seeded xorshift, so a failure reproduces from the
/// seed in its message; the fuzz target (`fuzz/fuzz_targets/kernel_api.rs`)
/// feeds it libFuzzer's input, so coverage steers the choices. One
/// dispatcher, two sources: whatever the fuzzer reaches, the test reaches
/// by the same code.
pub trait Entropy {
    fn next_u64(&mut self) -> u64;
}

/// xorshift64*, seeded once and printed on failure.
pub struct Xorshift(pub u64);

impl Entropy for Xorshift {
    fn next_u64(&mut self) -> u64 {
        let mut x = self.0;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.0 = x;
        x.wrapping_mul(0x2545_f491_4f6c_dd1d)
    }
}

/// The generator's helpers, over any source of entropy.
struct Rng<E: Entropy>(E);

impl<E: Entropy> Rng<E> {
    fn next(&mut self) -> u64 {
        self.0.next_u64()
    }

    fn below(&mut self, n: u64) -> u64 {
        if n == 0 {
            0
        } else {
            self.next().checked_rem(n).unwrap_or(0)
        }
    }

    /// A tick count drawn from the values that break things: zero, one,
    /// the maximum, either side of the maximum, and a spread in between.
    fn ticks(&mut self) -> u64 {
        match self.below(8) {
            0 => 0,
            1 => 1,
            2 => u64::MAX,
            3 => u64::MAX - 1,
            4 => u64::from(u32::MAX),
            5 => 1 << 63,
            _ => self.next(),
        }
    }

    /// A handle that is as likely to be wrong as right: a live one, a
    /// plausible-looking index, the null handle, or pure noise.
    fn task(&mut self, live: &[TaskHandle]) -> TaskHandle {
        match self.below(4) {
            0 if !live.is_empty() => {
                let i = self.below(live.len() as u64) as usize;
                live.get(i).copied().unwrap_or(TaskHandle::NULL)
            }
            1 => TaskHandle::NULL,
            2 => TaskHandle::from_raw(self.next() as u32),
            _ => TaskHandle::from_raw((self.below(16) as u32) | ((self.below(4) as u32) << 16)),
        }
    }

    fn queue(&mut self, live: &[QueueHandle]) -> QueueHandle {
        match self.below(4) {
            0 if !live.is_empty() => {
                let i = self.below(live.len() as u64) as usize;
                live.get(i).copied().unwrap_or(QueueHandle::NULL)
            }
            1 => QueueHandle::NULL,
            2 => QueueHandle::from_raw(self.next() as u32),
            _ => QueueHandle::from_raw((self.below(16) as u32) | ((self.below(4) as u32) << 16)),
        }
    }

    fn timer(&mut self, live: &[TimerHandle]) -> TimerHandle {
        match self.below(4) {
            0 if !live.is_empty() => {
                let i = self.below(live.len() as u64) as usize;
                live.get(i).copied().unwrap_or(TimerHandle::NULL)
            }
            1 => TimerHandle::NULL,
            2 => TimerHandle::from_raw(self.next() as u32),
            _ => TimerHandle::from_raw((self.below(16) as u32) | ((self.below(4) as u32) << 16)),
        }
    }

    fn group(&mut self, live: &[EventGroupHandle]) -> EventGroupHandle {
        match self.below(4) {
            0 if !live.is_empty() => {
                let i = self.below(live.len() as u64) as usize;
                live.get(i).copied().unwrap_or(EventGroupHandle::NULL)
            }
            1 => EventGroupHandle::NULL,
            2 => EventGroupHandle::from_raw(self.next() as u32),
            _ => {
                EventGroupHandle::from_raw((self.below(16) as u32) | ((self.below(4) as u32) << 16))
            }
        }
    }

    fn buffer(&mut self, live: &[StreamBufferHandle]) -> StreamBufferHandle {
        match self.below(4) {
            0 if !live.is_empty() => {
                let i = self.below(live.len() as u64) as usize;
                live.get(i).copied().unwrap_or(StreamBufferHandle::NULL)
            }
            1 => StreamBufferHandle::NULL,
            2 => StreamBufferHandle::from_raw(self.next() as u32),
            _ => StreamBufferHandle::from_raw(
                (self.below(16) as u32) | ((self.below(4) as u32) << 16),
            ),
        }
    }
}

/// What one pass actually managed to do, so a run that bounced off
/// invalid handles from start to finish cannot pass quietly.
#[derive(Debug, Default, Clone, Copy)]
pub struct Worked {
    /// Trace lines the kernel emitted.
    pub traced: u64,
    /// Ticks it counted.
    pub ticks: u64,
}

/// One pass: build a kernel, start it, then make `calls` arbitrary calls.
pub fn hammer<E: Entropy>(entropy: E, calls: u32) -> Worked {
    let mut rng = Rng(entropy);
    let mut k = K::new(TestPort::default(), Counting::default()).expect("the geometry adds up");

    let mut tasks = Live::<TaskHandle, TASKS>::new(TaskHandle::NULL);
    let mut queues = Live::<QueueHandle, QUEUES>::new(QueueHandle::NULL);
    let mut buffers = Live::<StreamBufferHandle, BUFFERS>::new(StreamBufferHandle::NULL);
    let mut timers = Live::<TimerHandle, TIMERS>::new(TimerHandle::NULL);
    let mut groups = Live::<EventGroupHandle, GROUPS>::new(EventGroupHandle::NULL);

    for i in 0..3 {
        if let Ok(t) = k.create_task("h", (i % 5) as u8) {
            tasks.push(t);
        }
    }
    let started = k.start_scheduler().expect("the scheduler starts");
    tasks.push(started.idle);
    tasks.push(started.timer);
    queues.push(started.timer_queue);

    let mut data = [0_u8; 64];
    let mut out = [0_u8; 64];

    for _ in 0..calls {
        let ticks = rng.ticks();
        let task = rng.task(tasks.all());
        let queue = rng.queue(queues.all());
        let buffer = rng.buffer(buffers.all());
        let timer = rng.timer(timers.all());
        let group = rng.group(groups.all());
        let index = rng.below(8) as usize;
        let value = rng.next();
        let length = rng.below(80) as usize;

        match rng.below(53) {
            0 => {
                if let Ok(t) = k.create_task("h", rng.below(300) as u8) {
                    tasks.push(t);
                }
            }
            1 => {
                if let Ok(q) = k.queue_create(rng.below(40) as usize) {
                    queues.push(q);
                }
            }
            2 => {
                if let Ok(q) =
                    k.semaphore_create_counting(rng.below(40) as usize, rng.below(40) as usize)
                {
                    queues.push(q);
                }
            }
            3 => {
                if let Ok(q) = k.mutex_create() {
                    queues.push(q);
                }
            }
            4 => {
                if let Ok(q) = k.mutex_create_recursive() {
                    queues.push(q);
                }
            }
            5 => {
                if let Ok(q) = k.queue_create_set(rng.below(40) as usize) {
                    queues.push(q);
                }
            }
            6 => {
                if let Ok(b) = k.stream_buffer_create(length, rng.below(80) as usize) {
                    buffers.push(b);
                }
            }
            7 => {
                if let Ok(b) = k.message_buffer_create(length) {
                    buffers.push(b);
                }
            }
            8 => {
                let _ = k.queue_send(queue, value, ticks);
            }
            9 => {
                let _ = k.queue_send_to_front(queue, value, ticks);
            }
            10 => {
                let _ = k.queue_overwrite(queue, value);
            }
            11 => {
                let _ = k.queue_receive(queue, ticks);
            }
            12 => {
                let _ = k.queue_peek(queue, ticks);
            }
            13 => {
                let _ = k.semaphore_take(queue, ticks);
            }
            14 => {
                let _ = k.semaphore_give(queue);
            }
            15 => {
                let _ = k.mutex_take_recursive(queue, ticks);
            }
            16 => {
                let _ = k.mutex_give_recursive(queue);
            }
            17 => {
                let _ = k.queue_messages_waiting(queue);
            }
            18 => {
                let _ = k.queue_spaces_available(queue);
            }
            19 => {
                let _ = k.queue_reset(queue);
            }
            20 => {
                let _ = k.queue_add_to_set(queue, rng.queue(queues.all()));
            }
            21 => {
                let _ = k.queue_remove_from_set(queue, rng.queue(queues.all()));
            }
            22 => {
                let _ = k.queue_select_from_set(queue, ticks);
            }
            23 => {
                let _ = k.queue_send_from_isr(queue, value);
            }
            24 => {
                let _ = k.queue_receive_from_isr(queue);
            }
            25 => {
                let _ = k.queue_peek_from_isr(queue);
            }
            26 => {
                let _ = k.delay(ticks);
            }
            27 => {
                let _ = k.suspend(if rng.below(2) == 0 { None } else { Some(task) });
            }
            28 => {
                let _ = k.resume(task);
            }
            29 => {
                let _ = k.set_priority(
                    if rng.below(2) == 0 { None } else { Some(task) },
                    rng.below(300) as u8,
                );
            }
            30 => {
                let _ = k.abort_delay(task);
            }
            31 => {
                let _ = k.notify(task, index, value as u32, action(rng.below(5)));
            }
            32 => {
                let n = length.min(data.len());
                for byte in data.get_mut(..n).unwrap_or(&mut []).iter_mut() {
                    *byte = value as u8;
                }
                let slice = data.get(..n).unwrap_or(&[]);
                let _ = k.stream_buffer_send(buffer, slice, ticks);
            }
            33 => {
                let n = length.min(out.len());
                let slice = out.get_mut(..n).unwrap_or(&mut []);
                let _ = k.stream_buffer_receive(buffer, slice, ticks);
            }
            34 => {
                if let Ok(t) =
                    k.timer_create("t", rng.below(40).max(1), rng.below(2) == 0, value, 0)
                {
                    timers.push(t);
                }
            }
            35 => {
                let _ = k.timer_start(timer, ticks);
            }
            36 => {
                let _ = k.timer_stop(timer, ticks);
            }
            37 => {
                let _ = k.timer_reset(timer, ticks);
            }
            38 => {
                let _ = k.timer_change_period(timer, rng.below(40), ticks);
            }
            39 => {
                let _ = k.timer_delete(timer, ticks);
            }
            40 => {
                // The four wrappers, not the raw command: the C's public
                // from-ISR API fills the value in itself, and a value from
                // anywhere else is a command time the daemon believes.
                match rng.below(4) {
                    0 => drop(k.timer_start_from_isr(timer)),
                    1 => drop(k.timer_stop_from_isr(timer)),
                    2 => drop(k.timer_reset_from_isr(timer)),
                    _ => drop(k.timer_change_period_from_isr(timer, rng.below(40).max(1))),
                }
            }
            41 => {
                let _ = k.timer_pend_function_call(0, value, value, ticks);
            }
            42 => {
                let _ = k.timer_is_active(timer);
            }
            43 => {
                let _ = k.timer_expiry_time(timer);
            }
            44 => {
                if let Ok(g) = k.event_group_create() {
                    groups.push(g);
                }
            }
            45 => {
                let _ = k.event_group_set_bits(group, value as u32);
            }
            46 => {
                let _ = k.event_group_clear_bits(group, value as u32);
            }
            47 => {
                let _ = k.event_group_wait_bits(
                    group,
                    value as u32,
                    value & 1 == 0,
                    value & 2 == 0,
                    ticks,
                );
            }
            48 => {
                let _ = k.event_group_sync(group, value as u32, (value >> 32) as u32, ticks);
            }
            49 => {
                let _ = k.event_group_bits(group);
            }
            50 => {
                let _ = k.event_group_set_bits_from_isr(group, value as u32);
            }
            51 => {
                let _ = k.event_group_delete(group);
            }
            _ => {
                let _ = k.process_one_timer_command(0);
            }
        }

        // A handful of calls that take no arguments worth randomising, plus
        // the tick itself, so the kernel keeps moving rather than sitting
        // in whatever state the last call left it.
        match rng.below(10) {
            0 => k.tick_from_isr(),
            1 => {
                let _ = k.resume_pending();
            }
            2 => k.task_yield(),
            3 => {
                k.enter_critical();
                k.exit_critical();
            }
            4 => k.idle_hook_tick(),
            5 => {
                let _ = k.notify_wait(index, value as u32, (value >> 32) as u32, ticks);
            }
            6 => {
                let _ = k.notify_state_clear(None, index);
            }
            7 => {
                let _ = k.task_priority_get(None);
            }
            8 => {
                let _ = k.state_of(task);
            }
            _ => {
                let _ = k.stream_buffer_delete(buffer);
            }
        }
    }
    Worked {
        traced: k.trace().0,
        ticks: k.tick_count(),
    }
}

fn action(n: u64) -> NotifyAction {
    match n {
        0 => NotifyAction::None,
        1 => NotifyAction::SetBits,
        2 => NotifyAction::Increment,
        3 => NotifyAction::Overwrite,
        _ => NotifyAction::NoOverwrite,
    }
}