setjmp/longjmp

Henry Spencer henry at utzoo.uucp
Fri Apr 28 02:53:19 AEST 1989


In article <1447 at cunixc.cc.columbia.edu> fuat at cunixc.cc.columbia.edu (Fuat C. Baran) writes:
>I don't know much about the Draft ANSI C, so I was wondering if
>someone could explain the idea behind the behaviour we are
>experiencing on the Encore (i.e. why can't automatic variables be
>modified after the setjmp such that they retain their value after the
>longjmp back)? ...

Because in the general case it's very hard.  With a cooperative machine,
an implementation which accepts some inefficiency on function calls, or a
very clever compiler, it can be done.  But when the machine is unhelpful
(many are) and the efficiency of calls is important (it usually is) and
the compiler's cleverness is limited (it usually is), restoring the
values is difficult.

The major problem is in cases where the variable is in a register, either
as a result of being declared "register" or as a result of a clever compiler,
and there is a single set of registers that is used by all functions.  When
doing a longjmp, to get the values "right" it is necessary to restore the
registers to the values that they had when control left the function being
longjmped to.  Depending on the save/restore convention used by the
particular machine and compiler, this can range from trivial to impossibly
hard.  Compilers that have called functions save registers, and do so only
when necessary, will have saved values scattered through the call stack,
appearing wherever an intermediate function needed that register.  If the
machine has a self-describing stack, like the VAX, longjmp() may be able
to dig them out... but such stacks are inefficient and modern machines
seldom have them.  One can choose a save/restore convention that avoids
this, or a very clever compiler can change save/restore conventions when
it notices the setjmp(), but there are tradeoffs and it isn't always
practical.

If you have a very up-to-date compiler, you may be able to avoid this
problem by declaring the crucial variables with the "volatile" modifier,
which tells an ANSI-C-compliant compiler not to get tricky.
-- 
Mars in 1980s:  USSR, 2 tries, |     Henry Spencer at U of Toronto Zoology
2 failures; USA, 0 tries.      | uunet!attcan!utzoo!henry henry at zoo.toronto.edu



More information about the Comp.std.c mailing list