Assorted Win32 error handling fixes (CreateThread, pgwin32_select, pg_usleep)

From: Sehrope Sarkuni <sehrope(at)jackdb(dot)com>
To: Pg Hackers <pgsql-hackers(at)postgresql(dot)org>
Subject: Assorted Win32 error handling fixes (CreateThread, pgwin32_select, pg_usleep)
Date: 2026-06-10 17:45:55
Message-ID: CAH7T-apWWfEt+V8uLU7KXv7CMM9LoqJ1Zo2LdWmXMz=u-Ek9=w@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hi-

While trying out some new analysis tooling, I noticed a few small bugs
in error handling. Attached are four patches:

0001: CreateThread() returns NULL on failure[1], not
INVALID_HANDLE_VALUE, so the failure check in the win32 timer code
could never fire. A failed thread creation would silently disable all
timer-based timeouts rather than reporting FATAL.

0002: Same CreateThread() return value mixup in pg_test_fsync.

0003: The events array in pgwin32_select() is sized for 2*FD_SETSIZE
socket events, but the signal event is appended after the sockets. If
the read and write fd sets are completely disjoint and full, the
signal event is written one element past the end of the array. Fixed
by sizing the array as 2*FD_SETSIZE + 1.

0004: pg_usleep() on win32 only checks for WAIT_OBJECT_0 from
WaitForSingleObject()[2], so WAIT_FAILED is silently treated the same as
a timeout, i.e. an immediate return. A caller using pg_usleep() in a
retry loop would spin at full speed if the event handle were ever
bad. Changed to handle WAIT_OBJECT_0 and WAIT_TIMEOUT explicitly and
elog(FATAL) on anything else.

0004 deserves some eyeballs since it changes behavior on the
failure path rather than just fixing a dead check. The first three
are mechanical.

Passes all checks with the new GitHub Actions CI:
https://github.com/sehrope/postgres/actions/runs/27282715049

[1]:
https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-createthread#return-value
[2]:
https://learn.microsoft.com/en-us/windows/win32/api/synchapi/nf-synchapi-waitforsingleobject#return-value

Regards,
-- Sehrope Sarkuni
Founder & CEO | JackDB, Inc. | https://www.jackdb.com/

Attachment Content-Type Size
0001-Fix-CreateThread-failure-check-in-win32-timer-code.patch application/octet-stream 1.1 KB
0002-Fix-CreateThread-failure-check-in-pg_test_fsync.patch application/octet-stream 996 bytes
0003-Fix-off-by-one-in-pgwin32_select-event-array.patch application/octet-stream 1.3 KB
0004-Do-not-treat-a-failed-wait-as-a-timeout-in-win32-pg_.patch application/octet-stream 1.3 KB

Browse pgsql-hackers by date

  From Date Subject
Next Message Andres Freund 2026-06-10 18:03:37 Re: [PATCH v5] pg_stat_statements: Add last_execution_start column
Previous Message Pavlo Golub 2026-06-10 17:36:24 [PATCH v5] pg_stat_statements: Add last_execution_start column