5

I am trying to understand the stack overflow handler in Rust. I have written the function recursive_stack() which declares some local variables again and again to exhaust the stack space.

extern crate nix;

use nix::sys::signal;

extern "C" fn handle_sigsegv(_: i32) {
    //Do something here
}

fn main() {
    let sig_action = signal::SigAction::new(
        signal::SigHandler::Handler(handle_sigsegv),
        signal::SaFlags::SA_NODEFER,
        signal::SigSet::empty(),
    );
    unsafe {
        signal::sigaction(signal::SIGSEGV, &sig_action);
    }
    println!("Before function");
    recursive_stack();
    println!("After function");
}

fn recursive_stack() {
    let _array: [i64; 50] = [0; 50];
    recursive_stack();
}

I want to catch the signal and execute my signal handler. If I register my signal handler, I get a "Segmentation fault (core dumped)" message. If I don't register a signal handler than I get a stack overflow message.

This signal handler works fine if I register it for SIGINT signal but gives strange results for SIGSEGV. What am I missing?

I am running this program on Ubuntu 18.04.

A-B
  • 487
  • 2
  • 23
  • 4
    In a signal handler, you can only use async-signal-safe function. I doubt this is the case of `println!`. – mcarton Aug 28 '18 at 20:58
  • 4
    See also [this](https://stackoverflow.com/a/21204438/841108). Handling `SIGSEGV` in Rust is as tricky as handling it in C. Look also [here](http://www.linuxprogrammingblog.com/all-about-linux-signals?page=4) – Basile Starynkevitch Aug 28 '18 at 20:59
  • Read also [signal-safety(7)](http://man7.org/linux/man-pages/man7/signal-safety.7.html) and [signal(7)](http://man7.org/linux/man-pages/man7/signal.7.html) – Basile Starynkevitch Aug 28 '18 at 21:13
  • 8
    "Exhausting stack space is one of the causes of segmentation fault. In this case running a signal handler is not possible because it requires space on the stack. To allow handling SIGSEGV in such condition the sigaltstack(2) function exists that sets alternative stack to be used by signal handlers." – Stargateur Aug 28 '18 at 21:40
  • @Stargateur Thanks for the comment. The alternate stack is working for me. – A-B Aug 31 '18 at 17:14

0 Answers0