From 44a338114d170251dc6da00baabb7180e8d568c7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Efe=20G=C3=B6kdemir?= Date: Tue, 3 Nov 2026 05:23:28 +0300 Subject: [PATCH] Make ZJIT tracing safe across Ractors --- test/ruby/test_zjit_cli.rb | 24 +++++++++++ zjit/src/state.rs | 84 ++++++++++++++++++++++---------------- zjit/src/stats.rs | 8 ++-- 3 files changed, 76 insertions(+), 40 deletions(-) diff --git a/test/ruby/test_zjit_cli.rb b/test/ruby/test_zjit_cli.rb index 8b9765e7a2252c..4d1210e0c6555c 100644 --- a/test/ruby/test_zjit_cli.rb +++ b/test/ruby/test_zjit_cli.rb @@ -392,6 +392,30 @@ def array.itself = :not_itself RUBY end + def test_fallback_tracing_is_ractor_safe + assert_runs 'true', <<~RUBY, extra_args: ['--zjit-trace-fallbacks'] + Warning[:experimental] = false + + def idx(array, index) = array[index] + + trace_file = "/tmp/perfetto-\#{Process.pid}.fxt" + begin + initial_trace_size = File.size(trace_file) + ractors = 2.times.map do + Ractor.new do + array = [1] + 50_000.times { idx(array, 99) } + end + end + ractors.each { |ractor| ractor.respond_to?(:value) ? ractor.value : ractor.take } + + File.size(trace_file) > initial_trace_size + ensure + File.unlink(trace_file) if File.exist?(trace_file) + end + RUBY + end + def test_send_forwarded_block_arg_nil_then_non_nil # Regression test: when a forwarded &block arg is profiled as nil, the nil # block optimization must update the frame state to match the stripped args. diff --git a/zjit/src/state.rs b/zjit/src/state.rs index 53587072b359ef..7ac06de241ab32 100644 --- a/zjit/src/state.rs +++ b/zjit/src/state.rs @@ -5,6 +5,7 @@ use crate::cruby::{self, rb_bug_panic_hook, rb_vm_insn_count, src_loc, EcPtr, Qn use crate::cruby_methods; use cruby::{ID, rb_callable_method_entry, get_def_method_serial, rb_gc_register_mark_object, ruby_str_to_rust_string_result}; use std::sync::atomic::Ordering; +use std::sync::Mutex; use crate::invariants::Invariants; use crate::asm::CodeBlock; use crate::options::{get_option, rb_zjit_prepare_options}; @@ -117,9 +118,6 @@ pub struct ZJITState { /// Counter pointers for access counts of ISEQs accessed by JIT code iseq_calls_count_pointers: HashMap>, - /// Perfetto tracer for --zjit-trace-exits - perfetto_tracer: Option, - /// Frame metadata for ISEQ and C calls that are known at compile time jit_frames: Vec<*mut JITFrame>, @@ -152,6 +150,9 @@ enum InitializationState { /// Private singleton instance of the codegen globals static mut ZJIT_STATE: InitializationState = InitializationState::Uninitialized; +/// Process-wide tracer, shared by Ractors when tracing ZJIT events. +static PERFETTO_TRACER: Mutex> = Mutex::new(None); + impl ZJITState { /// Initialize the ZJIT globals. Return the address of the JIT entry trampoline. pub fn init() -> *const u8 { @@ -205,10 +206,10 @@ impl ZJITState { not_annotated_frame_cfunc_counter_pointers: HashMap::new(), ccall_counter_pointers: HashMap::new(), iseq_calls_count_pointers: HashMap::new(), - perfetto_tracer, jit_frames: vec![], jit_frame_allocator: JITFrameAllocator::new(), }; + *PERFETTO_TRACER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()) = perfetto_tracer; unsafe { ZJIT_STATE = Enabled(zjit_state); } // With --zjit-stats, use a different trampoline on function stub exits @@ -364,10 +365,10 @@ impl ZJITState { ZJITState::get_instance().function_stub_hit_trampoline } - /// Get a mutable reference to the Perfetto tracer - pub fn get_tracer() -> Option<&'static mut PerfettoTracer> { - if !ZJITState::has_instance() { return None; } - ZJITState::get_instance().perfetto_tracer.as_mut() + /// Run a closure while holding the lock for the process-wide Perfetto tracer. + pub fn with_tracer(func: impl FnOnce(&mut PerfettoTracer) -> R) -> Option { + let mut tracer = PERFETTO_TRACER.lock().unwrap_or_else(|poisoned| poisoned.into_inner()); + tracer.as_mut().map(func) } } @@ -527,19 +528,23 @@ pub extern "C" fn rb_zjit_record_exit_stack(reason: *const std::ffi::c_char) { return; } - let tracer = match ZJITState::get_tracer() { - Some(t) => t, - None => return, - }; - - // When `trace_side_exits_sample_interval` is non-zero, apply sampling. - if get_option!(trace_side_exits_sample_interval) != 0 { - if tracer.skipped_samples < get_option!(trace_side_exits_sample_interval) { + let sample_interval = get_option!(trace_side_exits_sample_interval); + let should_trace = match ZJITState::with_tracer(|tracer| { + if sample_interval == 0 { + true + } else if tracer.skipped_samples < sample_interval { tracer.skipped_samples += 1; - return; + false } else { tracer.skipped_samples = 0; + true } + }) { + Some(should_trace) => should_trace, + None => return, + }; + if !should_trace { + return; } // Collect profile frames @@ -552,7 +557,7 @@ pub extern "C" fn rb_zjit_record_exit_stack(reason: *const std::ffi::c_char) { unsafe { std::ffi::CStr::from_ptr(reason).to_str().unwrap_or("unknown") } }; - tracer.write_event("side_exit", reason_str, &frames); + ZJITState::with_tracer(|tracer| tracer.write_event("side_exit", reason_str, &frames)); } /// Record a backtrace with ZJIT fallbacks as a Perfetto trace event @@ -562,19 +567,23 @@ pub extern "C" fn rb_zjit_record_fallback_stack(reason: *const std::ffi::c_char) return; } - let tracer = match ZJITState::get_tracer() { - Some(t) => t, - None => return, - }; - - // When `trace_fallbacks_sample_interval` is non-zero, apply sampling. - if get_option!(trace_fallbacks_sample_interval) != 0 { - if tracer.skipped_samples < get_option!(trace_fallbacks_sample_interval) { + let sample_interval = get_option!(trace_fallbacks_sample_interval); + let should_trace = match ZJITState::with_tracer(|tracer| { + if sample_interval == 0 { + true + } else if tracer.skipped_samples < sample_interval { tracer.skipped_samples += 1; - return; + false } else { tracer.skipped_samples = 0; + true } + }) { + Some(should_trace) => should_trace, + None => return, + }; + if !should_trace { + return; } // Collect profile frames @@ -587,7 +596,7 @@ pub extern "C" fn rb_zjit_record_fallback_stack(reason: *const std::ffi::c_char) unsafe { std::ffi::CStr::from_ptr(reason).to_str().unwrap_or("unknown") } }; - tracer.write_event("fallback", reason_str, &frames); + ZJITState::with_tracer(|tracer| tracer.write_event("fallback", reason_str, &frames)); } /// Wrap a closure in a Perfetto duration event with category "invalidation" @@ -600,18 +609,21 @@ pub fn trace_invalidation(reason_func: RF, func: F) -> R // Capture backtrace and emit begin event before patching let frames = capture_ruby_frames(); - let mut reason: String = "".into(); - if let Some(tracer) = ZJITState::get_tracer() { - let ts = tracer.elapsed_ns(); - reason = reason_func(); - tracer.write_duration_begin("invalidation", &reason, ts, &frames); + let reason = ZJITState::with_tracer(|_| ()).map(|_| reason_func()); + if let Some(reason) = &reason { + ZJITState::with_tracer(|tracer| { + let ts = tracer.elapsed_ns(); + tracer.write_duration_begin("invalidation", reason, ts, &frames); + }); } let result = func(); - if let Some(tracer) = ZJITState::get_tracer() { - let ts = tracer.elapsed_ns(); - tracer.write_duration_end("invalidation", &reason, ts); + if let Some(reason) = &reason { + ZJITState::with_tracer(|tracer| { + let ts = tracer.elapsed_ns(); + tracer.write_duration_end("invalidation", reason, ts); + }); } result } diff --git a/zjit/src/stats.rs b/zjit/src/stats.rs index f7b07b0daa730a..0aad7eaa463e1e 100644 --- a/zjit/src/stats.rs +++ b/zjit/src/stats.rs @@ -1013,15 +1013,15 @@ pub fn trace_compile_phase(name: &str, func: F) -> R where F: FnOnce() -> if !get_option!(trace_compiles, /*default=*/false) { return func(); } - if let Some(tracer) = ZJITState::get_tracer() { + ZJITState::with_tracer(|tracer| { let ts = tracer.elapsed_ns(); tracer.write_duration_begin("compile", name, ts, &[]); - } + }); let result = func(); - if let Some(tracer) = ZJITState::get_tracer() { + ZJITState::with_tracer(|tracer| { let ts = tracer.elapsed_ns(); tracer.write_duration_end("compile", name, ts); - } + }); result }