php / php/php-src

[FFI] Segmentation fault when calling callback function

Open
#9,214 9 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Extension: ffi Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

The following code:

<?php
class Test {
   public $lib;
   public function __construct() {
      $this->lib = \FFI::cdef("extern void setCloseSessionCallback(void(*fun)(unsigned long cid));
      extern void testCloseSessionCallback();
      ", "./libsomelib.so");
   }
}

$tclass = new Test();
$tclass->lib->setCloseSessionCallback(function($cid){
   echo "ok\n";
});

$tclass->lib->testCloseSessionCallback(); //this function creates new std::thread from c++ stl, sleeps 2 seconds and calls function passed to setCloseSessionCallback
while(true); //prevent php script from completion because testCloseSessionCallback running in other thread

Resulted in this output:

segmentation fault (core dumped)

But I expected this output instead:

ok

gdb backtrace:
image

PHP Version

PHP 8.0.21 (zts) with Zend OPcache v8.0.21

Operating System

Manjaro Linux

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the PHP FFI reproduction in the issue, including the callback registered through libsomelib.so and the C++ thread that invokes it. Use the provided gdb backtrace while testing the PHP 8.0.21 ZTS setup on Manjaro Linux. Done means the callback prints "ok" without a segmentation fault.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, php
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.