diff --git a/zjit/src/codegen_tests.rs b/zjit/src/codegen_tests.rs index 2f09e84d87b5e1..a5ec74e2ce0504 100644 --- a/zjit/src/codegen_tests.rs +++ b/zjit/src/codegen_tests.rs @@ -9288,6 +9288,94 @@ fn test_send_backtrace() { "#), @r#"[":3:in 'Object#jit_frame1'", ":4:in 'Object#entry'", ":6:in ''", "-e:in 'RubyVM::InstructionSequence#eval'"]"#); } +#[test] +fn test_protected_method_call_checks_caller_self() { + eval( + r#" + class EfeOrderedOptions1109 < Hash + alias_method :_get, :[] + protected :_get + end + + class EfeInheritableOptions1109 < EfeOrderedOptions1109 + def get_parent(parent, key) = parent._get(key) + end + + class EfeOtherHashOptions1109 < Hash + def get_parent(parent, key) = parent._get(key) + end + + class EfeUnrelatedOptions1109 + def get_parent(parent, key) + parent._get(key) + rescue NoMethodError + :denied + end + end + + EfeParent1109 = EfeOrderedOptions1109.new + EfeParent1109[:answer] = 42 + EfeCaller1109 = EfeInheritableOptions1109.new + EfeOtherHash1109 = EfeOtherHashOptions1109.new + EfeUnrelated1109 = EfeUnrelatedOptions1109.new + "#, + ); + let valid = with_inlining_threshold(2, || { + assert_compiles_allowing_exits( + r#" + EfeCaller1109.get_parent(EfeParent1109, :answer) + EfeCaller1109.get_parent(EfeParent1109, :answer) + EfeCaller1109.get_parent(EfeParent1109, :answer) + EfeCaller1109.get_parent(EfeParent1109, :answer) + EfeCaller1109.get_parent(EfeParent1109, :answer) + "#, + ) + }); + assert_eq!(valid, "42"); + + let iseq = with_rubyvm(|| get_instance_method_iseq("EfeInheritableOptions1109", "get_parent")); + unsafe { rb_zjit_profile_disable(iseq) }; + let mut function = iseq_to_hir(iseq).unwrap(); + function.optimize(); + function.validate().unwrap(); + let hir = format!( + "{}", + crate::hir::FunctionPrinter::without_snapshot(&function) + ); + assert!( + hir.contains("IsA") + && hir.contains("CCallWithFrame") + && hir.contains("EfeOrderedOptions1109#_get"), + "expected a caller-self guard and a direct C function call for the protected alias:\n{hir}" + ); + + let other_hash = with_inlining_threshold(2, || { + assert_compiles_allowing_exits( + r#" + EfeOtherHash1109.get_parent(EfeParent1109, :answer) + EfeOtherHash1109.get_parent(EfeParent1109, :answer) + EfeOtherHash1109.get_parent(EfeParent1109, :answer) + EfeOtherHash1109.get_parent(EfeParent1109, :answer) + EfeOtherHash1109.get_parent(EfeParent1109, :answer) + "#, + ) + }); + assert_eq!(other_hash, "42"); + + let invalid = with_inlining_threshold(2, || { + assert_compiles_allowing_exits( + r#" + EfeUnrelated1109.get_parent(EfeParent1109, :answer) + EfeUnrelated1109.get_parent(EfeParent1109, :answer) + EfeUnrelated1109.get_parent(EfeParent1109, :answer) + EfeUnrelated1109.get_parent(EfeParent1109, :answer) + EfeUnrelated1109.get_parent(EfeParent1109, :answer) + "#, + ) + }); + assert_eq!(invalid, ":denied"); +} + // Regression test: when specialized_instruction is disabled (as power_assert does), // eval'd code uses `send` instead of `opt_send_without_block`, producing SendNoProfiles. // The `times` call with a literal block is the SendNoProfiles send whose exit profiling diff --git a/zjit/src/hir.rs b/zjit/src/hir.rs index d82c938032b06b..3386e455cada90 100644 --- a/zjit/src/hir.rs +++ b/zjit/src/hir.rs @@ -4087,6 +4087,51 @@ impl Function { } } + /// Ensure the current `self` is allowed to make an explicit protected call. + /// The receiver's method lookup already proves it inherits the method owner; + /// Ruby also requires the caller's `self` to inherit that owner. + fn guard_protected_call(&mut self, block: BlockId, owner: VALUE, state: InsnId) -> bool { + if self.policy.no_side_exits { + return false; + } + let self_val = self.load_self(block); + let owner_type = Type::from_class_inexact(owner); + let self_type = self.type_of(self_val); + if !self_type.could_be(owner_type) { + return false; + } + if self_type.is_subtype(owner_type) { + return true; + } + + let class = self.push_insn( + block, + Insn::Const { + val: Const::Value(owner), + }, + ); + self.insn_types[class] = self.infer_type(class); + let allowed = self.push_insn( + block, + Insn::IsA { + val: self_val, + class, + }, + ); + self.insn_types[allowed] = self.infer_type(allowed); + self.push_insn( + block, + Insn::GuardBitEquals { + val: allowed, + expected: Const::Value(Qtrue), + reason: Box::new(SideExitReason::GuardType(owner_type)), + state, + recompile: Some(Recompile), + }, + ); + true + } + /// Validate and normalize SendDirect arguments without emitting HIR. fn build_send_direct_args(&self, caller_args: &CallerArguments, caller_splat: Option, iseq: IseqPtr, has_block: bool) -> Result { can_direct_send(iseq, caller_args, has_block, caller_splat)?; @@ -4889,15 +4934,34 @@ impl Function { // It allows you to use a faster ISEQ if possible. cme = unsafe { rb_check_overloaded_cme(cme, ci) }; let visibility = unsafe { METHOD_ENTRY_VISI(cme) }; - match (visibility, flags & VM_CALL_FCALL != 0) { - (METHOD_VISI_PUBLIC, _) => {} - (METHOD_VISI_PRIVATE, true) => {} - (METHOD_VISI_PROTECTED, true) => {} + let protected_owner = match (visibility, flags & VM_CALL_FCALL != 0) { + (METHOD_VISI_PUBLIC, _) + | (METHOD_VISI_PRIVATE, true) + | (METHOD_VISI_PROTECTED, true) => None, + (METHOD_VISI_PROTECTED, false) => { + // Refined and module-owned entries need their VM-specific + // protected-call class resolution. Keep those on the dynamic path. + let owner = unsafe { (*cme).defined_class }; + if unsafe { RB_TYPE_P(owner, RUBY_T_CLASS) } { + Some(owner) + } else { + self.set_dynamic_send_reason( + insn_id, + SendNotOptimizedNeedPermission, + ); + self.push_insn_id(block, insn_id); + continue; + } + } _ => { - self.set_dynamic_send_reason(insn_id, SendNotOptimizedNeedPermission); - self.push_insn_id(block, insn_id); continue; + self.set_dynamic_send_reason( + insn_id, + SendNotOptimizedNeedPermission, + ); + self.push_insn_id(block, insn_id); + continue; } - } + }; let mut def_type = unsafe { get_cme_def_type(cme) }; while def_type == VM_METHOD_TYPE_ALIAS { cme = unsafe { rb_aliased_callable_method_entry(cme) }; @@ -4997,6 +5061,29 @@ impl Function { self.push_insn_id(block, insn_id); continue; } + if let Some(owner) = protected_owner { + let supported = match def_type { + VM_METHOD_TYPE_ISEQ => true, + VM_METHOD_TYPE_CFUNC => { + !unsafe { rb_zjit_method_tracing_currently_enabled() } + && !unspecializable_c_call_type(flags) + } + VM_METHOD_TYPE_BMETHOD => !has_block, + VM_METHOD_TYPE_IVAR => !has_block && args.is_empty(), + VM_METHOD_TYPE_ATTRSET => !has_block && args.len() == 1, + VM_METHOD_TYPE_OPTIMIZED => !has_block, + _ => false, + }; + if !supported || !self.guard_protected_call(block, owner, state) { + self.set_dynamic_send_reason( + insn_id, + SendNotOptimizedNeedPermission, + ); + self.push_insn_id(block, insn_id); + continue; + } + } + if def_type == VM_METHOD_TYPE_ISEQ { // TODO(max): Allow non-iseq; cache cme // Only specialize positional-positional calls diff --git a/zjit/src/hir/opt_tests.rs b/zjit/src/hir/opt_tests.rs index 8c9edcec431b8e..3a7e3ac1ed5729 100644 --- a/zjit/src/hir/opt_tests.rs +++ b/zjit/src/hir/opt_tests.rs @@ -21733,15 +21733,17 @@ mod hir_opt_tests { } #[test] - fn dont_optimize_call_to_protected_method_iseq() { - eval(r#" + fn optimize_protected_method_iseq_with_self_guard() { + eval( + r#" class C protected def secret = 42 end Obj = C.new def test = Obj.secret rescue $! test - "#); + "#, + ); assert_snapshot!(hir_string("test"), @" fn test@:6: bb1(): @@ -21756,12 +21758,65 @@ mod hir_opt_tests { PatchPoint SingleRactorMode PatchPoint StableConstantNames(0x1000, Obj) v12:ObjectSubclass[VALUE(0x1008)] = Const Value(VALUE(0x1008)) - v14:BasicObject = Send v12, :secret # SendFallbackReason: Send: method private or protected and no FCALL + v21:BasicObject = LoadSelf + v22:ClassSubclass[C@0x1010] = Const Value(VALUE(0x1010)) + v23:BoolExact = IsA v21, v22 + v24:TrueClass = GuardBitEquals v23, Value(true) recompile + PatchPoint NoSingletonClass(C@0x1010) + PatchPoint MethodRedefined(C@0x1010, secret@0x1011, cme:0x1018) + v28:Fixnum[42] = Const Value(42) CheckInterrupts - Return v14 + Return v28 "); } + #[test] + fn dont_optimize_call_to_protected_method_defined_in_module() { + eval( + r#" + module EfeProtectedModule1109 + protected def secret = 42 + end + class EfeProtectedModuleCaller1109 + include EfeProtectedModule1109 + end + EfeProtectedModuleObj1109 = EfeProtectedModuleCaller1109.new + def test = EfeProtectedModuleObj1109.secret rescue $! + test + "#, + ); + let hir = hir_string("test"); + assert!( + hir.contains("Send v") + && hir.contains("SendFallbackReason: Send: method private or protected and no FCALL"), + "expected module-owned protected calls to keep a dynamic send:\n{hir}" + ); + } + + #[test] + fn dont_optimize_call_to_protected_method_under_refinement() { + eval( + r#" + class EfeRefinedProtected1109 + end + module EfeProtectedRefinement1109 + refine EfeRefinedProtected1109 do + protected def secret = 42 + end + end + using EfeProtectedRefinement1109 + EfeRefinedProtectedObj1109 = EfeRefinedProtected1109.new + def test = EfeRefinedProtectedObj1109.secret rescue $! + test + "#, + ); + let hir = hir_string("test"); + assert!( + hir.contains("Send v") && !hir.contains(" IsA "), + "expected refined protected calls to keep a dynamic send:\n{hir}" + ); + } + // Test that when a singleton class has been seen for a class, we skip the // NoSingletonClass optimization to avoid an invalidation loop. #[test]