RustForge

foundry

Foundry OS: the operating system built on the Rustbelt kernel

foundry / import / kernel-user / overflow.rs
1000 bytes ยท raw
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
//! A buggy program: a function that calls itself forever. Every call needs
//! a little more stack, so the stack grows down until it runs into the
//! *guard zone* below it, which is never mapped. The CPU raises a page
//! fault there and the kernel kills just this program, saying
//! "killed: stack overflow", instead of letting the stack quietly grow over
//! other memory.
#![no_std]
#![no_main]

#[macro_use]
#[path = "ulib.rs"]
mod ulib;

/// Uses 1 KiB of stack per call, then calls itself again.
fn recurse(depth: u64) -> u64 {
    let mut buf = [0u8; 1024];
    // `black_box` stops the compiler from removing the array or turning
    // the recursion into a loop.
    buf[0] = depth as u8;
    let buf = core::hint::black_box(buf);
    recurse(depth + 1) + buf[0] as u64
}

fn main() -> i64 {
    println!("[overflow] pid {}: recursing until the stack runs out...", ulib::getpid());
    let n = recurse(0);
    println!("[overflow] returned {} -- this must never be printed!", n);
    1
}