Jabberwocky

Segfault in Ruby

Posted in ruby by elisehuard on February 12, 2010

Note: the following works with C-based ruby, not JRuby or IronRuby, obviously.
This is a sight most rubyists will fear: the segmentation fault. You’re running your tests quite innocently, or your web server is doing it’s job, until BOOM !

[BUG] Segmentation fault

What just happened ?
A segfault means your program tries to play fast and loose with memory it hasn’t been allocated. The operating system says ‘hey you!’. When this occurs on a *nix, the process receives a signal, SIGSEGV. The program crashes, and in so doing leaves a core dump, which is a recording of the state of the program at the time of crash.

Ruby then traps the corresponding signal.
You’ll find corresponding code in signal.c of the ruby source code:

install_sighandler(SIGSEGV, sigsegv);

and the sigsegv function is:

#ifdef SIGSEGV
static RETSIGTYPE sigsegv _((int));
static RETSIGTYPE
sigsegv(sig)
    int sig; 
{
#if defined(HAVE_NATIVETHREAD) && defined(HAVE_NATIVETHREAD_KILL)
    if (!is_ruby_native_thread() && !rb_trap_accept_nativethreads[sig]) {
        sigsend_to_ruby_thread(sig);
        return;
    }    
#endif
    rb_gc_unstress();
    rb_bug("Segmentation fault");
}
#endif

The rb_bug at the bottom is responsible for the message you see appearing when a segmentation fault happens.

That’s all well, you’ll say, but how to I solve this ?
First off, you have to determine where the issue came from. There’s where the core dump can help you, by telling you if the issue happened in ruby itself, or in its binding to another component, like a database or something similar.
(more…)

Advertisements