diff --git a/internal/vm/thread.go b/internal/vm/thread.go index c3d54951..7f2d0023 100644 --- a/internal/vm/thread.go +++ b/internal/vm/thread.go @@ -3,6 +3,7 @@ package vm import ( "fmt" "math" + "reflect" "runtime" "sort" "strconv" @@ -130,10 +131,9 @@ type RThread struct { held []*RMutex // reportOnException mirrors Thread#report_on_exception (default true in MRI): - // whether a thread terminating with an unhandled exception prints a warning. - // rbgo does not print the warning, but the accessor is honoured for programs - // (and specs) that toggle it. Set on spawn so the zero value never masquerades - // as an explicit false. + // whether a thread terminating with an unhandled exception prints a report to + // $stderr (reportThreadException). Set on spawn so the zero value never + // masquerades as an explicit false. reportOnException bool } @@ -362,14 +362,16 @@ func (t *RThread) Truthy() bool { return true } // main thread); the status word is the live status, or "dead" once finished. func (t *RThread) describe() string { var b strings.Builder - fmt.Fprintf(&b, "#") return b.String() @@ -498,6 +500,44 @@ func (vm *VM) abortMainThread(t *RThread) { } } +// reportThreadException prints what MRI prints when a thread dies of an +// unhandled exception while its report_on_exception is true. thread.c +// thread_start_func_2 (v4.0.10:733-739) does, for an errinfo that is neither a +// fatal nor a SystemExit (a kill never reaches here): +// +// if (th->report_on_exception) { +// VALUE mesg = rb_thread_to_s(th->self); +// rb_str_cat_cstr(mesg, " terminated with exception (report_on_exception is true):\n"); +// rb_write_error_str(mesg); +// rb_ec_error_print(th->ec, errinfo); +// } +// +// It runs while the thread is still alive, so its #to_s says "run". +// rb_write_error_str goes through $stderr#write, and rb_ec_error_print is the +// top-level printer, whose Ruby face is Exception#full_message (highlight and +// order resolved from $stderr). A failure while printing is swallowed, as +// rb_ec_error_print does under EC_PUSH_TAG. Only a real exception object is +// reported: a Go-level failure wrapped as a RuntimeError has no MRI counterpart. +func (vm *VM) reportThreadException(t *RThread) { + if t.err == nil || t.err.Obj == nil || !t.reportOnException { + return + } + if se, ok := vm.consts["SystemExit"].(*RClass); ok && vm.send(t.err.Obj, "is_a?", []object.Value{se}, nil).Truthy() { + return + } + defer func() { + if r := recover(); r != nil { + if _, ok := r.(RubyError); !ok { + panic(r) + } + } + }() + out := vm.stderrValue() + head := t.describe() + " terminated with exception (report_on_exception is true):\n" + vm.send(out, "write", []object.Value{object.NewString(head)}, nil) + vm.send(out, "write", []object.Value{vm.send(t.err.Obj, "full_message", nil, nil)}, nil) +} + // threadCaptureErr turns a panic recovered in a thread's goroutine into the // RubyError to re-raise on join: a Ruby exception is preserved as-is; any other // panic (a Go-level failure) is wrapped as a RuntimeError rather than crashing @@ -599,6 +639,7 @@ func (vm *VM) registerThreadClass() { }() t.result = vm.callBlock(t.blk, t.args) }() + vm.reportThreadException(t) // MRI: before the thread is marked dead t.status = "dead" close(t.done) // MRI: rb_threadptr_join_list_wakeup, before the two below // A dying thread gives up the mutexes it still holds, then -- if its diff --git a/internal/vm/thread_blocking_test.go b/internal/vm/thread_blocking_test.go index 1c66ed39..8ab36eb5 100644 --- a/internal/vm/thread_blocking_test.go +++ b/internal/vm/thread_blocking_test.go @@ -126,8 +126,10 @@ t.kill t.join m.lock puts "relocked"`, "relocked\n"}, - // And by a thread that died on an unhandled exception. - {"failed_owner_releases_mutex", `m = Mutex.new + // And by a thread that died on an unhandled exception (whose stderr report, + // which MRI prints too, is not the subject here). + {"failed_owner_releases_mutex", `Thread.report_on_exception = false +m = Mutex.new t = Thread.new { m.lock; raise "boom" } begin; t.join; rescue RuntimeError; end m.lock @@ -210,8 +212,11 @@ p t.join(0.05) t.kill p t.join(5).equal?(t)`, "nil\ntrue\n"}, // An unhandled exception WITHOUT abort_on_exception does not reach the main - // thread: its sleep runs to completion, as in MRI. - {"no_abort_does_not_interrupt_main", `Thread.new { raise "boom" } + // thread: its sleep runs to completion, as in MRI. (Its death report, which + // MRI writes to $stderr and this harness folds into the output, is + // report_on_exception's business and is switched off here and below.) + {"no_abort_does_not_interrupt_main", `Thread.report_on_exception = false +Thread.new { raise "boom" } sleep 0.2 puts "main survived"`, "main survived\n"}, // The relock at the end of ConditionVariable#wait / Mutex#sleep is @@ -308,7 +313,8 @@ end`, "deadlock; recursive locking\n"}, // Until this case existed, that arm of the loop was reached only through the // uninterruptible relock, whose timing decides whether the waiter is parked // when the kill lands. A gate that reads coverage on the unlucky run fails. - {"masked_raise_reaches_a_mutex_wait", `m = Mutex.new + {"masked_raise_reaches_a_mutex_wait", `Thread.report_on_exception = false +m = Mutex.new m.lock t = Thread.new do Thread.handle_interrupt(RuntimeError => :never) do @@ -328,7 +334,8 @@ rescue RuntimeError => e end`, "lock acquired normally\ndelivered on exit: masked\n"}, // A raise masked by Thread.handle_interrupt(:never) does not end the wait it // arrives during — the wait goes back to sleep, as do_mutex_lock's loop does. - {"masked_raise_does_not_end_the_wait", `q = Queue.new + {"masked_raise_does_not_end_the_wait", `Thread.report_on_exception = false +q = Queue.new t = Thread.new do Thread.handle_interrupt(RuntimeError => :never) do q.pop @@ -359,9 +366,13 @@ begin; t.join; rescue RuntimeError => e; puts "delivered on exit: #{e.message}"; // The flag was previously stored by its setter and read by its getter and by // nothing else: a declared field equal to its own default, which no program could // tell from the feature being absent. +// +// Every program silences report_on_exception: the stderr report MRI also prints +// for these threads is TestThreadReportOnException's subject, not this one's. func TestAbortOnExceptionInterruptsMainThread(t *testing.T) { cases := []struct{ name, src, want string }{ - {"class_level_flag", `Thread.abort_on_exception = true + {"class_level_flag", `Thread.report_on_exception = false +Thread.abort_on_exception = true begin Thread.new { raise "boom" } sleep 5 @@ -369,7 +380,8 @@ begin rescue RuntimeError => e puts "interrupted: #{e.message}" end`, "interrupted: boom\n"}, - {"per_thread_flag", `begin + {"per_thread_flag", `Thread.report_on_exception = false +begin t = Thread.new { sleep 0.05; raise "later" } t.abort_on_exception = true sleep 5 @@ -378,7 +390,8 @@ rescue RuntimeError => e puts "interrupted: #{e.message}" end`, "interrupted: later\n"}, // The exception the main thread sees is the very object the thread raised. - {"same_exception_object", `exc = RuntimeError.new("shared") + {"same_exception_object", `Thread.report_on_exception = false +exc = RuntimeError.new("shared") Thread.abort_on_exception = true begin Thread.new { raise exc } diff --git a/internal/vm/thread_report_internal_test.go b/internal/vm/thread_report_internal_test.go new file mode 100644 index 00000000..29b897f9 --- /dev/null +++ b/internal/vm/thread_report_internal_test.go @@ -0,0 +1,55 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm + +import ( + "io" + "testing" + + "github.com/go-embedded-ruby/ruby/internal/object" +) + +// reportWithSink runs reportThreadException for a thread that died of a +// RuntimeError, with $stderr set to an object whose #write is write. +func reportWithSink(t *testing.T, write func()) { + t.Helper() + vm := New(io.Discard) + cls := newClass("ReportSink", vm.cObject) + cls.define("write", func(_ *VM, _ object.Value, _ []object.Value, _ *Proc) object.Value { + write() + return object.NilV + }) + vm.globals["$stderr"] = &RObject{class: cls, ivars: map[string]object.Value{}} + exc := vm.send(vm.consts["RuntimeError"], "new", []object.Value{object.NewString("x")}, nil) + th := &RThread{err: &RubyError{Class: "RuntimeError", Obj: exc}, reportOnException: true} + vm.reportThreadException(th) +} + +// TestReportThreadExceptionSwallowsARubyError: a $stderr whose #write raises +// must not turn the report into a second failure, as rb_ec_error_print runs +// under EC_PUSH_TAG. (MRI 4.0.10 itself never returns from this case: the +// probe hangs for 30 s, so the behaviour asserted here is rbgo's, not a copy.) +func TestReportThreadExceptionSwallowsARubyError(t *testing.T) { + calls := 0 + reportWithSink(t, func() { + calls++ + raise("RuntimeError", "boom") + }) + if calls != 1 { + t.Errorf("the report must stop at the first failing write, wrote %d times", calls) + } +} + +// TestReportThreadExceptionKeepsAGoPanic: a Go-level panic while printing is +// an rbgo defect, not a Ruby exception, and must not be swallowed. +func TestReportThreadExceptionKeepsAGoPanic(t *testing.T) { + defer func() { + if r := recover(); r != "plain go panic" { + t.Errorf("a Go panic while reporting must propagate, got %v", r) + } + }() + reportWithSink(t, func() { panic("plain go panic") }) + t.Fatal("expected the Go panic to propagate") +} diff --git a/internal/vm/thread_report_test.go b/internal/vm/thread_report_test.go new file mode 100644 index 00000000..d1b1d952 --- /dev/null +++ b/internal/vm/thread_report_test.go @@ -0,0 +1,80 @@ +// Copyright (c) the go-embedded-ruby/ruby authors +// +// SPDX-License-Identifier: BSD-3-Clause + +package vm_test + +import ( + "os" + "path/filepath" + "strconv" + "testing" +) + +// threadReportProgram is run from a required FILE: Thread#to_s names the file +// and line of the thread's block, and a block with no file has no such field. +// The backtrace label is masked ('[^']*'): the label of a required file's top +// level is a separate defect, and this test is about the report. +const threadReportProgram = `require "stringio" +def report + $stderr = StringIO.new + yield + $stderr.string.lines.first(2) +ensure + $stderr = STDERR +end +l = report { Thread.new { raise ArgumentError, "a1" }.join rescue nil } +puts l[0].sub(/0x\h{16}/, "X").sub(/ \S+:(\d+) run>/, ' F:\1 run>') +puts l[1].sub(/\A\S+?:(\d+):in '[^']*'/, 'F:\1') +l = report do + Thread.new { Thread.current.name = "w"; raise IOError, "named" }.join rescue nil +end +puts l[0].sub(/0x\h{16}/, "X").sub(/ \S+:(\d+) run>/, ' F:\1 run>') +p report { Thread.new { Thread.current.report_on_exception = false; raise "q" }.join rescue nil } +Thread.report_on_exception = false +p report { Thread.new { raise "q" }.join rescue nil } +Thread.report_on_exception = true +t = Thread.new do + :x +end +t.join +puts t.to_s.sub(/0x\h{16}/, "X").sub(/ \S+:(\d+) /, ' F:\1 ') +` + +// TestThreadReportOnException: a thread that dies of an unhandled exception +// while its report_on_exception is true writes " terminated with +// exception (report_on_exception is true):" and the error to $stderr, as +// thread.c thread_start_func_2 (v4.0.10:733-739) does; the per-thread flag and +// the class-level default (which a new thread inherits) both silence it. #to_s +// carries a 16-digit address and the block's FIRST line (20 for a do-block +// spanning 20-22). Expected output: MRI 4.0.10, rubydiff AGREE on the same +// program required from a file. +func TestThreadReportOnException(t *testing.T) { + path := filepath.Join(t.TempDir(), "report.rb") + if err := os.WriteFile(path, []byte(threadReportProgram), 0o600); err != nil { + t.Fatal(err) + } + got := eval(t, "require "+strconv.Quote(path)) + want := "# terminated with exception (report_on_exception is true):\n" + + "F:9: a1 (ArgumentError)\n" + + "# terminated with exception (report_on_exception is true):\n" + + "[]\n[]\n" + + "#\n" + if got != want { + t.Errorf("got %q\nwant %q", got, want) + } +} + +// TestThreadReportSkipsSystemExit: thread_start_func_2 reports neither a +// SystemExit nor a subclass of it (the rb_obj_is_kind_of branch, thread.c +// v4.0.10:726); the join still re-raises it. Expected output: MRI 4.0.10. +func TestThreadReportSkipsSystemExit(t *testing.T) { + checkCases(t, []runCase{ + {`$stderr = $stdout +t = Thread.new { raise SystemExit.new(4, "bye") } +begin; t.join; rescue SystemExit => e; p [e.class, e.status]; end +t = Thread.new { exit 5 } +begin; t.join; rescue SystemExit => e; p [e.class, e.status]; end +puts "end"`, "[SystemExit, 4]\n[SystemExit, 5]\nend\n"}, + }) +} diff --git a/internal/vm/thread_test.go b/internal/vm/thread_test.go index 102adf5f..a837f997 100644 --- a/internal/vm/thread_test.go +++ b/internal/vm/thread_test.go @@ -25,8 +25,8 @@ func TestThread(t *testing.T) { {`Thread.pass; p :passed`, ":passed\n"}, // Exception in a thread is re-raised on join, and changes its status. - {`t = Thread.new { raise "boom" }; begin; t.join; rescue => e; p e.message; end`, "\"boom\"\n"}, - {`t = Thread.new { raise "x" }; begin; t.join; rescue; end; p t.status`, "nil\n"}, + {`Thread.report_on_exception = false; t = Thread.new { raise "boom" }; begin; t.join; rescue => e; p e.message; end`, "\"boom\"\n"}, + {`Thread.report_on_exception = false; t = Thread.new { raise "x" }; begin; t.join; rescue; end; p t.status`, "nil\n"}, // Mutex. {`p [Mutex.equal?(Thread::Mutex), Queue.equal?(Thread::Queue)]`, "[true, true]\n"}, diff --git a/internal/vm/wave24_fiber_thread_test.go b/internal/vm/wave24_fiber_thread_test.go index ede596ea..a4ffd6cd 100644 --- a/internal/vm/wave24_fiber_thread_test.go +++ b/internal/vm/wave24_fiber_thread_test.go @@ -116,7 +116,7 @@ func TestWave24FiberThread(t *testing.T) { {`f = Fiber.new { 1 }; f.resume; p f.alive?; p f.kill.class; p f.alive?`, "false\nFiber\nfalse\n"}, {`f = Fiber.new { Fiber.yield }; f.resume; begin; (begin; raise "e1"; rescue => a; (begin; raise "e2"; rescue => b; f.raise(a, cause: b); end); end); rescue => e; p e.message; end`, "\"circular causes\"\n"}, {`e1 = nil; e3 = nil; g = Fiber.new { Fiber.yield }; g.resume; begin; raise "E1"; rescue => e1; begin; raise "E2"; rescue; begin; raise "E3"; rescue => e3; begin; g.raise(e1, cause: e3); rescue => e; p [e.class, e.message]; end; end; end; end`, "[ArgumentError, \"circular causes\"]\n"}, - {`out = []; go = false; th = Thread.new { begin; Thread.handle_interrupt(RuntimeError => :on_blocking) { begin; Thread.pass until STATE[0]; rescue RuntimeError; out << :inner; end }; rescue RuntimeError; out << :deferred; end }`, ""}, + {`Thread.report_on_exception = false; out = []; go = false; th = Thread.new { begin; Thread.handle_interrupt(RuntimeError => :on_blocking) { begin; Thread.pass until STATE[0]; rescue RuntimeError; out << :inner; end }; rescue RuntimeError; out << :deferred; end }`, ""}, {`p Thread.start { :started }.value`, ":started\n"}, {`p Thread.current.send(:priority=, 1)`, "1\n"}, {`begin; Thread.current.send(:priority=); rescue ArgumentError => e; p e.class; end`, "ArgumentError\n"}, @@ -190,9 +190,9 @@ p t.status // TestWave24ThreadDescribeFileField covers the file field of Thread#to_s: MRI // prints the source location of the thread's block, which only exists for a -// thread created in a required file (rbgo tracks no per-instruction line, so the -// line is 0 — the same value __LINE__ reports there). Asserted against MRI 4.0.5, -// which prints "#" for the same program. +// thread created in a required file; the line is the block's first line +// (rb_proc_location), 1 here. Asserted against MRI 4.0.5, which prints +// "#" for the same program. func TestWave24ThreadDescribeFileField(t *testing.T) { dir := t.TempDir() path := filepath.Join(dir, "spawner.rb") @@ -204,7 +204,7 @@ func TestWave24ThreadDescribeFileField(t *testing.T) { // the separators into forward slashes, as MRI's rb_file_expand_path does — so // the field holds the ToSlash form, whatever the platform separator is. There // is then nothing for String#inspect to escape. - field := filepath.ToSlash(path) + ":0" + field := filepath.ToSlash(path) + ":1 " if !strings.Contains(got, field) || !strings.Contains(got, " dead>") { t.Errorf("Thread#to_s file field: got %q, want it to name %q and end \" dead>\"", got, field) }