Skip to content

servers: drop CRT and curlx calls from main_window_loop() (Windows) - #22045

Closed
vszakats wants to merge 3 commits into
curl:masterfrom
vszakats:t-whandlers
Closed

vszakats wants to merge 3 commits into
curl:masterfrom
vszakats:t-whandlers

Conversation

@vszakats vszakats added tests Windows Windows-specific labels Jun 16, 2026
@vszakats

vszakats commented Jun 16, 2026 •

Copy link
Copy Markdown
Member Author

Error: Process completed with exit code 2304. on first run:
https://github.com/curl/curl/actions/runs/27620281150/job/81667049505?pr=22045

and a broken fork/pipe, then hang:

7004191 [main] sh 9151 dofork: child -1 - forked process 7312 died unexpectedly, retry 0, exit code 0xC0000142, errno 11
sh: fork: retry: Resource temporarily unavailable

https://github.com/curl/curl/actions/runs/27620281150/job/81667049419?pr=22045

@vszakats
vszakats marked this pull request as draft June 16, 2026 13:22
@bagder

bagder commented Jul 27, 2026

Copy link
Copy Markdown
Member

Abandoned?

@vszakats vszakats changed the title servers: avoid unsafe calls in ctrl event, main wnd, wnd proc handlers (Windows) servers: avoid potentially unsafe calls in ctrl event, main wnd, wnd proc handlers (Windows) Jul 28, 2026
@vszakats
vszakats marked this pull request as ready for review July 28, 2026 20:59
@vszakats

vszakats commented Jul 28, 2026 •

Copy link
Copy Markdown
Member Author

@jay I'm not sure if this is just overkill/unnecessary or potentially fixing edge cases. 1
Your thoughts?

edit: re-reading my own assesment in the PR, I'd find it quite unlikely if CRT calls
would be unsafe in window handlers. Perhaps in the ctrl event handler, yes.

Footnotes

  1. for sure it's not fixing the 'broken pipe' issue seen in CI: https://github.com/curl/curl/pull/22045#issuecomment-4719207577 ↩

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR experiments with minimizing potentially unsafe logging/diagnostic calls inside Windows callback contexts in the test server utilities, replacing them with direct Win32 GetStdHandle() + WriteFile() output (and allowing opt-in restoration via DEBUG_WIN32_CALLBACKS).

Changes:

  • Add an opt-in DEBUG_WIN32_CALLBACKS toggle for restoring prior detailed logging in Windows callbacks.
  • Replace logmsg() / fprintf()-based logging in Windows CTRL handler, window proc, and message loop error paths with WriteFile() to stderr.
  • Reduce dependency on CRT/internal helper APIs in these callback paths.
Comments suppressed due to low confidence (5)

tests/server/util.c:476

  • WriteFile() expects a DWORD byte count; CURL_CSTRLEN() is size_t. Adding an explicit cast and ignoring the return value explicitly avoids potential conversion warnings in Windows builds.
    WriteFile(out, msgend, CURL_CSTRLEN(msgend), &dwWritten, NULL);

tests/server/util.c:514

  • WriteFile() expects a DWORD byte count; CURL_CSTRLEN() is size_t. Adding an explicit cast (and explicitly discarding the return value) helps avoid conversion warnings on Windows toolchains.
      WriteFile(GetStdHandle(STD_ERROR_HANDLE), str, CURL_CSTRLEN(str),
                             &dwWritten, NULL);

tests/server/util.c:547

  • WriteFile() expects a DWORD byte count; CURL_CSTRLEN() is size_t. Adding an explicit cast (and explicitly discarding the return value) helps avoid conversion warnings on Windows toolchains.
    WriteFile(GetStdHandle(STD_ERROR_HANDLE), str, CURL_CSTRLEN(str),
              &dwWritten, NULL);

tests/server/util.c:567

  • WriteFile() expects a DWORD byte count; CURL_CSTRLEN() is size_t. Adding an explicit cast (and explicitly discarding the return value) helps avoid conversion warnings on Windows toolchains.
    WriteFile(GetStdHandle(STD_ERROR_HANDLE), str, CURL_CSTRLEN(str),
              &dwWritten, NULL);

tests/server/util.c:582

  • WriteFile() expects a DWORD byte count; CURL_CSTRLEN() is size_t. Adding an explicit cast (and explicitly discarding the return value) helps avoid conversion warnings on Windows toolchains.
      WriteFile(GetStdHandle(STD_ERROR_HANDLE), str, CURL_CSTRLEN(str),
                             &dwWritten, NULL);

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread tests/server/util.c Resolved
Comment thread tests/server/util.c Resolved
@jay

