Skip to content

Commit

Permalink
Add thread safety in ZTS mode for RayAOP
Browse files Browse the repository at this point in the history
Introduce mutex allocation and locking mechanisms in ZTS mode to ensure thread safety. This includes defining the MUTEX_T type, allocating and freeing the mutex during module initialization and shutdown, and utilizing it for global locks.
  • Loading branch information
koriym committed Nov 5, 2024
1 parent e649886 commit aa024ab
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 3 deletions.
16 changes: 13 additions & 3 deletions php_rayaop.h
Original file line number Diff line number Diff line change
Expand Up @@ -62,10 +62,17 @@ ZEND_END_ARG_INFO()
#define PHP_RAYAOP_DEBUG_PRINT(fmt, ...)
#endif

/* Thread safety macros */
/* Declare mutex type */
#if defined(WIN32)
#define MUTEX_T HANDLE
#else
#define MUTEX_T pthread_mutex_t*
#endif
extern MUTEX_T rayaop_mutex;

#ifdef ZTS
#define RAYAOP_G_LOCK() tsrm_mutex_lock(rayaop_globals_id)
#define RAYAOP_G_UNLOCK() tsrm_mutex_unlock(rayaop_globals_id)
#define RAYAOP_G_LOCK() tsrm_mutex_lock(rayaop_mutex)
#define RAYAOP_G_UNLOCK() tsrm_mutex_unlock(rayaop_mutex)
#else
#define RAYAOP_G_LOCK()
#define RAYAOP_G_UNLOCK()
Expand Down Expand Up @@ -104,6 +111,9 @@ ZEND_BEGIN_MODULE_GLOBALS(rayaop)
uint32_t debug_level; /* Debug level */
ZEND_END_MODULE_GLOBALS(rayaop)

/* Global initializer */
static void php_rayaop_init_globals(zend_rayaop_globals *globals);

/* Globals access macro */
#ifdef ZTS
#define RAYAOP_G(v) TSRMG(rayaop_globals_id, zend_rayaop_globals *, v)
Expand Down
20 changes: 20 additions & 0 deletions rayaop.c
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
#ifdef ZTS
MUTEX_T rayaop_mutex;
#endif

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
Expand Down Expand Up @@ -317,8 +321,16 @@ PHP_FUNCTION(method_intercept_enable) {
/* Module initialization */
PHP_MINIT_FUNCTION(rayaop) {
#ifdef ZTS
/* First, allocate TSRMG */
ts_allocate_id(&rayaop_globals_id, sizeof(zend_rayaop_globals),
(ts_allocate_ctor)php_rayaop_init_globals, NULL);

/* Then initialize mutex */
rayaop_mutex = tsrm_mutex_alloc();
if (!rayaop_mutex) {
php_error_docref(NULL, E_ERROR, "Failed to allocate mutex for RayAOP");
return FAILURE;
}
#else
php_rayaop_init_globals(&rayaop_globals);
#endif
Expand All @@ -340,6 +352,14 @@ PHP_MINIT_FUNCTION(rayaop) {

/* Module shutdown */
PHP_MSHUTDOWN_FUNCTION(rayaop) {
#ifdef ZTS
/* Free mutex */
if (rayaop_mutex) {
tsrm_mutex_free(rayaop_mutex);
rayaop_mutex = NULL;
}
#endif

if (php_rayaop_original_execute_ex) {
zend_execute_ex = php_rayaop_original_execute_ex;
}
Expand Down

0 comments on commit aa024ab

Please sign in to comment.