Skip to content

Commit 6d1a854

Browse files
committed
Avoid calling gettext() in signal handlers.
It seems highly unlikely that gettext() can be relied on to be async-signal-safe. psql used to understand that, but someone got it wrong long ago in the src/bin/scripts/ version of handle_sigint, and then the bad idea was perpetuated when those two versions were unified into src/fe_utils/cancel.c. I'm unsure why there have not been field complaints about this ... maybe gettext() is signal-safe once it's translated at least one message? But we have no business assuming any such thing. In cancel.c (v13 and up), I preserved our ability to localize "Cancel request sent" messages by invoking gettext() before the signal handler is set up. In earlier branches I just made src/bin/scripts/ not localize those messages, as psql did then. (Just for extra unsafety, the src/bin/scripts/ version was invoking fprintf() from a signal handler. Sigh.) Noted while fixing signal-safety issues in PQcancel() itself. Back-patch to all supported branches. Discussion: https://postgr.es/m/2937814.1641960929@sss.pgh.pa.us
1 parent 38f099e commit 6d1a854

File tree

1 file changed

+23
-4
lines changed

1 file changed

+23
-4
lines changed

src/bin/scripts/common.c

Lines changed: 23 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,19 @@
2323
#include "fe_utils/string_utils.h"
2424

2525

26+
/*
27+
* Write a simple string to stderr --- must be safe in a signal handler.
28+
* We ignore the write() result since there's not much we could do about it.
29+
* Certain compilers make that harder than it ought to be.
30+
*/
31+
#define write_stderr(str) \
32+
do { \
33+
const char *str_ = (str); \
34+
int rc_; \
35+
rc_ = write(fileno(stderr), str_, strlen(str_)); \
36+
(void) rc_; \
37+
} while (0)
38+
2639
#define PQmblenBounded(s, e) strnlen(s, PQmblen(s, e))
2740

2841
static PGcancel *volatile cancelConn = NULL;
@@ -485,10 +498,13 @@ handle_sigint(SIGNAL_ARGS)
485498
if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
486499
{
487500
CancelRequested = true;
488-
fprintf(stderr, _("Cancel request sent\n"));
501+
write_stderr("Cancel request sent\n");
489502
}
490503
else
491-
fprintf(stderr, _("Could not send cancel request: %s"), errbuf);
504+
{
505+
write_stderr("Could not send cancel request: ");
506+
write_stderr(errbuf);
507+
}
492508
}
493509
else
494510
CancelRequested = true;
@@ -522,11 +538,14 @@ consoleHandler(DWORD dwCtrlType)
522538
{
523539
if (PQcancel(cancelConn, errbuf, sizeof(errbuf)))
524540
{
525-
fprintf(stderr, _("Cancel request sent\n"));
526541
CancelRequested = true;
542+
write_stderr("Cancel request sent\n");
527543
}
528544
else
529-
fprintf(stderr, _("Could not send cancel request: %s"), errbuf);
545+
{
546+
write_stderr("Could not send cancel request: ");
547+
write_stderr(errbuf);
548+
}
530549
}
531550
else
532551
CancelRequested = true;

0 commit comments

Comments
 (0)