jay commented Jul 29, 2026

Copy link
Copy Markdown
Member

but do you know that this actually fixes anything

@vszakats

vszakats commented Jul 29, 2026 •

Copy link
Copy Markdown
Member Author

but do you know that this actually fixes anything

I don't, I just have this long-term desire to fix potential non-correctness to sort out
any goblins in the test code. (every flaky Windows CI failure is a reminder to continue!)

Initially this was pointed out by an LLM, but hard facts that I could find, are sparse.
My feeling is that this is a fluke, except maybe for the ctrl handler.

@jay

jay commented Jul 29, 2026 •

Copy link
Copy Markdown
Member

the ctrl handler in windows runs in its own thread so as long as the functions called are thread safe it should be ok. I took a look at logmsg and nothing stands out, I don't see any use of global variables etc.

however... the way logmsg works where it opens and closes the logfile for every call does not seem good. opening a FILE for logfile at the start would make more sense, then windows closes it automatically when the program ends. currently though issue would be if logmsg in the handler thread can't open the logfile because it's already open in another thread.

generally with the tests a possible issue that could cause crashes in windows is if tool code is being tested and tool_stderr is not initialized yet so maybe some tool function writes to tool_stderr while it's still null? though tool_stderr does appear to be initialized at the start so I guess ok. tool_stderr starts off null because in windows technically stderr is a function iob_func(2) or something and so we can't assign that to tool_stderr at compile time.

@vszakats

Copy link
Copy Markdown
Member Author

the ctrl handler in windows runs in its own thread so as long as the functions called are thread safe it should be ok. I took a look at logmsg and nothing stands out, I don't see any use of global variables etc.

however... the way logmsg works where it opens and closes the logfile for every call does not seem good. opening a FILE for logfile at the start would make more sense, then windows closes it automatically when the program ends. currently though issue would be if logmsg in the handler thread can't open the logfile because it's already open in another thread.

Sensible point. This is fixed by this patch, but in general it'd be
nicer to open at startup, indeed. Needs to be checked if this'd
cause an unnecessary empty log file in cases. Closing the file
could be done in the already existing atexit() function
win32_cleanup(). Perhaps do this in a separate PR? It may
perhaps improve perf as well.

