PostgreSQL Source Code  git master
signal.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * signal.c
4  * Microsoft Windows Win32 Signal Emulation Functions
5  *
6  * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  * src/backend/port/win32/signal.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 
14 #include "postgres.h"
15 
16 #include "libpq/pqsignal.h"
17 
18 /*
19  * These are exported for use by the UNBLOCKED_SIGNAL_QUEUE() macro.
20  * pg_signal_queue must be volatile since it is changed by the signal
21  * handling thread and inspected without any lock by the main thread.
22  * pg_signal_mask is only changed by main thread so shouldn't need it.
23  */
24 volatile int pg_signal_queue;
26 
28 HANDLE pgwin32_initial_signal_pipe = INVALID_HANDLE_VALUE;
29 
30 /*
31  * pg_signal_crit_sec is used to protect only pg_signal_queue. That is the only
32  * variable that can be accessed from the signal sending threads!
33  */
34 static CRITICAL_SECTION pg_signal_crit_sec;
35 
36 /* Note that array elements 0 are unused since they correspond to signal 0 */
39 
40 
41 /* Signal handling thread functions */
42 static DWORD WINAPI pg_signal_thread(LPVOID param);
43 static BOOL WINAPI pg_console_handler(DWORD dwCtrlType);
44 
45 
46 /*
47  * pg_usleep --- delay the specified number of microseconds, but
48  * stop waiting if a signal arrives.
49  *
50  * This replaces the non-signal-aware version provided by src/port/pgsleep.c.
51  */
52 void
53 pg_usleep(long microsec)
54 {
55  if (unlikely(pgwin32_signal_event == NULL))
56  {
57  /*
58  * If we're reached by pgwin32_open_handle() early in startup before
59  * the signal event is set up, just fall back to a regular
60  * non-interruptible sleep.
61  */
62  SleepEx((microsec < 500 ? 1 : (microsec + 500) / 1000), FALSE);
63  return;
64  }
65 
66  if (WaitForSingleObject(pgwin32_signal_event,
67  (microsec < 500 ? 1 : (microsec + 500) / 1000))
68  == WAIT_OBJECT_0)
69  {
71  errno = EINTR;
72  return;
73  }
74 }
75 
76 
77 /* Initialization */
78 void
80 {
81  int i;
82  HANDLE signal_thread_handle;
83 
84  InitializeCriticalSection(&pg_signal_crit_sec);
85 
86  for (i = 0; i < PG_SIGNAL_COUNT; i++)
87  {
90  }
91  pg_signal_mask = 0;
92  pg_signal_queue = 0;
93 
94  /* Create the global event handle used to flag signals */
95  pgwin32_signal_event = CreateEvent(NULL, TRUE, FALSE, NULL);
96  if (pgwin32_signal_event == NULL)
97  ereport(FATAL,
98  (errmsg_internal("could not create signal event: error code %lu", GetLastError())));
99 
100  /* Create thread for handling signals */
101  signal_thread_handle = CreateThread(NULL, 0, pg_signal_thread, NULL, 0, NULL);
102  if (signal_thread_handle == NULL)
103  ereport(FATAL,
104  (errmsg_internal("could not create signal handler thread")));
105 
106  /* Create console control handle to pick up Ctrl-C etc */
107  if (!SetConsoleCtrlHandler(pg_console_handler, TRUE))
108  ereport(FATAL,
109  (errmsg_internal("could not set console control handler")));
110 }
111 
112 /*
113  * Dispatch all signals currently queued and not blocked
114  * Blocked signals are ignored, and will be fired at the time of
115  * the pqsigprocmask() call.
116  */
117 void
119 {
120  int exec_mask;
121 
122  Assert(pgwin32_signal_event != NULL);
123  EnterCriticalSection(&pg_signal_crit_sec);
124  while ((exec_mask = UNBLOCKED_SIGNAL_QUEUE()) != 0)
125  {
126  /* One or more unblocked signals queued for execution */
127  int i;
128 
129  for (i = 1; i < PG_SIGNAL_COUNT; i++)
130  {
131  if (exec_mask & sigmask(i))
132  {
133  /* Execute this signal */
135 
136  if (sig == SIG_DFL)
139  if (sig != SIG_ERR && sig != SIG_IGN && sig != SIG_DFL)
140  {
141  LeaveCriticalSection(&pg_signal_crit_sec);
142  sig(i);
143  EnterCriticalSection(&pg_signal_crit_sec);
144  break; /* Restart outer loop, in case signal mask or
145  * queue has been modified inside signal
146  * handler */
147  }
148  }
149  }
150  }
151  ResetEvent(pgwin32_signal_event);
152  LeaveCriticalSection(&pg_signal_crit_sec);
153 }
154 
155 /* signal masking. Only called on main thread, no sync required */
156 int
157 pqsigprocmask(int how, const sigset_t *set, sigset_t *oset)
158 {
159  if (oset)
160  *oset = pg_signal_mask;
161 
162  if (!set)
163  return 0;
164 
165  switch (how)
166  {
167  case SIG_BLOCK:
168  pg_signal_mask |= *set;
169  break;
170  case SIG_UNBLOCK:
171  pg_signal_mask &= ~*set;
172  break;
173  case SIG_SETMASK:
174  pg_signal_mask = *set;
175  break;
176  default:
177  errno = EINVAL;
178  return -1;
179  }
180 
181  /*
182  * Dispatch any signals queued up right away, in case we have unblocked
183  * one or more signals previously queued
184  */
186 
187  return 0;
188 }
189 
190 
191 /*
192  * Unix-like signal handler installation
193  *
194  * Only called on main thread, no sync required
195  */
196 pqsigfunc
197 pqsignal(int signum, pqsigfunc handler)
198 {
199  pqsigfunc prevfunc;
200 
201  if (signum >= PG_SIGNAL_COUNT || signum < 0)
202  return SIG_ERR;
203  prevfunc = pg_signal_array[signum];
204  pg_signal_array[signum] = handler;
205  return prevfunc;
206 }
207 
208 /* Create the signal listener pipe for specified PID */
209 HANDLE
211 {
212  char pipename[128];
213  HANDLE pipe;
214 
215  snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%u", (int) pid);
216 
217  pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
218  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
219  PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
220 
221  if (pipe == INVALID_HANDLE_VALUE)
222  ereport(ERROR,
223  (errmsg("could not create signal listener pipe for PID %d: error code %lu",
224  (int) pid, GetLastError())));
225 
226  return pipe;
227 }
228 
229 
230 /*
231  * All functions below execute on the signal handler thread
232  * and must be synchronized as such!
233  * NOTE! The only global variable that can be used is
234  * pg_signal_queue!
235  */
236 
237 
238 /*
239  * Queue a signal for the main thread, by setting the flag bit and event.
240  */
241 void
242 pg_queue_signal(int signum)
243 {
244  Assert(pgwin32_signal_event != NULL);
245  if (signum >= PG_SIGNAL_COUNT || signum <= 0)
246  return; /* ignore any bad signal number */
247 
248  EnterCriticalSection(&pg_signal_crit_sec);
249  pg_signal_queue |= sigmask(signum);
250  LeaveCriticalSection(&pg_signal_crit_sec);
251 
252  SetEvent(pgwin32_signal_event);
253 }
254 
255 /* Signal handling thread */
256 static DWORD WINAPI
257 pg_signal_thread(LPVOID param)
258 {
259  char pipename[128];
260  HANDLE pipe = pgwin32_initial_signal_pipe;
261 
262  /* Set up pipe name, in case we have to re-create the pipe. */
263  snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%lu", GetCurrentProcessId());
264 
265  for (;;)
266  {
267  BOOL fConnected;
268 
269  /* Create a new pipe instance if we don't have one. */
270  if (pipe == INVALID_HANDLE_VALUE)
271  {
272  pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
273  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
274  PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
275 
276  if (pipe == INVALID_HANDLE_VALUE)
277  {
278  write_stderr("could not create signal listener pipe: error code %lu; retrying\n", GetLastError());
279  SleepEx(500, FALSE);
280  continue;
281  }
282  }
283 
284  /*
285  * Wait for a client to connect. If something connects before we
286  * reach here, we'll get back a "failure" with ERROR_PIPE_CONNECTED,
287  * which is actually a success (way to go, Microsoft).
288  */
289  fConnected = ConnectNamedPipe(pipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
290  if (fConnected)
291  {
292  /*
293  * We have a connection from a would-be signal sender. Process it.
294  */
295  BYTE sigNum;
296  DWORD bytes;
297 
298  if (ReadFile(pipe, &sigNum, 1, &bytes, NULL) &&
299  bytes == 1)
300  {
301  /*
302  * Queue the signal before responding to the client. In this
303  * way, it's guaranteed that once kill() has returned in the
304  * signal sender, the next CHECK_FOR_INTERRUPTS() in the
305  * signal recipient will see the signal. (This is a stronger
306  * guarantee than POSIX makes; maybe we don't need it? But
307  * without it, we've seen timing bugs on Windows that do not
308  * manifest on any known Unix.)
309  */
310  pg_queue_signal(sigNum);
311 
312  /*
313  * Write something back to the client, allowing its
314  * CallNamedPipe() call to terminate.
315  */
316  WriteFile(pipe, &sigNum, 1, &bytes, NULL); /* Don't care if it
317  * works or not */
318 
319  /*
320  * We must wait for the client to read the data before we can
321  * disconnect, else the data will be lost. (If the WriteFile
322  * call failed, there'll be nothing in the buffer, so this
323  * shouldn't block.)
324  */
325  FlushFileBuffers(pipe);
326  }
327  else
328  {
329  /*
330  * If we fail to read a byte from the client, assume it's the
331  * client's problem and do nothing. Perhaps it'd be better to
332  * force a pipe close and reopen?
333  */
334  }
335 
336  /* Disconnect from client so that we can re-use the pipe. */
337  DisconnectNamedPipe(pipe);
338  }
339  else
340  {
341  /*
342  * Connection failed. Cleanup and try again.
343  *
344  * This should never happen. If it does, there's a window where
345  * we'll miss signals until we manage to re-create the pipe.
346  * However, just trying to use the same pipe again is probably not
347  * going to work, so we have little choice.
348  */
349  CloseHandle(pipe);
350  pipe = INVALID_HANDLE_VALUE;
351  }
352  }
353  return 0;
354 }
355 
356 
357 /* Console control handler will execute on a thread created
358  by the OS at the time of invocation */
359 static BOOL WINAPI
360 pg_console_handler(DWORD dwCtrlType)
361 {
362  if (dwCtrlType == CTRL_C_EVENT ||
363  dwCtrlType == CTRL_BREAK_EVENT ||
364  dwCtrlType == CTRL_CLOSE_EVENT ||
365  dwCtrlType == CTRL_SHUTDOWN_EVENT)
366  {
367  pg_queue_signal(SIGINT);
368  return TRUE;
369  }
370  return FALSE;
371 }
#define write_stderr(str)
Definition: parallel.c:184
#define unlikely(x)
Definition: c.h:295
int errmsg_internal(const char *fmt,...)
Definition: elog.c:993
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define FATAL
Definition: elog.h:37
#define ERROR
Definition: elog.h:35
#define ereport(elevel,...)
Definition: elog.h:145
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
static int sig
Definition: pg_ctl.c:82
void(* pqsigfunc)(SIGNAL_ARGS)
Definition: port.h:484
#define snprintf
Definition: port.h:234
HANDLE pgwin32_create_signal_listener(pid_t pid)
Definition: signal.c:210
static DWORD WINAPI pg_signal_thread(LPVOID param)
Definition: signal.c:257
void pg_queue_signal(int signum)
Definition: signal.c:242
void pg_usleep(long microsec)
Definition: signal.c:53
volatile int pg_signal_queue
Definition: signal.c:24
HANDLE pgwin32_initial_signal_pipe
Definition: signal.c:28
static pqsigfunc pg_signal_array[PG_SIGNAL_COUNT]
Definition: signal.c:37
static CRITICAL_SECTION pg_signal_crit_sec
Definition: signal.c:34
static BOOL WINAPI pg_console_handler(DWORD dwCtrlType)
Definition: signal.c:360
static pqsigfunc pg_signal_defaults[PG_SIGNAL_COUNT]
Definition: signal.c:38
void pgwin32_dispatch_queued_signals(void)
Definition: signal.c:118
HANDLE pgwin32_signal_event
Definition: signal.c:27
int pqsigprocmask(int how, const sigset_t *set, sigset_t *oset)
Definition: signal.c:157
void pgwin32_signal_initialize(void)
Definition: signal.c:79
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:197
int pg_signal_mask
Definition: signal.c:25
#define UNBLOCKED_SIGNAL_QUEUE()
Definition: win32_port.h:473
#define SIG_DFL
Definition: win32_port.h:171
#define SIG_ERR
Definition: win32_port.h:172
#define EINTR
Definition: win32_port.h:369
#define sigmask(sig)
Definition: win32_port.h:165
#define SIG_IGN
Definition: win32_port.h:173
#define PG_SIGNAL_COUNT
Definition: win32_port.h:474