Skip to content

Commit 370c00e

Browse files
committed
Add crude memory limit to tracked alloc
Check whether the requested allocation size exceeds limit (rather than the cumulative size). This is useful to prevent allocations triggering OOM during fuzzing.
1 parent fa4bdf1 commit 370c00e

File tree

1 file changed

+17
-1
lines changed

1 file changed

+17
-1
lines changed

Zend/zend_alloc.c

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2698,10 +2698,23 @@ ZEND_API void shutdown_memory_manager(int silent, int full_shutdown)
26982698
#if ZEND_MM_CUSTOM
26992699
static void *tracked_malloc(size_t size)
27002700
{
2701+
zend_mm_heap *heap = AG(mm_heap);
2702+
if (size > heap->limit) {
2703+
#if ZEND_DEBUG
2704+
zend_mm_safe_error(heap,
2705+
"Allowed memory size of %zu bytes exhausted at %s:%d (tried to allocate %zu bytes)",
2706+
heap->limit, "file", 0, size);
2707+
#else
2708+
zend_mm_safe_error(heap,
2709+
"Allowed memory size of %zu bytes exhausted (tried to allocate %zu bytes)",
2710+
heap->limit, size);
2711+
#endif
2712+
}
2713+
27012714
void *ptr = __zend_malloc(size);
27022715
zend_ulong h = ((uintptr_t) ptr) >> ZEND_MM_ALIGNMENT_LOG2;
27032716
ZEND_ASSERT((void *) (uintptr_t) (h << ZEND_MM_ALIGNMENT_LOG2) == ptr);
2704-
zend_hash_index_add_empty_element(AG(mm_heap)->tracked_allocs, h);
2717+
zend_hash_index_add_empty_element(heap->tracked_allocs, h);
27052718
return ptr;
27062719
}
27072720

@@ -2742,6 +2755,9 @@ static void alloc_globals_ctor(zend_alloc_globals *alloc_globals)
27422755
zend_mm_heap *mm_heap = alloc_globals->mm_heap = malloc(sizeof(zend_mm_heap));
27432756
memset(mm_heap, 0, sizeof(zend_mm_heap));
27442757
mm_heap->use_custom_heap = ZEND_MM_CUSTOM_HEAP_STD;
2758+
mm_heap->limit = ((size_t)Z_L(-1) >> (size_t)Z_L(1));
2759+
mm_heap->overflow = 0;
2760+
27452761
if (!tracked) {
27462762
/* Use system allocator. */
27472763
mm_heap->custom_heap.std._malloc = __zend_malloc;

0 commit comments

Comments
 (0)