From aa024abe370c616c5b6468f82ed68ab623de8b80 Mon Sep 17 00:00:00 2001 From: Akihito Koriyama Date: Tue, 5 Nov 2024 22:29:57 +0900 Subject: [PATCH] Add thread safety in ZTS mode for RayAOP 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. --- php_rayaop.h | 16 +++++++++++++--- rayaop.c | 20 ++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/php_rayaop.h b/php_rayaop.h index fbc3116..6adbdaf 100644 --- a/php_rayaop.h +++ b/php_rayaop.h @@ -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() @@ -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) diff --git a/rayaop.c b/rayaop.c index 4acfd0d..31c85b6 100644 --- a/rayaop.c +++ b/rayaop.c @@ -1,3 +1,7 @@ +#ifdef ZTS +MUTEX_T rayaop_mutex; +#endif + #ifdef HAVE_CONFIG_H #include "config.h" #endif @@ -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 @@ -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; }