Issue #13705 has been updated by nagachika (Tomoyuki Chikanaga).

Backport changed from 2.2: WONTFIX, 2.3: REQUIRED, 2.4: REQUIRED to 2.2: WONTFIX, 2.3: REQUIRED, 2.4: DONE

ruby_2_4 r62651 merged revision(s) 59956.

----------------------------------------
Bug #13705: [PATCH] `cfp consistency error' occurs when raising exception in bmethod call event
https://bugs.ruby-lang.org/issues/13705#change-70769

* Author: ktsj (Kazuki Tsujimoto)
* Status: Closed
* Priority: Normal
* Assignee: 
* Target version: 
* ruby -v: ruby 2.5.0dev (2017-07-02 master 59246) [x86_64-linux]
* Backport: 2.2: WONTFIX, 2.3: REQUIRED, 2.4: DONE
----------------------------------------
bmethodのcallイベントの中でキャッチされない例外を起こすとcfp consistency errorになります。

~~~ruby
define_method(:m) {}

tp = TracePoint.new(:call) do
  raise ''
end

tap do
  tap do
    begin
      tp.enable
      m
    rescue
    end
  end
end
~~~

invoke_bmethodでFINISHフラグが立ったフレームを積んでからvm_execを呼び出すまでの間に
EXEC_EVENT_HOOKを呼んでいるのが原因です。

EXEC_EVENT_HOOKの呼び出し後にフレームを積むよう修正すると互換性に影響するので
FINISHフラグの設定をvm_execの直前に遅延させるのがよさそうです。

~~~diff
diff --git a/vm.c b/vm.c
index 6ff1d23..d0c11c8 100644
--- a/vm.c
+++ b/vm.c
@@ -986,7 +986,7 @@ invoke_bmethod(rb_thread_t *th, const rb_iseq_t *iseq, VALUE self, const struct
     int arg_size = iseq->body->param.size;
     VALUE ret;
 
-    vm_push_frame(th, iseq, type | VM_FRAME_FLAG_FINISH | VM_FRAME_FLAG_BMETHOD, self,
+    vm_push_frame(th, iseq, type | VM_FRAME_FLAG_BMETHOD, self,
 		  VM_GUARDED_PREV_EP(captured->ep),
 		  (VALUE)me,
 		  iseq->body->iseq_encoded + opt_pc,
@@ -996,6 +996,7 @@ invoke_bmethod(rb_thread_t *th, const rb_iseq_t *iseq, VALUE self, const struct
 
     RUBY_DTRACE_METHOD_ENTRY_HOOK(th, me->owner, me->def->original_id);
     EXEC_EVENT_HOOK(th, RUBY_EVENT_CALL, self, me->def->original_id, me->called_id, me->owner, Qnil);
+    VM_ENV_FLAGS_SET(th->ec.cfp->ep, VM_FRAME_FLAG_FINISH);
     ret = vm_exec(th);
     EXEC_EVENT_HOOK(th, RUBY_EVENT_RETURN, self, me->def->original_id, me->called_id, me->owner, ret);
     RUBY_DTRACE_METHOD_RETURN_HOOK(th, me->owner, me->def->original_id);
~~~




-- 
https://bugs.ruby-lang.org/