Bug #22541
closed`Thread#raise` and `Fiber#raise` can set VM throw data as `Exception#cause`, causing a crash.
Description
Thread#raise and Fiber#raise can store VM-internal throw data as the exception's cause. This happens when they are
called while a non-local exit (break, return or throw) is unwinding through a C frame, for example from a signal
trap. Any code that later reads the cause, such as Exception#full_message, crashes the interpreter.
This is a regression in Ruby 4.0. The same problem was fixed for rb_ec_setup_exception in #19593, but Thread#raise
and Fiber#raise now go through rb_exception_setup (https://github.com/ruby/ruby/pull/13967), which does not have the
check. #21865 restored the checked path for the VM's own signal raise, but not for these two methods.
Background¶
This was discovered in a production application using Async::Container, whose signal handler is Signal.trap(:INT) { Thread.current.raise(Interrupt) }. When the signal arrived while a break was unwinding, the resulting Interrupt had
throw data as its cause, and error reporting crashed when it read the cause.
A minimal reproduction is:
Signal.trap(:INT) { Thread.current.raise(Interrupt) }
Thread.new { loop { Process.kill(:INT, Process.pid); sleep 0.001 } }
50.times do
loop { (1..1).any? }
rescue Interrupt => e
e.full_message # walks e.cause
end
puts "no crash"
Expected output:
Actual result on Ruby 4.0.9:
The crash is in show_cause, called from exc_full_message. Ruby 3.4.8 prints no crash.
Tested with:
Proposed fix¶
Discard throw data when rb_exception_setup takes the implicit cause from errinfo, the same way
rb_ec_setup_exception does.
Pull request¶
PR: https://github.com/ruby/ruby/pull/19861
The PR includes:
- The
THROW_DATA_Pcheck inrb_exception_setup. - Regression tests for
Thread#raiseandFiber#raisethat do not depend on signals or timing.
Once accepted, I would like to request a backport to Ruby 4.0.