import io p = r'C:\Users\locpham\SonicForgeStudio\native_bridge\src\gui_probe.cpp' s = io.open(p, encoding='utf-8', newline='').read() def crlf(x): return x.replace('\n', '\r\n') # 1) add includes + handler helpers after existing includes old_inc = crlf('#include ') new_inc = crlf('''#include #include #ifdef _WIN32 static void probe_invalid_param(const wchar_t* expr, const wchar_t* func, const wchar_t* file, unsigned int line, uintptr_t reserved) { printf("[probe] INVALID_PARAMETER expr=%ls func=%ls\\n", expr ? expr : L"null", func ? func : L"null"); fflush(stdout); } #endif''') assert s.count(old_inc) == 1 s = s.replace(old_inc, new_inc) # 2) pump_for: wrap body with SEH + param handler old_pf = crlf('''static void pump_for(int secs) { auto t0 = std::chrono::steady_clock::now(); while (std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count() < secs) { MSG msg; while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); } Sleep(5); } }''') new_pf = crlf('''static void pump_for(int secs) { #ifdef _WIN32 _set_invalid_parameter_handler(probe_invalid_param); #endif auto t0 = std::chrono::steady_clock::now(); while (std::chrono::duration_cast( std::chrono::steady_clock::now() - t0).count() < secs) { MSG msg; while (PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessageW(&msg); } Sleep(5); } }''') assert s.count(old_pf) == 1 s = s.replace(old_pf, new_pf) io.open(p, 'w', encoding='utf-8', newline='').write(s) print('patched')