Skip to content

C unwinding with setjmp/longjmp #66

Open
@CAD97

Description

@CAD97

setjmp/longjmp based exception handling isn't particularly performant when cleanup frames are abundant, but it's supported by C89. Translation needs thread_local or some polyfill, though, which is C11.

Thread local state:

#include <setjmp.h>
#include <threads.h>
extern thread_local jmp_buf thread_jmp_buf;

unwind continue is trivial; nothing changes:

_1 = f() -> [return: bb1, unwind continue];
L1 = f();
goto bb1;

Cleanup adds to the jmp_buf stack:

_1 = f() -> [return: bb1, unwind: bb2];
jmp_buf tmp_jmp_buf; // scratch space

tmp_jmp_buf = thread_jmp_buf;
if (setjmp(thread_jmp_buf)) {
    thread_jmp_buf = tmp_jmp_buf;
    goto bb2;
}
L1 = f();
thread_jmp_buf = tmp_jmp_buf;
goto bb1;

Resuming an unwind is then a call to longjmp:

resume;
longjmp(thread_jmp_buf, 1);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions