Re: use of setjmp/longjmp in x86 emulator.

From: Zachary Amsden
Date: Mon Mar 01 2010 - 11:14:21 EST


On 02/28/2010 11:18 PM, Gleb Natapov wrote:
I am looking at improving KVM x86 emulator. Current code does not
handle some special cases correctly (code execution from ROM, ins/outs
to/from MMIO) and many exception conditions during instruction emulation
are not handled correctly. There is a lot of code in emulator that is
there only for exception propagation. Using setjmp/longjmp will be very
beneficial here as exception condition during instruction execution
maps very naturally to setjmp/longjmp, so my question is what about
adding setjmp/longjmp implementation to the kernel, or alternatively,
if there is a fear that it can be abused, add it locally to emulator.c?
Note that instruction emulation is always done in process context.

I'm all for radical ideas, but from a pragmatic point of view, you shouldn't use longjmp in the kernel. Seriously bad things are happening with it; it leaves local variables undefined, doesn't undo global state changes.

So if you:

spin_lock(&s->lock);
if (!s->active)
longjmp(buf, -1);

... you are broken. This case can be made very much more complex and hard to reason about by using local variables which are reset by the longjmp.

Further, it requires use of the volatile keyword to interact properly with logic involving more than one variable, and thus, by definition is impossible to use in the kernel, which does not implement the volatile keyword. :)


Instead, for this case, use the fact that there is an architecturally designed finite number of exceptions that can be processed simultaneously. This means if you queue exceptions to a pending list of control-flow interrupting events to be processed, as long as the queue is appropriately sized, you will never overflow this queue and never require dynamic allocation. Further, you can then naturally follow the exception priority rules at the top-level of the emulator and never need to pass back complex exception structures, merely a simple return value which indicates whether to return to top-level control logic or continue with instruction emulation. I believe using this style of programming will make your need for setjmp/longjmp go away.

Zach
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/