1 #include <stdio.h> 2 3 #include "test/jemalloc_test.h" 4 5 static_assert(JEMALLOC_INFALLIBLE_NEW == 1); 6 7 /* 8 * Verifies that, when jemalloc is built with --enable-cxx-infallible-new, 9 * throwing operator new on OOM aborts via safety_check_fail. The test hook 10 * intercepts the abort and asserts the size-bearing message prefix. 11 */ 12 bool fake_abort_called; 13 void 14 fake_abort(const char *message) { 15 const char *expected_start = "<jemalloc>: Allocation of size"; 16 if (strncmp(message, expected_start, strlen(expected_start)) != 0) { 17 abort(); 18 } 19 fake_abort_called = true; 20 } 21 22 static bool 23 own_operator_new(void) { 24 uint64_t before, after; 25 size_t sz = sizeof(before); 26 27 /* thread.allocated is always available, even w/o config_stats. */ 28 expect_d_eq(mallctl("thread.allocated", (void *)&before, &sz, NULL, 0), 29 0, "Unexpected mallctl failure reading stats"); 30 void *volatile ptr = ::operator new((size_t)8); 31 expect_ptr_not_null(ptr, "Unexpected allocation failure"); 32 expect_d_eq(mallctl("thread.allocated", (void *)&after, &sz, NULL, 0), 33 0, "Unexpected mallctl failure reading stats"); 34 35 return (after != before); 36 } 37 38 TEST_BEGIN(test_failing_alloc) { 39 test_hooks_safety_check_abort = &fake_abort; 40 41 /* 42 * Not owning operator new is only expected to happen on MinGW which 43 * does not support operator new / delete replacement. 44 */ 45 #ifdef _WIN32 46 test_skip_if(!own_operator_new()); 47 #else 48 expect_true(own_operator_new(), "No operator new overload"); 49 #endif 50 void *volatile ptr = (void *)1; 51 try { 52 /* Too big of an allocation to succeed. */ 53 ptr = ::operator new((size_t)-1); 54 } catch (...) { 55 abort(); 56 } 57 expect_ptr_null(ptr, "Allocation should have failed"); 58 expect_b_eq(fake_abort_called, true, "Abort hook not invoked"); 59 test_hooks_safety_check_abort = NULL; 60 } 61 TEST_END 62 63 int 64 main(void) { 65 return test(test_failing_alloc); 66 } 67