From c46a87eea8ee6f631ee962886ae8338ebaba22fb Mon Sep 17 00:00:00 2001
From: Maxim Prokhorov <prokhorov.max@outlook.com>
Date: Wed, 16 Nov 2022 23:17:45 +0300
Subject: [PATCH] wip

---
 cores/esp8266/abi.cpp               | 52 -----------------------------
 cores/esp8266/core_esp8266_main.cpp | 11 ++++++
 2 files changed, 11 insertions(+), 52 deletions(-)

diff --git a/cores/esp8266/abi.cpp b/cores/esp8266/abi.cpp
index 72f3fb0a06..6b7ea3509a 100644
--- a/cores/esp8266/abi.cpp
+++ b/cores/esp8266/abi.cpp
@@ -24,61 +24,9 @@
 using __cxxabiv1::__guard;
 
 // Debugging helper, last allocation which returned NULL
-extern void *umm_last_fail_alloc_addr;
-extern int umm_last_fail_alloc_size;
-
 extern "C" void __cxa_pure_virtual(void) __attribute__ ((__noreturn__));
 extern "C" void __cxa_deleted_virtual(void) __attribute__ ((__noreturn__));
 
-
-#if !defined(__cpp_exceptions)
-
-// overwrite weak operators new/new[] definitions
-
-void* operator new(size_t size)
-{
-    void *ret = malloc(size);
-    if (0 != size && 0 == ret) {
-        umm_last_fail_alloc_addr = __builtin_return_address(0);
-        umm_last_fail_alloc_size = size;
-        __unhandled_exception(PSTR("OOM"));
-    }
-    return ret;
-}
-
-void* operator new[](size_t size)
-{
-    void *ret = malloc(size);
-    if (0 != size && 0 == ret) {
-        umm_last_fail_alloc_addr = __builtin_return_address(0);
-        umm_last_fail_alloc_size = size;
-        __unhandled_exception(PSTR("OOM"));
-    }
-    return ret;
-}
-
-void* operator new (size_t size, const std::nothrow_t&)
-{
-    void *ret = malloc(size);
-    if (0 != size && 0 == ret) {
-        umm_last_fail_alloc_addr = __builtin_return_address(0);
-        umm_last_fail_alloc_size = size;
-    }
-    return ret;
-}
-
-void* operator new[] (size_t size, const std::nothrow_t&)
-{
-    void *ret = malloc(size);
-    if (0 != size && 0 == ret) {
-        umm_last_fail_alloc_addr = __builtin_return_address(0);
-        umm_last_fail_alloc_size = size;
-    }
-    return ret;
-}
-
-#endif // !defined(__cpp_exceptions)
-
 void __cxa_pure_virtual(void)
 {
     panic();
diff --git a/cores/esp8266/core_esp8266_main.cpp b/cores/esp8266/core_esp8266_main.cpp
index cf6dd669f6..fc3f272f93 100644
--- a/cores/esp8266/core_esp8266_main.cpp
+++ b/cores/esp8266/core_esp8266_main.cpp
@@ -301,9 +301,20 @@ static void  __unhandled_exception_cpp()
 }
 }
 
+extern void *umm_last_fail_alloc_addr;
+extern int umm_last_fail_alloc_size;
+
+static void __new_handler() {
+    umm_last_fail_alloc_addr = __builtin_return_address(0);
+    umm_last_fail_alloc_size = 0;
+    std::set_new_handler(nullptr);
+    __unhandled_exception(PSTR("OOM"));
+}
+
 void init_done() {
     system_set_os_print(1);
     gdb_init();
+    std::set_new_handler(__new_handler);
     std::set_terminate(__unhandled_exception_cpp);
     do_global_ctors();
     esp_schedule();