liveBook · Manning

Setjmp/longjmp

As explained in Rust in Action: Systems programming concepts and techniques

longjmp is a non-local control-flow function or compiler intrinsic that restores an execution context previously saved by setjmp.

setjmp marks a location and saves an execution context; longjmp restores that context, transferring control non-locally instead of returning through each intervening call. This escape route can reach error-handling code when an error or interrupt occurs deep in a call stack. section 12.9

A Rust implementation connects the control-flow mechanism to LLVM and operating-system facilities:

  • Declare LLVM's setjmp and longjmp intrinsics with extern "C" signatures and link_name attributes. section 12.9.2
  • Use the required link_llvm_intrinsics crate feature and call the declared functions inside unsafe code. section 12.9.2
  • Store the jump buffer and shutdown flag in mutable global state, with the example restricted to non-Windows targets. section 12.9.5

Escaping recursive calls

A recursive dive() call normally prints increasing depth markers and then prints them again while returning. With longjmp, control can leave after the third call, skip the remaining stack frames, and continue in main(), producing an early-return message followed by finishing. section 12.9

Table 12.3 Comparing the intended output from listing 12.13 and listing 12.17 (view table figure)

Listing 12.13 produces a symmetrical pattern. Each level is caused by a nested call to dive(), which is removed when the calls return.

Listing 12.17 produces a much different pattern. After a few calls to dive(), control teleports back to main() without returning the calls to dive().

#
##
###
####
#####
###
##
#
#
##
###
early return!
finishing!

Compare ordinary recursive unwinding with longjmp's direct transfer to main() through the contrasting depth-marker output. section 12.9

How Rust in Action: Systems programming concepts and techniques covers it

How deep it goes
Explains saved contexts, skipped stack frames, recursive behavior, and LLVM declarations, but stops short of full intrinsic implementation details.
Examples
Uses recursive dive() calls, depth-marker output, a saved jump buffer, signal constants, and a shutdown flag.
What it assumes
Assumes basic Rust functions and recursion while teaching call-stack behavior, LLVM intrinsics, C conventions, and unsafe access.
What you can do after
Build it from scratch as a non-Windows Rust project that invokes LLVM's setjmp and longjmp facilities through unsafe declarations.
How it connects
Connects non-local control transfer with call stacks, signal handlers, exception handling, unsafe Rust, and LLVM intrinsics.

Also explained in

Compare how 3 books explain setjmp/longjmp →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Rust in Action: Systems programming concepts and techniques. The section links point to the parts of the book it draws on.