xref: /PHP-7.4/sapi/phpdbg/phpdbg_sigsafe.c (revision 1ad08256)
1 #include "phpdbg_sigsafe.h"
2 #include "phpdbg.h"
3 
ZEND_EXTERN_MODULE_GLOBALS(phpdbg)4 ZEND_EXTERN_MODULE_GLOBALS(phpdbg)
5 
6 #define STR(x) #x
7 #define EXP_STR(x) STR(x)
8 
9 static void* zend_mm_mem_alloc(zend_mm_storage *storage, size_t size, size_t alignment) {
10 
11 	if (EXPECTED(size <= PHPDBG_SIGSAFE_MEM_SIZE && !PHPDBG_G(sigsafe_mem).allocated)) {
12 		PHPDBG_G(sigsafe_mem).allocated = 1;
13 		return (void *) (((size_t) PHPDBG_G(sigsafe_mem).mem & ~(alignment - 1)) + alignment);
14 	}
15 
16 	zend_quiet_write(PHPDBG_G(io)[PHPDBG_STDERR].fd, ZEND_STRL("Tried to allocate more than " EXP_STR(PHPDBG_SIGSAFE_MEM_SIZE) " bytes from stack memory in signal handler ... bailing out of signal handler\n"));
17 
18 	if (*EG(bailout)) {
19 		LONGJMP(*EG(bailout), FAILURE);
20 	}
21 
22 	zend_quiet_write(PHPDBG_G(io)[PHPDBG_STDERR].fd, ZEND_STRL("Bailed out without a bailout address in signal handler!\n"));
23 
24 	return NULL;
25 }
26 
zend_mm_mem_free(zend_mm_storage * storage,void * ptr,size_t size)27 static void zend_mm_mem_free(zend_mm_storage *storage, void *ptr, size_t size) {
28 }
29 
phpdbg_set_sigsafe_mem(char * buffer)30 void phpdbg_set_sigsafe_mem(char *buffer) {
31 	phpdbg_signal_safe_mem *mem = &PHPDBG_G(sigsafe_mem);
32 	const zend_mm_handlers phpdbg_handlers = {
33 		zend_mm_mem_alloc,
34 		zend_mm_mem_free,
35 		NULL,
36 		NULL,
37 	};
38 
39 	mem->mem = buffer;
40 	mem->allocated = 0;
41 
42 	mem->heap = zend_mm_startup_ex(&phpdbg_handlers, NULL, 0);
43 
44 	mem->old_heap = zend_mm_set_heap(mem->heap);
45 }
46 
phpdbg_original_heap_sigsafe_mem(void)47 zend_mm_heap *phpdbg_original_heap_sigsafe_mem(void) {
48 	return PHPDBG_G(sigsafe_mem).old_heap;
49 }
50 
phpdbg_clear_sigsafe_mem(void)51 void phpdbg_clear_sigsafe_mem(void) {
52 	zend_mm_set_heap(phpdbg_original_heap_sigsafe_mem());
53 	PHPDBG_G(sigsafe_mem).mem = NULL;
54 }
55 
phpdbg_active_sigsafe_mem(void)56 zend_bool phpdbg_active_sigsafe_mem(void) {
57 	return !!PHPDBG_G(sigsafe_mem).mem;
58 }
59