[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [libunwind] Some basic questions about libunwind

From: James E Wilson
Subject: Re: [libunwind] Some basic questions about libunwind
Date: Mon, 06 Dec 2004 16:34:20 -0800

On Mon, 2004-12-06 at 14:37, Archie Cobbs wrote:
> It seems like with libunwind's longjmp(), variables in registers would
> always be restored to the values they had when longjmp() is called,
> because you can never pluck an "old" value off the stack (i.e., the
> register values are never stored in more than one place).

It isn't safe to assume anything more than what the standard guarantees,
and the standard says that non-volatile automatics are indeterminate
after a longjmp.

Your reasoning is flawed, because you fail to consider compiler
effects.  You are assuming that automatic variables are objects
corresponding to a single storage location that is always updated when
the variable is written to.  This is far from true with an optimizing
compiler.  The compiler may use multiple locations for a variable, it
may use different locations in different code regions, it may defer
stores, it may optimize away the storage location, etc.

The same is true for both automatics and global variables, however,
there is an important difference.  A global variable might be referenced
by a subroutine call, but an automatic can not if its address is not
passed to a subroutine.  The compiler can make use of this to better
optimize automatics.  Thus a global variable will have a known state
when longjmp is called, but an automatic may not.  We don't have to
worry about longjmp here, as the standard explicitly says we don't have

In fact, if you compile your example with current FSF gcc mainline for
x86 or x86-64 with -O, the "x = 2" store gets deferred to after the bar
subroutine call, and the example always prints "1", regardless of how
setjmp/longjmp work.  The instruction that sets x to 2 never gets
executed because it is after a function call that never returns.

If I optimize with -O3, we do function inlining, and the "x = 2;" line
is completely optimized away.

Other compilers may handle this differently, as the standard allows the
compiler to choose either value after the longjmp.  Also, other gcc
versions may handle this differently.

Another point, just because gcc ends up with the value set before the
setjmp for this example does not mean that gcc will do this for all
examples.  This example is easy to analyze.  In a more complex example,
you could end up with other results.  As the standard says, you can end
up with any value contained by the variable in between the setjmp and
the longjmp.  We make no guarantees.

reply via email to

[Prev in Thread] Current Thread [Next in Thread]