dennis90
dennis90

Reputation: 269

Is it safe to longjmp through a try block?

I have the following lua_CFunction, written in C++:

int my_function(lua_State* L) {
    int x = 0;
    try {
        x = do_cpp_stuff_that_invokes_lua_API_as_well();
    } catch(const std::exception& ex) {
        lua_pushstring(ex.what().c_str());
        lua_error(L);
    }
    return x;
}

My question is the following: Is it OK to do a lua_error(L) or call any lua function that might longjmp:

I take care of variables allocated on the stack simply by not allocating anything that would rely on a destructor (string, etc...). If I need to do that, than all the lua functions in that scope are wrapped in a pcall and if that pcall fails an exception is thrown to this function that I posted. Simply I am concerned with try-catch blocks.

Many thanks

Upvotes: 1

Views: 537

Answers (2)

Yegor Derevenets
Yegor Derevenets

Reputation: 191

If you are doing a long jump from a catch block, you are at least going to leak the memory used to store the exception object. The compiler generates the code freeing this memory on the control flow paths leading out of the catch block scope. If you do a long jump, none of these paths is taken.

Sun Studio's documentation forbids mixing exceptions and longjmp explicitly:

In particular, you must not longjmp into or out of a try-block or catch-block (directly or indirectly), or longjmp past the initialization or non-trivial destruction of auto variables or temporary variables.

Upvotes: 1

T.C.
T.C.

Reputation: 137310

The relevant rule is (§18.10 [support.runtime]/p4):

The function signature longjmp(jmp_buf jbuf, int val) has more restricted behavior in this International Standard. A setjmp/longjmp call pair has undefined behavior if replacing the setjmp and longjmp by catch and throw would invoke any non-trivial destructors for any automatic objects.

The C++ standard does not otherwise restrict the use of setjmp and longjmp.

Upvotes: 3

Related Questions