nodepp icon indicating copy to clipboard operation
nodepp copied to clipboard

Two SIGSEGVs closing/tearing down ws_t sockets (Windows/IOCP) — with minimal repros

Open binaryduke opened this issue 4 months ago • 5 comments

Two separate, reproducible segfaults hit while building a WebSocket server on nodepp (Windows, MSVC 2022, C++20, x64 / IOCP backend). Both are in the same family as the io_uring shutdown corruption you fixed in V1.5.0_1, but neither is that bug — they're on the IOCP side and have different mechanisms.

Both were root-caused by elimination against minimal, 100%-reproducible repros (nodepp ws::server + one real localhost client — no network cost). Full logs below.


Bug 1 — process::exit() after a ws_t::write() segfaults

Symptom: a WS server that has written to at least one connected client segfaults on process::exit(). A server that only accepts clients exits cleanly.

Mechanism (our reading): ws_t::write() leaves the client socket with a persistent poll/task registration in the event loop's kernel — the same registration that keeps the socket's read loop alive across multiple writes. That's fine while the process runs. But process::exit() (nodepp/evloop.h) calls kernel_t::clear(), which unconditionally wipes the entire task queue — including that still-live registration — and then calls libc ::exit(). Tearing that registration out from under a socket that was actually written to is what crashes.

Proven by elimination, in this order:

  1. Connected client that never receives a write → exits cleanly, every time.
  2. Connected client that receives ≥1 write, then process::exit() → SIGSEGV, 100% of runs.
  3. Deferring where exit() is called from (flipping the loop's should_close flag and letting nodepp's own process::stop() call exit() later, from the top level rather than from inside a callback) → still crashes. So it is not "calling exit() while nested in callback dispatch" — the corruption is tied to the live write-registration itself, not to the call-stack depth.
  4. Waiting ~500ms (an extra timer tick) before exit(), to let any in-flight write complete → still crashes. So it is not pending I/O completion — the registration is persistent for the connection's lifetime, not a one-shot completion that reaps itself.
  5. Explicitly close()-ing every connected client's socket before process::exit() (which synchronously runs the normal onClose()/disconnect path and properly unregisters that task) → clean exit, repeatable.

Workaround we shipped: snapshot the client list, close() each one, then process::exit(). Note this isn't an _exit()-style hack — it makes the shutdown sequence correct (stop serving, actually disconnect, then tear down), which a WS server arguably should do anyway. But it shouldn't be required to avoid a crash.

This one matters in production: docker stop sends SIGTERM, so every graceful restart would crash without the workaround.


Bug 2 — closing a ws_t from inside its own onData handler segfaults

Symptom: calling close() on a socket synchronously from within that same socket's onData callback → SIGSEGV. Independent of Bug 1.

Repro: server + one real connected client that sends one message; server closes it from within its own onData.

What did NOT fix it: deferring by a single next-tick (timer::timeout(fn, 0)) — still crashes.

What DID prove safe: collecting the sockets to close into a batch snapshot, and closing them from an unrelated timer running several seconds later. Verified against a client that had both received a write and sent data itself.

This shape is common: any auth/validation flow wants to inspect the first message and reject the connection if it's wrong — i.e. close from within onData. That currently can't be done safely.


Context

Both are worked around in our code, so this isn't urgent for us — but they're real, they're reproducible, and Bug 2 in particular blocks an obvious and common pattern.

Happy to extract the minimal repros into standalone .cpp files if that would help.

binaryduke avatar Jul 12 '26 06:07 binaryduke

Bug 1

Thanks for the detailed report — and you're right, I hit the exact same bug recently on the signaling server for a P2P game I'm building.

io_uring and IOCP are very similar — different protocols, but the same philosophy. The real problem is that the kernel is very picky about memory. When you send an I/O request (read, write, recv, send, accept, etc.), you must provide a buffer. That buffer belongs to the kernel until the operation finishes. So when you close the program with SIGTERM, SIGINT, or exit(), the socket destructor runs and frees memory that still belongs to the kernel — and that's a segfault.

