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-2019, 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 function */
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 {
56  if (WaitForSingleObject(pgwin32_signal_event,
57  (microsec < 500 ? 1 : (microsec + 500) / 1000))
58  == WAIT_OBJECT_0)
59  {
61  errno = EINTR;
62  return;
63  }
64 }
65 
66 
67 /* Initialization */
68 void
70 {
71  int i;
72  HANDLE signal_thread_handle;
73 
74  InitializeCriticalSection(&pg_signal_crit_sec);
75 
76  for (i = 0; i < PG_SIGNAL_COUNT; i++)
77  {
80  }
81  pg_signal_mask = 0;
82  pg_signal_queue = 0;
83 
84  /* Create the global event handle used to flag signals */
85  pgwin32_signal_event = CreateEvent(NULL, TRUE, FALSE, NULL);
86  if (pgwin32_signal_event == NULL)
87  ereport(FATAL,
88  (errmsg_internal("could not create signal event: error code %lu", GetLastError())));
89 
90  /* Create thread for handling signals */
91  signal_thread_handle = CreateThread(NULL, 0, pg_signal_thread, NULL, 0, NULL);
92  if (signal_thread_handle == NULL)
93  ereport(FATAL,
94  (errmsg_internal("could not create signal handler thread")));
95 
96  /* Create console control handle to pick up Ctrl-C etc */
97  if (!SetConsoleCtrlHandler(pg_console_handler, TRUE))
98  ereport(FATAL,
99  (errmsg_internal("could not set console control handler")));
100 }
101 
102 /*
103  * Dispatch all signals currently queued and not blocked
104  * Blocked signals are ignored, and will be fired at the time of
105  * the pqsigsetmask() call.
106  */
107 void
109 {
110  int exec_mask;
111 
112  Assert(pgwin32_signal_event != NULL);
113  EnterCriticalSection(&pg_signal_crit_sec);
114  while ((exec_mask = UNBLOCKED_SIGNAL_QUEUE()) != 0)
115  {
116  /* One or more unblocked signals queued for execution */
117  int i;
118 
119  for (i = 1; i < PG_SIGNAL_COUNT; i++)
120  {
121  if (exec_mask & sigmask(i))
122  {
123  /* Execute this signal */
125 
126  if (sig == SIG_DFL)
127  sig = pg_signal_defaults[i];
128  pg_signal_queue &= ~sigmask(i);
129  if (sig != SIG_ERR && sig != SIG_IGN && sig != SIG_DFL)
130  {
131  LeaveCriticalSection(&pg_signal_crit_sec);
132  sig(i);
133  EnterCriticalSection(&pg_signal_crit_sec);
134  break; /* Restart outer loop, in case signal mask or
135  * queue has been modified inside signal
136  * handler */
137  }
138  }
139  }
140  }
141  ResetEvent(pgwin32_signal_event);
142  LeaveCriticalSection(&pg_signal_crit_sec);
143 }
144 
145 /* signal masking. Only called on main thread, no sync required */
146 int
147 pqsigsetmask(int mask)
148 {
149  int prevmask;
150 
151  prevmask = pg_signal_mask;
152  pg_signal_mask = mask;
153 
154  /*
155  * Dispatch any signals queued up right away, in case we have unblocked
156  * one or more signals previously queued
157  */
159 
160  return prevmask;
161 }
162 
163 
164 /*
165  * Unix-like signal handler installation
166  *
167  * Only called on main thread, no sync required
168  */
169 pqsigfunc
170 pqsignal(int signum, pqsigfunc handler)
171 {
172  pqsigfunc prevfunc;
173 
174  if (signum >= PG_SIGNAL_COUNT || signum < 0)
175  return SIG_ERR;
176  prevfunc = pg_signal_array[signum];
177  pg_signal_array[signum] = handler;
178  return prevfunc;
179 }
180 
181 /* Create the signal listener pipe for specified PID */
182 HANDLE
184 {
185  char pipename[128];
186  HANDLE pipe;
187 
188  snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%u", (int) pid);
189 
190  pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
191  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
192  PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
193 
194  if (pipe == INVALID_HANDLE_VALUE)
195  ereport(ERROR,
196  (errmsg("could not create signal listener pipe for PID %d: error code %lu",
197  (int) pid, GetLastError())));
198 
199  return pipe;
200 }
201 
202 
203 /*
204  * All functions below execute on the signal handler thread
205  * and must be synchronized as such!
206  * NOTE! The only global variable that can be used is
207  * pg_signal_queue!
208  */
209 
210 
211 void
212 pg_queue_signal(int signum)
213 {
214  Assert(pgwin32_signal_event != NULL);
215  if (signum >= PG_SIGNAL_COUNT || signum <= 0)
216  return;
217 
218  EnterCriticalSection(&pg_signal_crit_sec);
219  pg_signal_queue |= sigmask(signum);
220  LeaveCriticalSection(&pg_signal_crit_sec);
221 
222  SetEvent(pgwin32_signal_event);
223 }
224 
225 /* Signal dispatching thread */
226 static DWORD WINAPI
228 {
229  HANDLE pipe = (HANDLE) param;
230  BYTE sigNum;
231  DWORD bytes;
232 
233  if (!ReadFile(pipe, &sigNum, 1, &bytes, NULL))
234  {
235  /* Client died before sending */
236  CloseHandle(pipe);
237  return 0;
238  }
239  if (bytes != 1)
240  {
241  /* Received <bytes> bytes over signal pipe (should be 1) */
242  CloseHandle(pipe);
243  return 0;
244  }
245  WriteFile(pipe, &sigNum, 1, &bytes, NULL); /* Don't care if it works or
246  * not.. */
247  FlushFileBuffers(pipe);
248  DisconnectNamedPipe(pipe);
249  CloseHandle(pipe);
250 
251  pg_queue_signal(sigNum);
252  return 0;
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  snprintf(pipename, sizeof(pipename), "\\\\.\\pipe\\pgsignal_%lu", GetCurrentProcessId());
263 
264  for (;;)
265  {
266  BOOL fConnected;
267  HANDLE hThread;
268 
269  if (pipe == INVALID_HANDLE_VALUE)
270  {
271  pipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
272  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
273  PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
274 
275  if (pipe == INVALID_HANDLE_VALUE)
276  {
277  write_stderr("could not create signal listener pipe: error code %lu; retrying\n", GetLastError());
278  SleepEx(500, FALSE);
279  continue;
280  }
281  }
282 
283  fConnected = ConnectNamedPipe(pipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
284  if (fConnected)
285  {
286  HANDLE newpipe;
287 
288  /*
289  * We have a connected pipe. Pass this off to a separate thread
290  * that will do the actual processing of the pipe.
291  *
292  * We must also create a new instance of the pipe *before* we
293  * start running the new thread. If we don't, there is a race
294  * condition whereby the dispatch thread might run CloseHandle()
295  * before we have created a new instance, thereby causing a small
296  * window of time where we will miss incoming requests.
297  */
298  newpipe = CreateNamedPipe(pipename, PIPE_ACCESS_DUPLEX,
299  PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
300  PIPE_UNLIMITED_INSTANCES, 16, 16, 1000, NULL);
301  if (newpipe == INVALID_HANDLE_VALUE)
302  {
303  /*
304  * This really should never fail. Just retry in case it does,
305  * even though we have a small race window in that case. There
306  * is nothing else we can do other than abort the whole
307  * process which will be even worse.
308  */
309  write_stderr("could not create signal listener pipe: error code %lu; retrying\n", GetLastError());
310 
311  /*
312  * Keep going so we at least dispatch this signal. Hopefully,
313  * the call will succeed when retried in the loop soon after.
314  */
315  }
316  hThread = CreateThread(NULL, 0,
317  (LPTHREAD_START_ROUTINE) pg_signal_dispatch_thread,
318  (LPVOID) pipe, 0, NULL);
319  if (hThread == INVALID_HANDLE_VALUE)
320  write_stderr("could not create signal dispatch thread: error code %lu\n",
321  GetLastError());
322  else
323  CloseHandle(hThread);
324 
325  /*
326  * Background thread is running with our instance of the pipe. So
327  * replace our reference with the newly created one and loop back
328  * up for another run.
329  */
330  pipe = newpipe;
331  }
332  else
333  {
334  /*
335  * Connection failed. Cleanup and try again.
336  *
337  * This should never happen. If it does, we have a small race
338  * condition until we loop up and re-create the pipe.
339  */
340  CloseHandle(pipe);
341  pipe = INVALID_HANDLE_VALUE;
342  }
343  }
344  return 0;
345 }
346 
347 
348 /* Console control handler will execute on a thread created
349  by the OS at the time of invocation */
350 static BOOL WINAPI
351 pg_console_handler(DWORD dwCtrlType)
352 {
353  if (dwCtrlType == CTRL_C_EVENT ||
354  dwCtrlType == CTRL_BREAK_EVENT ||
355  dwCtrlType == CTRL_CLOSE_EVENT ||
356  dwCtrlType == CTRL_SHUTDOWN_EVENT)
357  {
358  pg_queue_signal(SIGINT);
359  return TRUE;
360  }
361  return FALSE;
362 }
int pg_signal_mask
Definition: signal.c:25
#define TRUE
Definition: ecpglib.h:35
static BOOL WINAPI pg_console_handler(DWORD dwCtrlType)
Definition: signal.c:351
void pgwin32_signal_initialize(void)
Definition: signal.c:69
void(* pqsigfunc)(int signo)
Definition: port.h:522
int pqsigsetmask(int mask)
Definition: signal.c:147
#define FALSE
Definition: ecpglib.h:39
def bytes(source, encoding='ascii', errors='strict')
volatile int pg_signal_queue
Definition: signal.c:24
#define write_stderr(str)
Definition: parallel.c:182
#define SIG_ERR
Definition: win32_port.h:159
#define sigmask(sig)
Definition: win32_port.h:152
HANDLE pgwin32_initial_signal_pipe
Definition: signal.c:28
#define UNBLOCKED_SIGNAL_QUEUE()
Definition: win32_port.h:426
void pg_usleep(long microsec)
Definition: signal.c:53
HANDLE pgwin32_signal_event
Definition: signal.c:27
void pgwin32_dispatch_queued_signals(void)
Definition: signal.c:108
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static CRITICAL_SECTION pg_signal_crit_sec
Definition: signal.c:34
static DWORD WINAPI pg_signal_dispatch_thread(LPVOID param)
Definition: signal.c:227
#define ereport(elevel, rest)
Definition: elog.h:141
#define PG_SIGNAL_COUNT
Definition: win32_port.h:427
#define SIG_IGN
Definition: win32_port.h:160
static pqsigfunc pg_signal_defaults[PG_SIGNAL_COUNT]
Definition: signal.c:38
static int sig
Definition: pg_ctl.c:84
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
int errmsg_internal(const char *fmt,...)
Definition: elog.c:814
#define SIG_DFL
Definition: win32_port.h:158
#define Assert(condition)
Definition: c.h:732
void pg_queue_signal(int signum)
Definition: signal.c:212
static pqsigfunc pg_signal_array[PG_SIGNAL_COUNT]
Definition: signal.c:37
int errmsg(const char *fmt,...)
Definition: elog.c:784
int i
HANDLE pgwin32_create_signal_listener(pid_t pid)
Definition: signal.c:183
static DWORD WINAPI pg_signal_thread(LPVOID param)
Definition: signal.c:257
#define EINTR
Definition: win32_port.h:332
#define snprintf
Definition: port.h:192