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 pqsigsetmask() 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 pqsigsetmask(int mask)
158 {
159  int prevmask;
160 
161  prevmask = pg_signal_mask;
162  pg_signal_mask = mask;
163 
164  /*
165  * Dispatch any signals queued up right away, in case we have unblocked
166  * one or more signals previously queued
167  */
169 
170  return prevmask;
171 }
172 
173 
174 /*
175  * Unix-like signal handler installation
176  *
177  * Only called on main thread, no sync required
178  */
179 pqsigfunc
180 pqsignal(int signum, pqsigfunc handler)
181 {
182  pqsigfunc prevfunc;
183 
184  if (signum >= PG_SIGNAL_COUNT || signum < 0)
185  return SIG_ERR;
186  prevfunc = pg_signal_array[signum];
187  pg_signal_array[signum] = handler;
188  return prevfunc;
189 }
190 
191 /* Create the signal listener pipe for specified PID */
192 HANDLE
194 {
195  char pipename[128];
196  HANDLE pipe;
197 
198  snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%u", (int) pid);
199 
200  pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
201  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
202  PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
203 
204  if (pipe == INVALID_HANDLE_VALUE)
205  ereport(ERROR,
206  (errmsg("could not create signal listener pipe for PID %d: error code %lu",
207  (int) pid, GetLastError())));
208 
209  return pipe;
210 }
211 
212 
213 /*
214  * All functions below execute on the signal handler thread
215  * and must be synchronized as such!
216  * NOTE! The only global variable that can be used is
217  * pg_signal_queue!
218  */
219 
220 
221 /*
222  * Queue a signal for the main thread, by setting the flag bit and event.
223  */
224 void
225 pg_queue_signal(int signum)
226 {
227  Assert(pgwin32_signal_event != NULL);
228  if (signum >= PG_SIGNAL_COUNT || signum <= 0)
229  return; /* ignore any bad signal number */
230 
231  EnterCriticalSection(&pg_signal_crit_sec);
232  pg_signal_queue |= sigmask(signum);
233  LeaveCriticalSection(&pg_signal_crit_sec);
234 
235  SetEvent(pgwin32_signal_event);
236 }
237 
238 /* Signal handling thread */
239 static DWORD WINAPI
240 pg_signal_thread(LPVOID param)
241 {
242  char pipename[128];
243  HANDLE pipe = pgwin32_initial_signal_pipe;
244 
245  /* Set up pipe name, in case we have to re-create the pipe. */
246  snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%lu", GetCurrentProcessId());
247 
248  for (;;)
249  {
250  BOOL fConnected;
251 
252  /* Create a new pipe instance if we don't have one. */
253  if (pipe == INVALID_HANDLE_VALUE)
254  {
255  pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
256  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
257  PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
258 
259  if (pipe == INVALID_HANDLE_VALUE)
260  {
261  write_stderr("could not create signal listener pipe: error code %lu; retrying\n", GetLastError());
262  SleepEx(500, FALSE);
263  continue;
264  }
265  }
266 
267  /*
268  * Wait for a client to connect. If something connects before we
269  * reach here, we'll get back a "failure" with ERROR_PIPE_CONNECTED,
270  * which is actually a success (way to go, Microsoft).
271  */
272  fConnected = ConnectNamedPipe(pipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
273  if (fConnected)
274  {
275  /*
276  * We have a connection from a would-be signal sender. Process it.
277  */
278  BYTE sigNum;
279  DWORD bytes;
280 
281  if (ReadFile(pipe, &sigNum, 1, &bytes, NULL) &&
282  bytes == 1)
283  {
284  /*
285  * Queue the signal before responding to the client. In this
286  * way, it's guaranteed that once kill() has returned in the
287  * signal sender, the next CHECK_FOR_INTERRUPTS() in the
288  * signal recipient will see the signal. (This is a stronger
289  * guarantee than POSIX makes; maybe we don't need it? But
290  * without it, we've seen timing bugs on Windows that do not
291  * manifest on any known Unix.)
292  */
293  pg_queue_signal(sigNum);
294 
295  /*
296  * Write something back to the client, allowing its
297  * CallNamedPipe() call to terminate.
298  */
299  WriteFile(pipe, &sigNum, 1, &bytes, NULL); /* Don't care if it
300  * works or not */
301 
302  /*
303  * We must wait for the client to read the data before we can
304  * disconnect, else the data will be lost. (If the WriteFile
305  * call failed, there'll be nothing in the buffer, so this
306  * shouldn't block.)
307  */
308  FlushFileBuffers(pipe);
309  }
310  else
311  {
312  /*
313  * If we fail to read a byte from the client, assume it's the
314  * client's problem and do nothing. Perhaps it'd be better to
315  * force a pipe close and reopen?
316  */
317  }
318 
319  /* Disconnect from client so that we can re-use the pipe. */
320  DisconnectNamedPipe(pipe);
321  }
322  else
323  {
324  /*
325  * Connection failed. Cleanup and try again.
326  *
327  * This should never happen. If it does, there's a window where
328  * we'll miss signals until we manage to re-create the pipe.
329  * However, just trying to use the same pipe again is probably not
330  * going to work, so we have little choice.
331  */
332  CloseHandle(pipe);
333  pipe = INVALID_HANDLE_VALUE;
334  }
335  }
336  return 0;
337 }
338 
339 
340 /* Console control handler will execute on a thread created
341  by the OS at the time of invocation */
342 static BOOL WINAPI
343 pg_console_handler(DWORD dwCtrlType)
344 {
345  if (dwCtrlType == CTRL_C_EVENT ||
346  dwCtrlType == CTRL_BREAK_EVENT ||
347  dwCtrlType == CTRL_CLOSE_EVENT ||
348  dwCtrlType == CTRL_SHUTDOWN_EVENT)
349  {
350  pg_queue_signal(SIGINT);
351  return TRUE;
352  }
353  return FALSE;
354 }
#define write_stderr(str)
Definition: parallel.c:186
#define unlikely(x)
Definition: c.h:273
int errmsg_internal(const char *fmt,...)
Definition: elog.c:991
int errmsg(const char *fmt,...)
Definition: elog.c:904
#define FATAL
Definition: elog.h:35
#define ERROR
Definition: elog.h:33
#define ereport(elevel,...)
Definition: elog.h:143
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
static int sig
Definition: pg_ctl.c:84
#define snprintf
Definition: port.h:225
void(* pqsigfunc)(int signo)
Definition: port.h:535
HANDLE pgwin32_create_signal_listener(pid_t pid)
Definition: signal.c:193
static DWORD WINAPI pg_signal_thread(LPVOID param)
Definition: signal.c:240
void pg_queue_signal(int signum)
Definition: signal.c:225
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:343
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 pqsigsetmask(int mask)
Definition: signal.c:157
void pgwin32_signal_initialize(void)
Definition: signal.c:79
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:180
int pg_signal_mask
Definition: signal.c:25
#define UNBLOCKED_SIGNAL_QUEUE()
Definition: win32_port.h:455
#define SIG_DFL
Definition: win32_port.h:162
#define SIG_ERR
Definition: win32_port.h:163
#define EINTR
Definition: win32_port.h:351
#define sigmask(sig)
Definition: win32_port.h:156
#define SIG_IGN
Definition: win32_port.h:164
#define PG_SIGNAL_COUNT
Definition: win32_port.h:456