It's not Nodepp — it's the kernel.

I haven't seen this error on Linux (io_uring) since I reorganized the destructor in socket.h and file.h:

~NODE(){ if( fd == INVALID_SOCKET ){ return; }
//  ::shutdown( fd, SHUT_WR ); 
    ::close   ( fd /*----*/ );
    NODEPP_URING().free( pd );
}

Close the fd first — that invalidates any pending io_uring operations — then free the memory from user-space. Same idea on Windows (IOCP): close the handle first, then cancel pending operations.

~NODE(){ if( fd == INVALID_SOCKET ){ return; }
//  ::shutdown   ( fd , SD_RECEIVE ); 
    ::closesocket( fd /*--------*/ );
    CancelIoEx   ((HANDLE) fd, &ovr);
    CancelIoEx   ((HANDLE) fd, &ovw);
}

I also commented out shutdown() — it felt redundant to shut down the pipe and then close the connection. Two syscalls when one does the job. So I skipped it and close directly.

This has been fixed since V1.5.0, but I haven't tested on a real MSVC windows compiler, just ming + wine. Let me know if it still reproduces on your end.

EDBCREPO avatar Jul 13 '26 02:07 EDBCREPO

Bug 2

this is a known one. ( But Solved since V1.4.0 )

This was reported earlier in #26. The root cause was that close() internally forced a cleanup of the onData event while its own memory was still being used, which caused a use-after-free. I originally designed it that way (and still do in some places) to avoid circular dependencies.

The fix ended up being a flag on clear(): if the event is currently in use, it marks the internal state as kill, finishes processing the queue, and then releases the memory. There's a stress test for this specific scenario here.

The core logic looks like this:

void clear() const noexcept { 
    if( obj->state &  STATE::EV_STATE_USED )
      { obj->state |= STATE::EV_STATE_KILL; return; }  
        obj->state &=~STATE::EV_STATE_KILL;
    obj->que.clear();
}

//[...]

void emit( const A&... args ) const noexcept {
    if( empty() || is_paused() || is_used() ){ return; }

    obj->state |= STATE::EV_STATE_USED;
    auto x = obj->que.first();

    while( x != nullptr ){ obj->addr = x->next;

        bool val = x->data.emit( args... );
        if( obj->que.empty() ){ break ; }
        if( val == false ){ obj->que.erase(x); }

    x = obj->que.as( obj->addr ); }

        obj->state &=~ STATE::EV_STATE_USED;
    if( obj->state &   STATE::EV_STATE_KILL ){ clear(); }
}

This has been fixed since V1.4.0 (or at least it should be). To be sure, you can run this minimal repro:

#include <nodepp/nodepp.h>
#include <nodepp/event.h>

using namespace nodepp;

void onMain(){
    
    event_t<> ev;

    ev.on([=](){
        console::log( "before" );
        ev.clear(); ev.clear();
        console::log( "after" );
    });

    ev.emit();
}

If that compiles and runs without crashing, well, it must be a different bug. Let me know if it still reproduces on your end — I'm happy to dig deeper.

EDBCREPO avatar Jul 13 '26 02:07 EDBCREPO

Both verdicts, from a real MSVC 2022 / x64 / C++20 build. One of them is an apology.

Bug 2 (close() → use-after-free in the event queue) — FIXED. Your call was right.

Your event_t repro (the double ev.clear() inside its own handler) runs clean on MSVC:

before
after
survived emit() -- no use-after-free

And the real WebSocket shape — closing a ws_t from inside its own onData, which is the auth-reject pattern we hit it with — also survives on 1.4.0:

[server] onData: BAD_AUTH_TOKEN
[server] closed from inside onData -- survived the close() call
[server] still alive after close-from-onData -- exiting 0

The confusion was entirely ours. We had been building against a commit that became an orphan after your history rewrite — our local "V1.4.0" (e7b4408) is not your 1.4.0 (e9b1866). It carries only a partial version of the EV_STATE_USED / EV_STATE_KILL work (4 hits in event.h against 9 in the real tag), which is exactly why the bug kept reproducing for us and not for you.