(In my understanding the logging within the handler doesn't serve
a critical role in running tests, it mostly seems to help debugging
the handler itself, hence my solution in this PR for this. The test
harness catches the output either way, and what we'll miss is the
runtime variables that'd need printf.)

Another concern of mine is that a relatively complex function such
as logmsg(), or a function that it calls, may accidentally get
updated in ways that makes it no longer fit for use in the handler.
There is no warning about this, and it happened in the past.

generally with the tests a possible issue that could cause crashes in windows is if tool code is being tested and tool_stderr is not initialized yet so maybe some tool function writes to tool_stderr while it's still null? though tool_stderr does appear to be initialized at the start so I guess ok. tool_stderr starts off null because in windows technically stderr is a function iob_func(2) or something and so we can't assign that to tool_stderr at compile time.

Maybe we could check this and somehow fail gracefully but visibly
in this case? It doesn't seem like an issue in practice, but hardening
it seems like a plus to me.

@jay

jay commented Jul 29, 2026

Copy link
Copy Markdown
Member

The only issue we know this solves though is the logmsg contention if it's called from multiple threads, and IMO that's more of a logmsg issue, it doesn't need a bypass of the function. Unless we know this PR solves an issue in correctness.. because I can't point to what's not correct or what this fixes (sans logmsg file contention).

Also, creating a zero length logfile I don't think would be a problem unless there are scripts that rely on the file existence for detection, not sure.

Another concern of mine is that a relatively complex function such
as logmsg(), or a function that it calls, may accidentally get
updated in ways that makes it no longer fit for use in the handler.

Yes is a point but I mean for posterity we could just add a comment that logmsg is run multi-threaded., really that seems to me to be the solution here rather than gate everything separately with the WriteFiles

generally with the tests a possible issue that could cause crashes in windows is if tool code is being tested [...]

Maybe we could check this and somehow fail gracefully but visibly
in this case? It doesn't seem like an issue in practice, but hardening
it seems like a plus to me.

Yeah I was being theoretical here I don't know it's an issue but I was thinking in general if we see a null dereference crash in Windows it could possibly be that. I wouldn't worry about it unless we start seeing that...

@vszakats

vszakats commented Jul 29, 2026 •

Copy link
Copy Markdown
Member Author

The only issue we know this solves though is the logmsg contention if it's called from multiple threads, and IMO that's more of a logmsg issue, it doesn't need a bypass of the function. Unless we know this PR solves an issue in correctness.. because I can't point to what's not correct or what this fixes (sans logmsg file contention).

Also, creating a zero length logfile I don't think would be a problem unless there are scripts that rely on the file existence for detection, not sure.

I'd also be guessing it's okay.

Another concern of mine is that a relatively complex function such
as logmsg(), or a function that it calls, may accidentally get
updated in ways that makes it no longer fit for use in the handler.

Yes is a point but I mean for posterity we could just add a comment that logmsg is run multi-threaded., really that seems to me to be the solution here rather than gate everything separately with the WriteFiles

I have doubts it helps in practice. It's super easy to overlook,
or not even see. Simple-looking functions can be complex in the
background. E.g. curlx_fopen() is doing encoding translation,
long-filename support, and have seen significant changes over
time. I don't think it's in anyone's mind that it may be called from
a ctrl handler. Other functions may also be (and are) overridden
the same way via PP. They call time functions, too. I also say this
because regressions happened (IIRC multiple times.) Given the
minimal added value it gives over static log entries in this particular
case, I'm not sure it's worth the risk and maintenance hassle.

@jay

jay commented Jul 31, 2026

Copy link
Copy Markdown
Member

It doesn't look like what I suggested earlier (to open the logfile at the beginning) would be simple because the signal handler exit_signal_handler opens and closes the logfile as well and only certain functions can be called in a signal handler. Also the server/first.c main() is just a wrapper around whatever server main and the serverlogfile name is not set until in each server's main and could be a default or --logfile user specified etc. All the test servers would need to be adjusted to open the logfile. So I don't like that anymore.

If you are concerned about calling logmsg multi-threaded like in the control handler or the window thread then you could call fprintf(stderr, ... . I see no reason why that would be unsafe. Windows ctrl handlers aren't like signal handlers in posix. The code that already uses fprintf(stderr should be fine with no reason for WriteFile.

For logmsg calls for example rather than all this:

#ifdef DEBUG_WIN32_CALLBACKS
      logmsg("main_window_proc: %u -> %d", uMsg, signum);
#else
      static const char str[] = "main_window_proc\n";
      DWORD dwWritten;
      WriteFile(GetStdHandle(STD_ERROR_HANDLE), str, CURL_CSTRLEN(str),
                             &dwWritten, NULL);
#endif

I suggest this:

fprintf(stderr, "main_window_proc: %u -> %d", uMsg, signum);

and a note in those functions not to call logmsg since those functions run in separate threads

@jay

jay commented Jul 31, 2026

Copy link
Copy Markdown
Member

I'm proposing #22454 to replace this. Basically it syncs logmsg in Windows, and that should take care of allowing logmsg to be called from multiple threads in Windows.

@vszakats

vszakats commented Jul 31, 2026 •

Copy link
Copy Markdown
Member Author

fprintf() looks fine to me. The critical section solution, I find overkill.
There is enough things to worry about IMO than introducing a new
concept, and critical sections / locks are never trivial IMO. Also, tests
are not multi-threaded, apart from these handlers, and using logmsg()
seems easily avoidable there, without losing anything important. Or am
I missing something?

edit: re fprintf(), it's not just that but the strerror retrieving stuff that
has a deeper call stack. But I think that's also something that's quite
unlikely to fail, and if it fails, the error string is not important, and we
can let it go.

@jay

jay commented Aug 1, 2026

Copy link
Copy Markdown
Member

The solution is simple and I disagree that it's overkill. logmsg has the advantage that it logs to the file, of course. fprintf is fine too.

vszakats added a commit that referenced this pull request Aug 6, 2026
…dd exit message

On Windows, the init code calls `SetConsoleCtrlHandler()`, and before
this patch also set handlers for all Unixy signals. Of these, `SIGBREAK`
(used on Windows-only), `SIGINT`, `SIGABRT` and `SIGTERM` were also
setting up a `SetConsoleCtrlHandler()`, in addition to the call made
directly. (The rest, `SIGHUP`, `SIGPIPE`, `SIGALRM` are either missing
the macros, or ignored by `signal()` on Windows.)

As per WINE sources, `SetConsolCtrlHandler(<h>, TRUE)` calls are
additive, which means the test server set up two console ctrl handlers.

Then the ctrl handler set directly (`ctrl_event_handler()`), was
triggering the other signal handler via `raise()`, for the 'initiate
exit' logic, which in turn triggered exiting a wait within `select_ws()`
and other loops. The Windows window handler also made use of the
`SIGTERM` event to initiate exit via `raise()` and the second signal
handler.

To simplify, de-duplicate the ctrl handlers by dropping `signal()` calls
and keeping the direct Win32 call with `ctrl_event_handler()` doing all
the signal handling on Windows. Break out the 'initiate exit' logic into
a function and call it from both Unix and Windows signal/ctrl/window
handlers. Also drop calling `raise()` on exit, because it's a no-op
without a `signal()` pair.

Also:
- drop logging the actual ctrl type number, replace with just logging
  whether we handled the event, in `ctrl_event_handler()`. To avoid
  using non-signal-safe functions (e.g. `fprintf()`) from the handler.
- also replace `logmsg()` with `WriteFile()` to prevent regressions.
  Ref: #22045
- replace `logmsg()` with `WriteFile()` in `main_window_proc()`.
- fix to forward ctrl handling to the OS in the rare case of failed
  `exit_event` initialization on startup. To swap a possible hang
  (within `WaitForMultipleObjectsEx()`) with an ungraceful shutdown.
- add support for an 'exit message' string, set by signal/ctrl handlers,
  and log it on app exit. To avoid the need to deal with logging within
  the handlers, yet have a static trace message about the event.
  Complementing the already logged signal number.
- drop stderr trace message from `exit_signal_handler()` in favor of an
  exit message. runtests triggers it frequantly, which added much noise
  to stderr. As a bonus, this also allows dropping the compiler warning
  suppression.
  Reported-by: Stefan Eissing
  Bug: #22487 (comment)
  Follow-up to 3aae64e #22507

Refs:
https://learn.microsoft.com/windows/console/setconsolectrlhandler
https://learn.microsoft.com/windows/console/registering-a-control-handler-function
https://learn.microsoft.com/cpp/c-runtime-library/reference/raise
https://learn.microsoft.com/cpp/c-runtime-library/reference/signal
https://gitlab.winehq.org/wine/wine/-/blob/wine-11.14/dlls/kernelbase/console.c#L1517-1526
https://github.com/huangqinjin/ucrt/blob/d6e817a4cc90f6f1fe54f8a0aa4af4fff0bb647d/misc/signal.cpp#L286-L348

Follow-up to fe28fcf 7dc8a98 0e05877 #5260

Closes #22487
@vszakats vszakats changed the title servers: avoid potentially unsafe calls in ctrl event, main wnd, wnd proc handlers (Windows) servers: drop CRT and internal calls from main_window_loop() (Windows) Aug 6, 2026
@vszakats

vszakats commented Aug 6, 2026 •

Copy link
Copy Markdown
Member Author

The solution is simple and I disagree that it's overkill. logmsg has the advantage that it logs to the file, of course. fprintf is fine too.

fprintf() isn't signal-safe (as it turns out). I reduced this PR to
the main window loop. The rest went through several iterations,
and now don't need/use anything complex in signal/wnd callbacks.

@vszakats vszakats changed the title servers: drop CRT and internal calls from main_window_loop() (Windows) servers: drop CRT and curlx calls from main_window_loop() (Windows) Aug 6, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 1 out of 1 changed files in this pull request and generated no new comments.

@vszakats vszakats closed this in 7db9947 Aug 6, 2026
@vszakats
vszakats deleted the t-whandlers branch August 6, 2026 14:06
vszakats added a commit that referenced this pull request Aug 11, 2026
curl already built like this in UWP mode; add a macro to allow building
regular Win32 targets too, meaning without the hidden GUI window, window
handler, and thus without support for shutting down `servers.exe`
gracefully. To test the server in CI as a plain console app and remove
one component/variable from the system, in an effort chasing flaky runs.

The graceful option was used by `taskkill` (without `-f`) in runtests,
and it has been disabled (in favor of always `-f` (forced) kill), in an
attempt to avoid taskkill hanging. Those resolved, but general CI
flakiness remained. We see `taskkill` invoked seldom per job, and in
most of these cases it doesn't find the PID requested. It means the
graceful option is not actually used since 2025-04, and rather rarely
before that. Also just today, the callback and main loop received a few
updates to avoid potentially unsafe calls and interaction with the ctrl
handler.

Not expecting anything breakthrough here. Also graceful shutdown
is a useful feature to cleanup properly and to be in sync with other
platforms.

Also: GHA/windows: enable in Windows CI jobs.

Ref: https://learn.microsoft.com/windows/console/registering-a-control-handler-function#listen-with-hidden-window-example

Follow-up to 7db9947 #22045
Follow-up to 9ea4881 #22487
Follow-up to b11e002 #22495
Follow-up to 208b877 #21039
Follow-up to f450f38 #19897
Follow-up to 2701ac6 #19421
Follow-up to 4e203f6 #17054

Closes #22496
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

tests Windows Windows-specific

Development

Successfully merging this pull request may close these issues.

4 participants