Skip to content

Commit 4a4ca20

Browse files
Goober5000claude
andcommitted
Fix crash when restarting mongoose server on Windows
mg_start() calls InitializeCriticalSection(&global_log_file_lock) on every invocation, but mg_stop() never calls DeleteCriticalSection. Re-initializing an already-initialized critical section is undefined behavior on Windows and corrupts the heap, causing the next allocation to throw an exception. Make the Win32 initialization (WSAStartup + InitializeCriticalSection) one-shot via a static flag, and remove the asymmetric WSACleanup from mg_stop so resources remain valid across mg_start/mg_stop cycles. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
1 parent cc26887 commit 4a4ca20

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

lib/mongoose/mongoose.c

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5046,9 +5046,9 @@ void mg_stop(struct mg_context *ctx) {
50465046
}
50475047
free_context(ctx);
50485048

5049-
#if defined(_WIN32) && !defined(__SYMBIAN32__)
5050-
(void) WSACleanup();
5051-
#endif // _WIN32
5049+
// Note: WSACleanup and DeleteCriticalSection are intentionally omitted here.
5050+
// The one-shot initialization in mg_start ensures these resources remain
5051+
// valid across multiple mg_start/mg_stop cycles within the same process.
50525052
}
50535053

50545054
struct mg_context *mg_start(mg_callback_t user_callback, void *user_data,
@@ -5058,9 +5058,15 @@ struct mg_context *mg_start(mg_callback_t user_callback, void *user_data,
50585058
int i;
50595059

50605060
#if defined(_WIN32) && !defined(__SYMBIAN32__)
5061-
WSADATA data;
5062-
WSAStartup(MAKEWORD(2,2), &data);
5063-
InitializeCriticalSection(&global_log_file_lock);
5061+
{
5062+
static int win32_initialized;
5063+
if (!win32_initialized) {
5064+
WSADATA data;
5065+
WSAStartup(MAKEWORD(2,2), &data);
5066+
InitializeCriticalSection(&global_log_file_lock);
5067+
win32_initialized = 1;
5068+
}
5069+
}
50645070
#endif // _WIN32
50655071

50665072
// Allocate context and initialize reasonable general case defaults.

0 commit comments

Comments
 (0)