On your actual 1.4.0 it is fixed. You said it was fixed since 1.4.0, and it was. Sorry for the runaround — and this is a good advertisement for the tags you've just cut in #35.

Bug 1 (SIGSEGV tearing down a ws_t) — WITHDRAWN. Unreproducible.

We can't give you a straight answer, and we'd rather say that than guess.

We offered to attach the original minimal repro and never did, and it's now gone. Reconstructing it from our own bug description, we cannot make Bug 1 fire again — not on 1.5.0, not on your real 1.4.0, and not even on the orphan tree where we originally hit it. Write-then-exit with a client still connected exits cleanly in every variant we tried: bare ws::server, layered http::server + ws::server, with and without client→server traffic, with and without the close-first workaround.

So either our reconstruction is missing a condition the original had, or the original diagnosis was wrong. Either way, we're not going to claim your CancelIoEx reorder fixed something we can no longer reproduce. If it resurfaces we'll reopen with the repro attached, properly this time.

Your explanation of the mechanism is worth keeping regardless — "the buffer belongs to the kernel until the operation finishes, so the destructor frees memory the kernel still owns" is exactly right, and closing the handle before cancelling is the correct ordering on IOCP as much as io_uring.

Feel free to close this one

Bug 2 is fixed, Bug 1 is withdrawn. Neither is what's actually blocking us now — that's #36, where 1.5.0 segfaults on MSVC the instant a WebSocket client connects. Reproduced with your own examples/15-WS.cpp + 16-WS-Client.cpp, unmodified, on a pristine checkout of the tag; 1.4.0 is clean with identical source.

We have a real Windows/MSVC box and you don't. Send us anything you want tested.

binaryduke avatar Jul 13 '26 06:07 binaryduke

Bug 1 (SIGSEGV tearing down a ws_t) — WITHDRAWN. Unreproducible.

I actually think I know exactly what happened here.

Remember I mentioned that <unistd.h> was used to detect thread support? well:

#if defined(_POSIX_THREADS) && _POSIX_THREADS>0 && NODEPP_ALLOW_THREADS==1
#define NODEPP_THREAD_SUPPORTED
#else
#define thread_local /*unused*/
#endif

Following the logic, by commenting out unistd.h, _POSIX_THREADS no longer gets detected, which causes Nodepp to disable thread_local. ( I do this because not all devices support it e.g., Arduino ). That's why I added #define thread_local /*unused*/ — so that when a device doesn't support it, the rest of the code doesn't break.

Even though there are 4 ports of Nodepp (nodepp-arduino, nodepp-esp32, nodepp-wasm, and nodepp-core), the code is exactly the same across all of them. Only sleep.h changes in the best case. Keeping it this way makes maintenance much easier for me — I just copy and paste across all ports, and the compiler handles the dirty work.

On your local build, you disabled <unistd.h>, which in turn disabled thread_local. If you also patched worker.h and mutex.h, then the error was most likely caused by a race condition.

Nodepp is single-threaded, shared-nothing:

namespace nodepp { 
inline uring_t& NODEPP_URING() {
thread_local static uring_t out; return out; }}

thread_local is extremely important to avoid sharing memory between threads — which is the cause of 99.99999% of memory errors in C/C++.

Just look at the websocket.cpp example:

void onMain() {
    worker::add( coroutine::add( COROUTINE(){
    coBegin ; server();
    process::wait(); coFinish }));

    worker::add( coroutine::add( COROUTINE(){
    coBegin ; client();
    process::wait(); coFinish }));
}

Technically, without thread_local, both workers are reading and writing to the same memory addresses. It's a time bomb waiting to explode.

EDBCREPO avatar Jul 15 '26 03:07 EDBCREPO

Resolved on our side — the teardown SIGSEGV is fixed; the second report we withdrew as not reproducible. Closing. Thanks.

binaryduke avatar Jul 15 '26 11:07 binaryduke