Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

After invoking longjmp(), non–volatile-qualified local objects should not be accessed if their values could have changed since the invocation of setjmp(). Their value in this case is considered indeterminate, and accessing them is undefined behavior. (See undefined behavior behaviors 127,  and 10.)

The longjmp() function should never be used to return control to a function that has terminated execution. (See Undefined Behavior undefined behavior 126.)

Signal masks, floating-point status flags, and the state of open files are not saved by the setjmp() function. If signal masks need to be saved, the sigsetjmp() function should be used.

...

Code Block
bgColor#FFCCCC
langc
jmp_buf buf;
unsigned char b[] = {0xe5, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00};

int main(void) {
  setup();
  do_stuff();
  return 0;
}

void setup(void) {
  f();
}

void f(void) {
  g();
}

void g(void) {
  if (setjmp(buf) == 0) {
    printf("setjmp() invoked\n");
  } else {
    printf("longjmp() invoked\n");
  }
}

void do_stuff(void) {
  char a[8];
  memcpy(a, b, 8);
  /* ... stuff ... */
  longjmp(buf, 1);
}

void bad(void) {
  printf("Should not be called!\n");
  exit(1);
}

Implementation Details

When compiled Compiled for x86-64 using GCC v4version 4.1.2 on Linux, the above the preceding example outputs the following when run:

...

Because g() has finished executing at the time longjmp() is called, it is no longer on the stack. When do_stuff() is invoked, its stackframe occupies the same memory as the old stackframe of g(). In this case, a was located in the same location as the return address of function g(). The call to memcpy() overwrites the return address, so , when longjmp() sends control back to function g(), the function returns to the wrong address (in this case, to function bad()).

...

The longjmp() function should only be used when only when the function containing the corresponding setjmp() is guaranteed not to have completed execution, as in the following example:

...

In this noncompliant example, non-volatilenon–volatile-qualified objects local to the function that invoked the corresponding setjmp() have indeterminate values after longjmp() has been is executed if their value has been changed since the invocation of setjmp().

...

Recommendation

Severity

Likelihood

Remediation Cost

Priority

Level

MSC22-C

low

probable

medium

P4

L3

Related Guidelines

ISO/IEC 9899:1999 Section 2011 Section 7.13, "Nonlocal jumps <setjmp.h>," , Section Annex J.2, "Portability issues"

...

 

...