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