1 /*--------------------------------------------------------------------
2  * Symbols referenced in this file:
3  * - ClientAuthInProgress
4  *--------------------------------------------------------------------
5  */
6 
7 /*-------------------------------------------------------------------------
8  *
9  * postmaster.c
10  *	  This program acts as a clearing house for requests to the
11  *	  POSTGRES system.  Frontend programs send a startup message
12  *	  to the Postmaster and the postmaster uses the info in the
13  *	  message to setup a backend process.
14  *
15  *	  The postmaster also manages system-wide operations such as
16  *	  startup and shutdown. The postmaster itself doesn't do those
17  *	  operations, mind you --- it just forks off a subprocess to do them
18  *	  at the right times.  It also takes care of resetting the system
19  *	  if a backend crashes.
20  *
21  *	  The postmaster process creates the shared memory and semaphore
22  *	  pools during startup, but as a rule does not touch them itself.
23  *	  In particular, it is not a member of the PGPROC array of backends
24  *	  and so it cannot participate in lock-manager operations.  Keeping
25  *	  the postmaster away from shared memory operations makes it simpler
26  *	  and more reliable.  The postmaster is almost always able to recover
27  *	  from crashes of individual backends by resetting shared memory;
28  *	  if it did much with shared memory then it would be prone to crashing
29  *	  along with the backends.
30  *
31  *	  When a request message is received, we now fork() immediately.
32  *	  The child process performs authentication of the request, and
33  *	  then becomes a backend if successful.  This allows the auth code
34  *	  to be written in a simple single-threaded style (as opposed to the
35  *	  crufty "poor man's multitasking" code that used to be needed).
36  *	  More importantly, it ensures that blockages in non-multithreaded
37  *	  libraries like SSL or PAM cannot cause denial of service to other
38  *	  clients.
39  *
40  *
41  * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
42  * Portions Copyright (c) 1994, Regents of the University of California
43  *
44  *
45  * IDENTIFICATION
46  *	  src/backend/postmaster/postmaster.c
47  *
48  * NOTES
49  *
50  * Initialization:
51  *		The Postmaster sets up shared memory data structures
52  *		for the backends.
53  *
54  * Synchronization:
55  *		The Postmaster shares memory with the backends but should avoid
56  *		touching shared memory, so as not to become stuck if a crashing
57  *		backend screws up locks or shared memory.  Likewise, the Postmaster
58  *		should never block on messages from frontend clients.
59  *
60  * Garbage Collection:
61  *		The Postmaster cleans up after backends if they have an emergency
62  *		exit and/or core dump.
63  *
64  * Error Reporting:
65  *		Use write_stderr() only for reporting "interactive" errors
66  *		(essentially, bogus arguments on the command line).  Once the
67  *		postmaster is launched, use ereport().
68  *
69  *-------------------------------------------------------------------------
70  */
71 
72 #include "postgres.h"
73 
74 #include <unistd.h>
75 #include <signal.h>
76 #include <time.h>
77 #include <sys/wait.h>
78 #include <ctype.h>
79 #include <sys/stat.h>
80 #include <sys/socket.h>
81 #include <fcntl.h>
82 #include <sys/param.h>
83 #include <netinet/in.h>
84 #include <arpa/inet.h>
85 #include <netdb.h>
86 #include <limits.h>
87 
88 #ifdef HAVE_SYS_SELECT_H
89 #include <sys/select.h>
90 #endif
91 
92 #ifdef USE_BONJOUR
93 #include <dns_sd.h>
94 #endif
95 
96 #ifdef USE_SYSTEMD
97 #include <systemd/sd-daemon.h>
98 #endif
99 
100 #ifdef HAVE_PTHREAD_IS_THREADED_NP
101 #include <pthread.h>
102 #endif
103 
104 #include "access/transam.h"
105 #include "access/xlog.h"
106 #include "bootstrap/bootstrap.h"
107 #include "catalog/pg_control.h"
108 #include "common/ip.h"
109 #include "lib/ilist.h"
110 #include "libpq/auth.h"
111 #include "libpq/libpq.h"
112 #include "libpq/pqformat.h"
113 #include "libpq/pqsignal.h"
114 #include "miscadmin.h"
115 #include "pg_getopt.h"
116 #include "pgstat.h"
117 #include "postmaster/autovacuum.h"
118 #include "postmaster/bgworker_internals.h"
119 #include "postmaster/fork_process.h"
120 #include "postmaster/pgarch.h"
121 #include "postmaster/postmaster.h"
122 #include "postmaster/syslogger.h"
123 #include "replication/logicallauncher.h"
124 #include "replication/walsender.h"
125 #include "storage/fd.h"
126 #include "storage/ipc.h"
127 #include "storage/pg_shmem.h"
128 #include "storage/pmsignal.h"
129 #include "storage/proc.h"
130 #include "tcop/tcopprot.h"
131 #include "utils/builtins.h"
132 #include "utils/datetime.h"
133 #include "utils/dynamic_loader.h"
134 #include "utils/memutils.h"
135 #include "utils/pidfile.h"
136 #include "utils/ps_status.h"
137 #include "utils/timeout.h"
138 #include "utils/varlena.h"
139 
140 #ifdef EXEC_BACKEND
141 #include "storage/spin.h"
142 #endif
143 
144 
145 /*
146  * Possible types of a backend. Beyond being the possible bkend_type values in
147  * struct bkend, these are OR-able request flag bits for SignalSomeChildren()
148  * and CountChildren().
149  */
150 #define BACKEND_TYPE_NORMAL		0x0001	/* normal backend */
151 #define BACKEND_TYPE_AUTOVAC	0x0002	/* autovacuum worker process */
152 #define BACKEND_TYPE_WALSND		0x0004	/* walsender process */
153 #define BACKEND_TYPE_BGWORKER	0x0008	/* bgworker process */
154 #define BACKEND_TYPE_ALL		0x000F	/* OR of all the above */
155 
156 /*
157  * List of active backends (or child processes anyway; we don't actually
158  * know whether a given child has become a backend or is still in the
159  * authorization phase).  This is used mainly to keep track of how many
160  * children we have and send them appropriate signals when necessary.
161  *
162  * "Special" children such as the startup, bgwriter and autovacuum launcher
163  * tasks are not in this list.  Autovacuum worker and walsender are in it.
164  * Also, "dead_end" children are in it: these are children launched just for
165  * the purpose of sending a friendly rejection message to a would-be client.
166  * We must track them because they are attached to shared memory, but we know
167  * they will never become live backends.  dead_end children are not assigned a
168  * PMChildSlot.
169  *
170  * Background workers are in this list, too.
171  */
172 typedef struct bkend
173 {
174 	pid_t		pid;			/* process id of backend */
175 	int32		cancel_key;		/* cancel key for cancels for this backend */
176 	int			child_slot;		/* PMChildSlot for this backend, if any */
177 
178 	/*
179 	 * Flavor of backend or auxiliary process.  Note that BACKEND_TYPE_WALSND
180 	 * backends initially announce themselves as BACKEND_TYPE_NORMAL, so if
181 	 * bkend_type is normal, you should check for a recent transition.
182 	 */
183 	int			bkend_type;
184 	bool		dead_end;		/* is it going to send an error and quit? */
185 	bool		bgworker_notify;	/* gets bgworker start/stop notifications */
186 	dlist_node	elem;			/* list link in BackendList */
187 } Backend;
188 
189 
190 
191 #ifdef EXEC_BACKEND
192 static Backend *ShmemBackendArray;
193 #endif
194 
195 
196 
197 
198 
199 /* The socket number we are listening for connections on */
200 
201 
202 /* The directory names for Unix socket(s) */
203 
204 
205 /* The TCP listen address(es) */
206 
207 
208 /*
209  * ReservedBackends is the number of backends reserved for superuser use.
210  * This number is taken out of the pool size given by MaxBackends so
211  * number of backend slots available to non-superusers is
212  * (MaxBackends - ReservedBackends).  Note what this really means is
213  * "if there are <= ReservedBackends connections available, only superusers
214  * can make new connections" --- pre-existing superuser connections don't
215  * count against the limit.
216  */
217 
218 
219 /* The socket(s) we're listening to. */
220 #define MAXLISTEN	64
221 
222 
223 /*
224  * Set by the -o option
225  */
226 
227 
228 /*
229  * These globals control the behavior of the postmaster in case some
230  * backend dumps core.  Normally, it kills all peers of the dead backend
231  * and reinitializes shared memory.  By specifying -s or -n, we can have
232  * the postmaster stop (rather than kill) peers and not reinitialize
233  * shared data structures.  (Reinit is currently dead code, though.)
234  */
235 
236 
237 
238 /* still more option variables */
239 
240 
241 
242 
243 
244 		/* for ps display and logging */
245 
246 
247 
248 
249 
250 
251 
252 /* PIDs of special child processes; 0 when not running */
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 /* Startup process's status */
264 typedef enum
265 {
266 	STARTUP_NOT_RUNNING,
267 	STARTUP_RUNNING,
268 	STARTUP_SIGNALED,			/* we sent it a SIGQUIT or SIGKILL */
269 	STARTUP_CRASHED
270 } StartupStatusEnum;
271 
272 
273 
274 /* Startup/shutdown state */
275 #define			NoShutdown		0
276 #define			SmartShutdown	1
277 #define			FastShutdown	2
278 #define			ImmediateShutdown	3
279 
280 
281 
282  /* T if recovering from backend crash */
283 
284 /*
285  * We use a simple state machine to control startup, shutdown, and
286  * crash recovery (which is rather like shutdown followed by startup).
287  *
288  * After doing all the postmaster initialization work, we enter PM_STARTUP
289  * state and the startup process is launched. The startup process begins by
290  * reading the control file and other preliminary initialization steps.
291  * In a normal startup, or after crash recovery, the startup process exits
292  * with exit code 0 and we switch to PM_RUN state.  However, archive recovery
293  * is handled specially since it takes much longer and we would like to support
294  * hot standby during archive recovery.
295  *
296  * When the startup process is ready to start archive recovery, it signals the
297  * postmaster, and we switch to PM_RECOVERY state. The background writer and
298  * checkpointer are launched, while the startup process continues applying WAL.
299  * If Hot Standby is enabled, then, after reaching a consistent point in WAL
300  * redo, startup process signals us again, and we switch to PM_HOT_STANDBY
301  * state and begin accepting connections to perform read-only queries.  When
302  * archive recovery is finished, the startup process exits with exit code 0
303  * and we switch to PM_RUN state.
304  *
305  * Normal child backends can only be launched when we are in PM_RUN or
306  * PM_HOT_STANDBY state.  (connsAllowed can also restrict launching.)
307  * In other states we handle connection requests by launching "dead_end"
308  * child processes, which will simply send the client an error message and
309  * quit.  (We track these in the BackendList so that we can know when they
310  * are all gone; this is important because they're still connected to shared
311  * memory, and would interfere with an attempt to destroy the shmem segment,
312  * possibly leading to SHMALL failure when we try to make a new one.)
313  * In PM_WAIT_DEAD_END state we are waiting for all the dead_end children
314  * to drain out of the system, and therefore stop accepting connection
315  * requests at all until the last existing child has quit (which hopefully
316  * will not be very long).
317  *
318  * Notice that this state variable does not distinguish *why* we entered
319  * states later than PM_RUN --- Shutdown and FatalError must be consulted
320  * to find that out.  FatalError is never true in PM_RECOVERY, PM_HOT_STANDBY,
321  * or PM_RUN states, nor in PM_SHUTDOWN states (because we don't enter those
322  * states when trying to recover from a crash).  It can be true in PM_STARTUP
323  * state, because we don't clear it until we've successfully started WAL redo.
324  */
325 typedef enum
326 {
327 	PM_INIT,					/* postmaster starting */
328 	PM_STARTUP,					/* waiting for startup subprocess */
329 	PM_RECOVERY,				/* in archive recovery mode */
330 	PM_HOT_STANDBY,				/* in hot standby mode */
331 	PM_RUN,						/* normal "database is alive" state */
332 	PM_STOP_BACKENDS,			/* need to stop remaining backends */
333 	PM_WAIT_BACKENDS,			/* waiting for live backends to exit */
334 	PM_SHUTDOWN,				/* waiting for checkpointer to do shutdown
335 								 * ckpt */
336 	PM_SHUTDOWN_2,				/* waiting for archiver and walsenders to
337 								 * finish */
338 	PM_WAIT_DEAD_END,			/* waiting for dead_end children to exit */
339 	PM_NO_CHILDREN				/* all important children have exited */
340 } PMState;
341 
342 
343 
344 /*
345  * While performing a "smart shutdown", we restrict new connections but stay
346  * in PM_RUN or PM_HOT_STANDBY state until all the client backends are gone.
347  * connsAllowed is a sub-state indicator showing the active restriction.
348  * It is of no interest unless pmState is PM_RUN or PM_HOT_STANDBY.
349  */
350 typedef enum
351 {
352 	ALLOW_ALL_CONNS,			/* normal not-shutting-down state */
353 	ALLOW_SUPERUSER_CONNS,		/* only superusers can connect */
354 	ALLOW_NO_CONNS				/* no new connections allowed, period */
355 } ConnsAllowedState;
356 
357 
358 
359 /* Start time of SIGKILL timeout during immediate shutdown or child crash */
360 /* Zero means timeout is not running */
361 
362 
363 /* Length of said timeout */
364 #define SIGKILL_CHILDREN_AFTER_SECS		5
365 
366 	/* T if we've reached PM_RUN */
367 
368 __thread bool		ClientAuthInProgress = false;
369 	/* T during new-client
370 											 * authentication */
371 
372 	/* stderr redirected for syslogger? */
373 
374 /* received START_AUTOVAC_LAUNCHER signal */
375 
376 
377 /* the launcher needs to be signalled to communicate some condition */
378 
379 
380 /* received START_WALRECEIVER signal */
381 
382 
383 /* set when there's a worker that needs to be started up */
384 
385 
386 
387 #ifndef HAVE_STRONG_RANDOM
388 /*
389  * State for assigning cancel keys.
390  * Also, the global MyCancelKey passes the cancel key assigned to a given
391  * backend from the postmaster to that backend (via fork).
392  */
393 static unsigned int random_seed = 0;
394 static struct timeval random_start_time;
395 #endif
396 
397 #ifdef USE_SSL
398 /* Set when and if SSL has been initialized properly */
399 static bool LoadedSSL = false;
400 #endif
401 
402 #ifdef USE_BONJOUR
403 static DNSServiceRef bonjour_sdref = NULL;
404 #endif
405 
406 /*
407  * postmaster.c - function prototypes
408  */
409 static void CloseServerPorts(int status, Datum arg);
410 static void unlink_external_pid_file(int status, Datum arg);
411 static void getInstallationPaths(const char *argv0);
412 static void checkDataDir(void);
413 static Port *ConnCreate(int serverFd);
414 static void ConnFree(Port *port);
415 static void reset_shared(int port);
416 static void SIGHUP_handler(SIGNAL_ARGS);
417 static void pmdie(SIGNAL_ARGS);
418 static void reaper(SIGNAL_ARGS);
419 static void sigusr1_handler(SIGNAL_ARGS);
420 static void process_startup_packet_die(SIGNAL_ARGS);
421 static void process_startup_packet_quickdie(SIGNAL_ARGS);
422 static void dummy_handler(SIGNAL_ARGS);
423 static void StartupPacketTimeoutHandler(void);
424 static void CleanupBackend(int pid, int exitstatus);
425 static bool CleanupBackgroundWorker(int pid, int exitstatus);
426 static void HandleChildCrash(int pid, int exitstatus, const char *procname);
427 static void LogChildExit(int lev, const char *procname,
428 			 int pid, int exitstatus);
429 static void PostmasterStateMachine(void);
430 static void BackendInitialize(Port *port);
431 static void BackendRun(Port *port) pg_attribute_noreturn();
432 static void ExitPostmaster(int status) pg_attribute_noreturn();
433 static int	ServerLoop(void);
434 static int	BackendStartup(Port *port);
435 static int	ProcessStartupPacket(Port *port, bool SSLdone);
436 static void SendNegotiateProtocolVersion(List *unrecognized_protocol_options);
437 static void processCancelRequest(Port *port, void *pkt);
438 static int	initMasks(fd_set *rmask);
439 static void report_fork_failure_to_client(Port *port, int errnum);
440 static CAC_state canAcceptConnections(int backend_type);
441 static bool RandomCancelKey(int32 *cancel_key);
442 static void signal_child(pid_t pid, int signal);
443 static bool SignalSomeChildren(int signal, int targets);
444 static void TerminateChildren(int signal);
445 
446 #define SignalChildren(sig)			   SignalSomeChildren(sig, BACKEND_TYPE_ALL)
447 
448 static int	CountChildren(int target);
449 static bool assign_backendlist_entry(RegisteredBgWorker *rw);
450 static void maybe_start_bgworkers(void);
451 static bool CreateOptsFile(int argc, char *argv[], char *fullprogname);
452 static pid_t StartChildProcess(AuxProcType type);
453 static void StartAutovacuumWorker(void);
454 static void MaybeStartWalReceiver(void);
455 static void InitPostmasterDeathWatchHandle(void);
456 
457 /*
458  * Archiver is allowed to start up at the current postmaster state?
459  *
460  * If WAL archiving is enabled always, we are allowed to start archiver
461  * even during recovery.
462  */
463 #define PgArchStartupAllowed()	\
464 	((XLogArchivingActive() && pmState == PM_RUN) ||	\
465 	 (XLogArchivingAlways() &&	\
466 	  (pmState == PM_RECOVERY || pmState == PM_HOT_STANDBY)))
467 
468 #ifdef EXEC_BACKEND
469 
470 #ifdef WIN32
471 #define WNOHANG 0				/* ignored, so any integer value will do */
472 
473 static pid_t waitpid(pid_t pid, int *exitstatus, int options);
474 static void WINAPI pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired);
475 
476 static HANDLE win32ChildQueue;
477 
478 typedef struct
479 {
480 	HANDLE		waitHandle;
481 	HANDLE		procHandle;
482 	DWORD		procId;
483 } win32_deadchild_waitinfo;
484 #endif							/* WIN32 */
485 
486 static pid_t backend_forkexec(Port *port);
487 static pid_t internal_forkexec(int argc, char *argv[], Port *port);
488 
489 /* Type for a socket that can be inherited to a client process */
490 #ifdef WIN32
491 typedef struct
492 {
493 	SOCKET		origsocket;		/* Original socket value, or PGINVALID_SOCKET
494 								 * if not a socket */
495 	WSAPROTOCOL_INFO wsainfo;
496 } InheritableSocket;
497 #else
498 typedef int InheritableSocket;
499 #endif
500 
501 /*
502  * Structure contains all variables passed to exec:ed backends
503  */
504 typedef struct
505 {
506 	Port		port;
507 	InheritableSocket portsocket;
508 	char		DataDir[MAXPGPATH];
509 	pgsocket	ListenSocket[MAXLISTEN];
510 	int32		MyCancelKey;
511 	int			MyPMChildSlot;
512 #ifndef WIN32
513 	unsigned long UsedShmemSegID;
514 #else
515 	void	   *ShmemProtectiveRegion;
516 	HANDLE		UsedShmemSegID;
517 #endif
518 	void	   *UsedShmemSegAddr;
519 	slock_t    *ShmemLock;
520 	VariableCache ShmemVariableCache;
521 	Backend    *ShmemBackendArray;
522 #ifndef HAVE_SPINLOCKS
523 	PGSemaphore *SpinlockSemaArray;
524 #endif
525 	int			NamedLWLockTrancheRequests;
526 	NamedLWLockTranche *NamedLWLockTrancheArray;
527 	LWLockPadded *MainLWLockArray;
528 	slock_t    *ProcStructLock;
529 	PROC_HDR   *ProcGlobal;
530 	PGPROC	   *AuxiliaryProcs;
531 	PGPROC	   *PreparedXactProcs;
532 	PMSignalData *PMSignalState;
533 	InheritableSocket pgStatSock;
534 	pid_t		PostmasterPid;
535 	TimestampTz PgStartTime;
536 	TimestampTz PgReloadTime;
537 	pg_time_t	first_syslogger_file_time;
538 	bool		redirection_done;
539 	bool		IsBinaryUpgrade;
540 	int			max_safe_fds;
541 	int			MaxBackends;
542 #ifdef WIN32
543 	HANDLE		PostmasterHandle;
544 	HANDLE		initial_signal_pipe;
545 	HANDLE		syslogPipe[2];
546 #else
547 	int			postmaster_alive_fds[2];
548 	int			syslogPipe[2];
549 #endif
550 	char		my_exec_path[MAXPGPATH];
551 	char		pkglib_path[MAXPGPATH];
552 	char		ExtraOptions[MAXPGPATH];
553 } BackendParameters;
554 
555 static void read_backend_variables(char *id, Port *port);
556 static void restore_backend_variables(BackendParameters *param, Port *port);
557 
558 #ifndef WIN32
559 static bool save_backend_variables(BackendParameters *param, Port *port);
560 #else
561 static bool save_backend_variables(BackendParameters *param, Port *port,
562 					   HANDLE childProcess, pid_t childPid);
563 #endif
564 
565 static void ShmemBackendArrayAdd(Backend *bn);
566 static void ShmemBackendArrayRemove(Backend *bn);
567 #endif							/* EXEC_BACKEND */
568 
569 #define StartupDataBase()		StartChildProcess(StartupProcess)
570 #define StartBackgroundWriter() StartChildProcess(BgWriterProcess)
571 #define StartCheckpointer()		StartChildProcess(CheckpointerProcess)
572 #define StartWalWriter()		StartChildProcess(WalWriterProcess)
573 #define StartWalReceiver()		StartChildProcess(WalReceiverProcess)
574 
575 /* Macros to check exit status of a child process */
576 #define EXIT_STATUS_0(st)  ((st) == 0)
577 #define EXIT_STATUS_1(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 1)
578 #define EXIT_STATUS_3(st)  (WIFEXITED(st) && WEXITSTATUS(st) == 3)
579 
580 #ifndef WIN32
581 /*
582  * File descriptors for pipe used to monitor if postmaster is alive.
583  * First is POSTMASTER_FD_WATCH, second is POSTMASTER_FD_OWN.
584  */
585 
586 #else
587 /* Process handle of postmaster used for the same purpose on Windows */
588 HANDLE		PostmasterHandle;
589 #endif
590 
591 /*
592  * Postmaster main entry point
593  */
594 #ifdef SIGXFSZ
595 #endif
596 #ifdef HAVE_INT_OPTRESET
597 #endif
598 #ifdef USE_SSL
599 #endif
600 #ifdef USE_BONJOUR
601 #endif
602 #ifdef HAVE_UNIX_SOCKETS
603 #endif
604 #ifdef WIN32
605 #endif
606 #ifdef EXEC_BACKEND
607 #endif
608 #ifdef HAVE_PTHREAD_IS_THREADED_NP
609 #endif
610 #ifndef HAVE_STRONG_RANDOM
611 #endif
612 
613 
614 /*
615  * on_proc_exit callback to close server's listen sockets
616  */
617 
618 
619 /*
620  * on_proc_exit callback to delete external_pid_file
621  */
622 
623 
624 
625 /*
626  * Compute and check the directory paths to files that are part of the
627  * installation (as deduced from the postgres executable's own location)
628  */
629 #ifdef EXEC_BACKEND
630 #endif
631 
632 
633 /*
634  * Validate the proposed data directory
635  */
636 #if !defined(WIN32) && !defined(__CYGWIN__)
637 #endif
638 #if !defined(WIN32) && !defined(__CYGWIN__)
639 #endif
640 
641 /*
642  * Determine how long should we let ServerLoop sleep.
643  *
644  * In normal conditions we wait at most one minute, to ensure that the other
645  * background tasks handled by ServerLoop get done even when no requests are
646  * arriving.  However, if there are background workers waiting to be started,
647  * we don't actually sleep so that they are quickly serviced.  Other exception
648  * cases are as shown in the code.
649  */
650 
651 
652 /*
653  * Main idle loop of postmaster
654  *
655  * NB: Needs to be called with signals blocked
656  */
657 #ifdef HAVE_PTHREAD_IS_THREADED_NP
658 #endif
659 
660 /*
661  * Initialise the masks for select() for the ports we are listening on.
662  * Return the number of sockets to listen on.
663  */
664 
665 
666 
667 /*
668  * Read a client's startup packet and do something according to it.
669  *
670  * Returns STATUS_OK or STATUS_ERROR, or might call ereport(FATAL) and
671  * not return at all.
672  *
673  * (Note that ereport(FATAL) stuff is sent to the client, so only use it
674  * if that's what you want.  Return STATUS_ERROR if you don't want to
675  * send anything to the client, which would typically be appropriate
676  * if we detect a communications failure.)
677  */
678 #ifdef USE_SSL
679 #else
680 #endif
681 #ifdef USE_SSL
682 #endif
683 
684 /*
685  * Send a NegotiateProtocolVersion to the client.  This lets the client know
686  * that they have requested a newer minor protocol version than we are able
687  * to speak.  We'll speak the highest version we know about; the client can,
688  * of course, abandon the connection if that's a problem.
689  *
690  * We also include in the response a list of protocol options we didn't
691  * understand.  This allows clients to include optional parameters that might
692  * be present either in newer protocol versions or third-party protocol
693  * extensions without fear of having to reconnect if those options are not
694  * understood, while at the same time making certain that the client is aware
695  * of which options were actually accepted.
696  */
697 
698 
699 /*
700  * The client has sent a cancel request packet, not a normal
701  * start-a-new-connection packet.  Perform the necessary processing.
702  * Nothing is sent back to the client.
703  */
704 #ifndef EXEC_BACKEND
705 #else
706 #endif
707 #ifndef EXEC_BACKEND
708 #else
709 #endif
710 
711 /*
712  * canAcceptConnections --- check to see if database state allows connections
713  * of the specified type.  backend_type can be BACKEND_TYPE_NORMAL,
714  * BACKEND_TYPE_AUTOVAC, or BACKEND_TYPE_BGWORKER.  (Note that we don't yet
715  * know whether a NORMAL connection might turn into a walsender.)
716  */
717 
718 
719 
720 /*
721  * ConnCreate -- create a local connection data structure
722  *
723  * Returns NULL on failure, other than out-of-memory which is fatal.
724  */
725 #ifndef EXEC_BACKEND
726 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
727 #endif
728 #endif
729 
730 
731 /*
732  * ConnFree -- free a local connection data structure
733  */
734 #ifdef USE_SSL
735 #endif
736 
737 
738 /*
739  * ClosePostmasterPorts -- close all the postmaster's open sockets
740  *
741  * This is called during child process startup to release file descriptors
742  * that are not needed by that child process.  The postmaster still has
743  * them open, of course.
744  *
745  * Note: we pass am_syslogger as a boolean because we don't want to set
746  * the global variable yet when this is called.
747  */
748 #ifndef WIN32
749 #endif
750 #ifndef WIN32
751 #else
752 #endif
753 #ifdef USE_BONJOUR
754 #endif
755 
756 
757 /*
758  * reset_shared -- reset shared memory and semaphores
759  */
760 
761 
762 
763 /*
764  * SIGHUP -- reread config files, and tell children to do same
765  */
766 #ifdef WIN32
767 #endif
768 #ifdef USE_SSL
769 #endif
770 #ifdef EXEC_BACKEND
771 #endif
772 #ifdef WIN32
773 #endif
774 
775 
776 /*
777  * pmdie -- signal handler for processing various postmaster signals.
778  */
779 #ifdef WIN32
780 #endif
781 #ifdef USE_SYSTEMD
782 #endif
783 #ifdef USE_SYSTEMD
784 #endif
785 #ifdef USE_SYSTEMD
786 #endif
787 #ifdef WIN32
788 #endif
789 
790 /*
791  * Reaper -- signal handler to cleanup after a child process dies.
792  */
793 #ifdef WIN32
794 #endif
795 #ifdef USE_SYSTEMD
796 #endif
797 #ifdef WIN32
798 #endif
799 
800 /*
801  * Scan the bgworkers list and see if the given PID (which has just stopped
802  * or crashed) is in it.  Handle its shutdown if so, and return true.  If not a
803  * bgworker, return false.
804  *
805  * This is heavily based on CleanupBackend.  One important difference is that
806  * we don't know yet that the dying process is a bgworker, so we must be silent
807  * until we're sure it is.
808  */
809 #ifdef WIN32
810 #endif
811 #ifdef EXEC_BACKEND
812 #endif
813 
814 /*
815  * CleanupBackend -- cleanup after terminated backend.
816  *
817  * Remove all local state associated with backend.
818  *
819  * If you change this, see also CleanupBackgroundWorker.
820  */
821 #ifdef WIN32
822 #endif
823 #ifdef EXEC_BACKEND
824 #endif
825 
826 /*
827  * HandleChildCrash -- cleanup after failed backend, bgwriter, checkpointer,
828  * walwriter, autovacuum, or background worker.
829  *
830  * The objectives here are to clean up our local state about the child
831  * process, and to signal all other remaining children to quickdie.
832  */
833 #ifdef EXEC_BACKEND
834 #endif
835 #ifdef EXEC_BACKEND
836 #endif
837 
838 /*
839  * Log the death of a child process.
840  */
841 #if defined(WIN32)
842 #else
843 #endif
844 
845 /*
846  * Advance the postmaster's state machine and take actions as appropriate
847  *
848  * This is common code for pmdie(), reaper() and sigusr1_handler(), which
849  * receive the signals that might mean we need to change state.
850  */
851 
852 
853 
854 /*
855  * Send a signal to a postmaster child process
856  *
857  * On systems that have setsid(), each child process sets itself up as a
858  * process group leader.  For signals that are generally interpreted in the
859  * appropriate fashion, we signal the entire process group not just the
860  * direct child process.  This allows us to, for example, SIGQUIT a blocked
861  * archive_recovery script, or SIGINT a script being run by a backend via
862  * system().
863  *
864  * There is a race condition for recently-forked children: they might not
865  * have executed setsid() yet.  So we signal the child directly as well as
866  * the group.  We assume such a child will handle the signal before trying
867  * to spawn any grandchild processes.  We also assume that signaling the
868  * child twice will not cause any problems.
869  */
870 #ifdef HAVE_SETSID
871 #endif
872 
873 /*
874  * Send a signal to the targeted children (but NOT special children;
875  * dead_end children are never signaled, either).
876  */
877 
878 
879 /*
880  * Send a termination signal to children.  This considers all of our children
881  * processes, except syslogger and dead_end backends.
882  */
883 
884 
885 /*
886  * BackendStartup -- start backend process
887  *
888  * returns: STATUS_ERROR if the fork failed, STATUS_OK otherwise.
889  *
890  * Note: if you change this code, also consider StartAutovacuumWorker.
891  */
892 #ifdef EXEC_BACKEND
893 #else							/* !EXEC_BACKEND */
894 #endif							/* EXEC_BACKEND */
895 #ifdef EXEC_BACKEND
896 #endif
897 
898 /*
899  * Try to report backend fork() failure to client before we close the
900  * connection.  Since we do not care to risk blocking the postmaster on
901  * this connection, we set the connection to non-blocking and try only once.
902  *
903  * This is grungy special-purpose code; we cannot use backend libpq since
904  * it's not up and running.
905  */
906 
907 
908 
909 /*
910  * BackendInitialize -- initialize an interactive (postmaster-child)
911  *				backend process, and collect the client's startup packet.
912  *
913  * returns: nothing.  Will not return at all if there's any failure.
914  *
915  * Note: this code does not depend on having any access to shared memory.
916  * In the EXEC_BACKEND case, we are physically attached to shared memory
917  * but have not yet set up most of our local pointers to shmem structures.
918  */
919 
920 
921 
922 /*
923  * BackendRun -- set up the backend's argument list and invoke PostgresMain()
924  *
925  * returns:
926  *		Shouldn't return at all.
927  *		If PostgresMain() fails, return status.
928  */
929 #ifndef HAVE_STRONG_RANDOM
930 #endif
931 
932 
933 #ifdef EXEC_BACKEND
934 
935 /*
936  * postmaster_forkexec -- fork and exec a postmaster subprocess
937  *
938  * The caller must have set up the argv array already, except for argv[2]
939  * which will be filled with the name of the temp variable file.
940  *
941  * Returns the child process PID, or -1 on fork failure (a suitable error
942  * message has been logged on failure).
943  *
944  * All uses of this routine will dispatch to SubPostmasterMain in the
945  * child process.
946  */
947 pid_t
948 postmaster_forkexec(int argc, char *argv[])
949 {
950 	Port		port;
951 
952 	/* This entry point passes dummy values for the Port variables */
953 	memset(&port, 0, sizeof(port));
954 	return internal_forkexec(argc, argv, &port);
955 }
956 
957 /*
958  * backend_forkexec -- fork/exec off a backend process
959  *
960  * Some operating systems (WIN32) don't have fork() so we have to simulate
961  * it by storing parameters that need to be passed to the child and
962  * then create a new child process.
963  *
964  * returns the pid of the fork/exec'd process, or -1 on failure
965  */
966 static pid_t
967 backend_forkexec(Port *port)
968 {
969 	char	   *av[4];
970 	int			ac = 0;
971 
972 	av[ac++] = "postgres";
973 	av[ac++] = "--forkbackend";
974 	av[ac++] = NULL;			/* filled in by internal_forkexec */
975 
976 	av[ac] = NULL;
977 	Assert(ac < lengthof(av));
978 
979 	return internal_forkexec(ac, av, port);
980 }
981 
982 #ifndef WIN32
983 
984 /*
985  * internal_forkexec non-win32 implementation
986  *
987  * - writes out backend variables to the parameter file
988  * - fork():s, and then exec():s the child process
989  */
990 static pid_t
991 internal_forkexec(int argc, char *argv[], Port *port)
992 {
993 	static unsigned long tmpBackendFileNum = 0;
994 	pid_t		pid;
995 	char		tmpfilename[MAXPGPATH];
996 	BackendParameters param;
997 	FILE	   *fp;
998 
999 	if (!save_backend_variables(&param, port))
1000 		return -1;				/* log made by save_backend_variables */
1001 
1002 	/* Calculate name for temp file */
1003 	snprintf(tmpfilename, MAXPGPATH, "%s/%s.backend_var.%d.%lu",
1004 			 PG_TEMP_FILES_DIR, PG_TEMP_FILE_PREFIX,
1005 			 MyProcPid, ++tmpBackendFileNum);
1006 
1007 	/* Open file */
1008 	fp = AllocateFile(tmpfilename, PG_BINARY_W);
1009 	if (!fp)
1010 	{
1011 		/*
1012 		 * As in OpenTemporaryFileInTablespace, try to make the temp-file
1013 		 * directory
1014 		 */
1015 		mkdir(PG_TEMP_FILES_DIR, S_IRWXU);
1016 
1017 		fp = AllocateFile(tmpfilename, PG_BINARY_W);
1018 		if (!fp)
1019 		{
1020 			ereport(LOG,
1021 					(errcode_for_file_access(),
1022 					 errmsg("could not create file \"%s\": %m",
1023 							tmpfilename)));
1024 			return -1;
1025 		}
1026 	}
1027 
1028 	if (fwrite(&param, sizeof(param), 1, fp) != 1)
1029 	{
1030 		ereport(LOG,
1031 				(errcode_for_file_access(),
1032 				 errmsg("could not write to file \"%s\": %m", tmpfilename)));
1033 		FreeFile(fp);
1034 		return -1;
1035 	}
1036 
1037 	/* Release file */
1038 	if (FreeFile(fp))
1039 	{
1040 		ereport(LOG,
1041 				(errcode_for_file_access(),
1042 				 errmsg("could not write to file \"%s\": %m", tmpfilename)));
1043 		return -1;
1044 	}
1045 
1046 	/* Make sure caller set up argv properly */
1047 	Assert(argc >= 3);
1048 	Assert(argv[argc] == NULL);
1049 	Assert(strncmp(argv[1], "--fork", 6) == 0);
1050 	Assert(argv[2] == NULL);
1051 
1052 	/* Insert temp file name after --fork argument */
1053 	argv[2] = tmpfilename;
1054 
1055 	/* Fire off execv in child */
1056 	if ((pid = fork_process()) == 0)
1057 	{
1058 		if (execv(postgres_exec_path, argv) < 0)
1059 		{
1060 			ereport(LOG,
1061 					(errmsg("could not execute server process \"%s\": %m",
1062 							postgres_exec_path)));
1063 			/* We're already in the child process here, can't return */
1064 			exit(1);
1065 		}
1066 	}
1067 
1068 	return pid;					/* Parent returns pid, or -1 on fork failure */
1069 }
1070 #else							/* WIN32 */
1071 
1072 /*
1073  * internal_forkexec win32 implementation
1074  *
1075  * - starts backend using CreateProcess(), in suspended state
1076  * - writes out backend variables to the parameter file
1077  *	- during this, duplicates handles and sockets required for
1078  *	  inheritance into the new process
1079  * - resumes execution of the new process once the backend parameter
1080  *	 file is complete.
1081  */
1082 static pid_t
1083 internal_forkexec(int argc, char *argv[], Port *port)
1084 {
1085 	int			retry_count = 0;
1086 	STARTUPINFO si;
1087 	PROCESS_INFORMATION pi;
1088 	int			i;
1089 	int			j;
1090 	char		cmdLine[MAXPGPATH * 2];
1091 	HANDLE		paramHandle;
1092 	BackendParameters *param;
1093 	SECURITY_ATTRIBUTES sa;
1094 	char		paramHandleStr[32];
1095 	win32_deadchild_waitinfo *childinfo;
1096 
1097 	/* Make sure caller set up argv properly */
1098 	Assert(argc >= 3);
1099 	Assert(argv[argc] == NULL);
1100 	Assert(strncmp(argv[1], "--fork", 6) == 0);
1101 	Assert(argv[2] == NULL);
1102 
1103 	/* Resume here if we need to retry */
1104 retry:
1105 
1106 	/* Set up shared memory for parameter passing */
1107 	ZeroMemory(&sa, sizeof(sa));
1108 	sa.nLength = sizeof(sa);
1109 	sa.bInheritHandle = TRUE;
1110 	paramHandle = CreateFileMapping(INVALID_HANDLE_VALUE,
1111 									&sa,
1112 									PAGE_READWRITE,
1113 									0,
1114 									sizeof(BackendParameters),
1115 									NULL);
1116 	if (paramHandle == INVALID_HANDLE_VALUE)
1117 	{
1118 		elog(LOG, "could not create backend parameter file mapping: error code %lu",
1119 			 GetLastError());
1120 		return -1;
1121 	}
1122 
1123 	param = MapViewOfFile(paramHandle, FILE_MAP_WRITE, 0, 0, sizeof(BackendParameters));
1124 	if (!param)
1125 	{
1126 		elog(LOG, "could not map backend parameter memory: error code %lu",
1127 			 GetLastError());
1128 		CloseHandle(paramHandle);
1129 		return -1;
1130 	}
1131 
1132 	/* Insert temp file name after --fork argument */
1133 #ifdef _WIN64
1134 	sprintf(paramHandleStr, "%llu", (LONG_PTR) paramHandle);
1135 #else
1136 	sprintf(paramHandleStr, "%lu", (DWORD) paramHandle);
1137 #endif
1138 	argv[2] = paramHandleStr;
1139 
1140 	/* Format the cmd line */
1141 	cmdLine[sizeof(cmdLine) - 1] = '\0';
1142 	cmdLine[sizeof(cmdLine) - 2] = '\0';
1143 	snprintf(cmdLine, sizeof(cmdLine) - 1, "\"%s\"", postgres_exec_path);
1144 	i = 0;
1145 	while (argv[++i] != NULL)
1146 	{
1147 		j = strlen(cmdLine);
1148 		snprintf(cmdLine + j, sizeof(cmdLine) - 1 - j, " \"%s\"", argv[i]);
1149 	}
1150 	if (cmdLine[sizeof(cmdLine) - 2] != '\0')
1151 	{
1152 		elog(LOG, "subprocess command line too long");
1153 		return -1;
1154 	}
1155 
1156 	memset(&pi, 0, sizeof(pi));
1157 	memset(&si, 0, sizeof(si));
1158 	si.cb = sizeof(si);
1159 
1160 	/*
1161 	 * Create the subprocess in a suspended state. This will be resumed later,
1162 	 * once we have written out the parameter file.
1163 	 */
1164 	if (!CreateProcess(NULL, cmdLine, NULL, NULL, TRUE, CREATE_SUSPENDED,
1165 					   NULL, NULL, &si, &pi))
1166 	{
1167 		elog(LOG, "CreateProcess call failed: %m (error code %lu)",
1168 			 GetLastError());
1169 		return -1;
1170 	}
1171 
1172 	if (!save_backend_variables(param, port, pi.hProcess, pi.dwProcessId))
1173 	{
1174 		/*
1175 		 * log made by save_backend_variables, but we have to clean up the
1176 		 * mess with the half-started process
1177 		 */
1178 		if (!TerminateProcess(pi.hProcess, 255))
1179 			ereport(LOG,
1180 					(errmsg_internal("could not terminate unstarted process: error code %lu",
1181 									 GetLastError())));
1182 		CloseHandle(pi.hProcess);
1183 		CloseHandle(pi.hThread);
1184 		return -1;				/* log made by save_backend_variables */
1185 	}
1186 
1187 	/* Drop the parameter shared memory that is now inherited to the backend */
1188 	if (!UnmapViewOfFile(param))
1189 		elog(LOG, "could not unmap view of backend parameter file: error code %lu",
1190 			 GetLastError());
1191 	if (!CloseHandle(paramHandle))
1192 		elog(LOG, "could not close handle to backend parameter file: error code %lu",
1193 			 GetLastError());
1194 
1195 	/*
1196 	 * Reserve the memory region used by our main shared memory segment before
1197 	 * we resume the child process.  Normally this should succeed, but if ASLR
1198 	 * is active then it might sometimes fail due to the stack or heap having
1199 	 * gotten mapped into that range.  In that case, just terminate the
1200 	 * process and retry.
1201 	 */
1202 	if (!pgwin32_ReserveSharedMemoryRegion(pi.hProcess))
1203 	{
1204 		/* pgwin32_ReserveSharedMemoryRegion already made a log entry */
1205 		if (!TerminateProcess(pi.hProcess, 255))
1206 			ereport(LOG,
1207 					(errmsg_internal("could not terminate process that failed to reserve memory: error code %lu",
1208 									 GetLastError())));
1209 		CloseHandle(pi.hProcess);
1210 		CloseHandle(pi.hThread);
1211 		if (++retry_count < 100)
1212 			goto retry;
1213 		ereport(LOG,
1214 				(errmsg("giving up after too many tries to reserve shared memory"),
1215 				 errhint("This might be caused by ASLR or antivirus software.")));
1216 		return -1;
1217 	}
1218 
1219 	/*
1220 	 * Now that the backend variables are written out, we start the child
1221 	 * thread so it can start initializing while we set up the rest of the
1222 	 * parent state.
1223 	 */
1224 	if (ResumeThread(pi.hThread) == -1)
1225 	{
1226 		if (!TerminateProcess(pi.hProcess, 255))
1227 		{
1228 			ereport(LOG,
1229 					(errmsg_internal("could not terminate unstartable process: error code %lu",
1230 									 GetLastError())));
1231 			CloseHandle(pi.hProcess);
1232 			CloseHandle(pi.hThread);
1233 			return -1;
1234 		}
1235 		CloseHandle(pi.hProcess);
1236 		CloseHandle(pi.hThread);
1237 		ereport(LOG,
1238 				(errmsg_internal("could not resume thread of unstarted process: error code %lu",
1239 								 GetLastError())));
1240 		return -1;
1241 	}
1242 
1243 	/*
1244 	 * Queue a waiter for to signal when this child dies. The wait will be
1245 	 * handled automatically by an operating system thread pool.
1246 	 *
1247 	 * Note: use malloc instead of palloc, since it needs to be thread-safe.
1248 	 * Struct will be free():d from the callback function that runs on a
1249 	 * different thread.
1250 	 */
1251 	childinfo = malloc(sizeof(win32_deadchild_waitinfo));
1252 	if (!childinfo)
1253 		ereport(FATAL,
1254 				(errcode(ERRCODE_OUT_OF_MEMORY),
1255 				 errmsg("out of memory")));
1256 
1257 	childinfo->procHandle = pi.hProcess;
1258 	childinfo->procId = pi.dwProcessId;
1259 
1260 	if (!RegisterWaitForSingleObject(&childinfo->waitHandle,
1261 									 pi.hProcess,
1262 									 pgwin32_deadchild_callback,
1263 									 childinfo,
1264 									 INFINITE,
1265 									 WT_EXECUTEONLYONCE | WT_EXECUTEINWAITTHREAD))
1266 		ereport(FATAL,
1267 				(errmsg_internal("could not register process for wait: error code %lu",
1268 								 GetLastError())));
1269 
1270 	/* Don't close pi.hProcess here - the wait thread needs access to it */
1271 
1272 	CloseHandle(pi.hThread);
1273 
1274 	return pi.dwProcessId;
1275 }
1276 #endif							/* WIN32 */
1277 
1278 
1279 /*
1280  * SubPostmasterMain -- Get the fork/exec'd process into a state equivalent
1281  *			to what it would be if we'd simply forked on Unix, and then
1282  *			dispatch to the appropriate place.
1283  *
1284  * The first two command line arguments are expected to be "--forkFOO"
1285  * (where FOO indicates which postmaster child we are to become), and
1286  * the name of a variables file that we can read to load data that would
1287  * have been inherited by fork() on Unix.  Remaining arguments go to the
1288  * subprocess FooMain() routine.
1289  */
1290 void
1291 SubPostmasterMain(int argc, char *argv[])
1292 {
1293 	Port		port;
1294 
1295 	/* In EXEC_BACKEND case we will not have inherited these settings */
1296 	IsPostmasterEnvironment = true;
1297 	whereToSendOutput = DestNone;
1298 
1299 	/* Setup as postmaster child */
1300 	InitPostmasterChild();
1301 
1302 	/* Setup essential subsystems (to ensure elog() behaves sanely) */
1303 	InitializeGUCOptions();
1304 
1305 	/* Check we got appropriate args */
1306 	if (argc < 3)
1307 		elog(FATAL, "invalid subpostmaster invocation");
1308 
1309 	/* Read in the variables file */
1310 	memset(&port, 0, sizeof(Port));
1311 	read_backend_variables(argv[2], &port);
1312 
1313 	/* Close the postmaster's sockets (as soon as we know them) */
1314 	ClosePostmasterPorts(strcmp(argv[1], "--forklog") == 0);
1315 
1316 	/*
1317 	 * Set reference point for stack-depth checking
1318 	 */
1319 	set_stack_base();
1320 
1321 	/*
1322 	 * Set up memory area for GSS information. Mirrors the code in ConnCreate
1323 	 * for the non-exec case.
1324 	 */
1325 #if defined(ENABLE_GSS) || defined(ENABLE_SSPI)
1326 	port.gss = (pg_gssinfo *) calloc(1, sizeof(pg_gssinfo));
1327 	if (!port.gss)
1328 		ereport(FATAL,
1329 				(errcode(ERRCODE_OUT_OF_MEMORY),
1330 				 errmsg("out of memory")));
1331 #endif
1332 
1333 	/*
1334 	 * If appropriate, physically re-attach to shared memory segment. We want
1335 	 * to do this before going any further to ensure that we can attach at the
1336 	 * same address the postmaster used.  On the other hand, if we choose not
1337 	 * to re-attach, we may have other cleanup to do.
1338 	 *
1339 	 * If testing EXEC_BACKEND on Linux, you should run this as root before
1340 	 * starting the postmaster:
1341 	 *
1342 	 * echo 0 >/proc/sys/kernel/randomize_va_space
1343 	 *
1344 	 * This prevents using randomized stack and code addresses that cause the
1345 	 * child process's memory map to be different from the parent's, making it
1346 	 * sometimes impossible to attach to shared memory at the desired address.
1347 	 * Return the setting to its old value (usually '1' or '2') when finished.
1348 	 */
1349 	if (strcmp(argv[1], "--forkbackend") == 0 ||
1350 		strcmp(argv[1], "--forkavlauncher") == 0 ||
1351 		strcmp(argv[1], "--forkavworker") == 0 ||
1352 		strcmp(argv[1], "--forkboot") == 0 ||
1353 		strncmp(argv[1], "--forkbgworker=", 15) == 0)
1354 		PGSharedMemoryReAttach();
1355 	else
1356 		PGSharedMemoryNoReAttach();
1357 
1358 	/* autovacuum needs this set before calling InitProcess */
1359 	if (strcmp(argv[1], "--forkavlauncher") == 0)
1360 		AutovacuumLauncherIAm();
1361 	if (strcmp(argv[1], "--forkavworker") == 0)
1362 		AutovacuumWorkerIAm();
1363 
1364 	/*
1365 	 * Start our win32 signal implementation. This has to be done after we
1366 	 * read the backend variables, because we need to pick up the signal pipe
1367 	 * from the parent process.
1368 	 */
1369 #ifdef WIN32
1370 	pgwin32_signal_initialize();
1371 #endif
1372 
1373 	/* In EXEC_BACKEND case we will not have inherited these settings */
1374 	pqinitmask();
1375 	PG_SETMASK(&BlockSig);
1376 
1377 	/* Read in remaining GUC variables */
1378 	read_nondefault_variables();
1379 
1380 	/*
1381 	 * Reload any libraries that were preloaded by the postmaster.  Since we
1382 	 * exec'd this process, those libraries didn't come along with us; but we
1383 	 * should load them into all child processes to be consistent with the
1384 	 * non-EXEC_BACKEND behavior.
1385 	 */
1386 	process_shared_preload_libraries();
1387 
1388 	/* Run backend or appropriate child */
1389 	if (strcmp(argv[1], "--forkbackend") == 0)
1390 	{
1391 		Assert(argc == 3);		/* shouldn't be any more args */
1392 
1393 		/*
1394 		 * Need to reinitialize the SSL library in the backend, since the
1395 		 * context structures contain function pointers and cannot be passed
1396 		 * through the parameter file.
1397 		 *
1398 		 * If for some reason reload fails (maybe the user installed broken
1399 		 * key files), soldier on without SSL; that's better than all
1400 		 * connections becoming impossible.
1401 		 *
1402 		 * XXX should we do this in all child processes?  For the moment it's
1403 		 * enough to do it in backend children.
1404 		 */
1405 #ifdef USE_SSL
1406 		if (EnableSSL)
1407 		{
1408 			if (secure_initialize(false) == 0)
1409 				LoadedSSL = true;
1410 			else
1411 				ereport(LOG,
1412 						(errmsg("SSL configuration could not be loaded in child process")));
1413 		}
1414 #endif
1415 
1416 		/*
1417 		 * Perform additional initialization and collect startup packet.
1418 		 *
1419 		 * We want to do this before InitProcess() for a couple of reasons: 1.
1420 		 * so that we aren't eating up a PGPROC slot while waiting on the
1421 		 * client. 2. so that if InitProcess() fails due to being out of
1422 		 * PGPROC slots, we have already initialized libpq and are able to
1423 		 * report the error to the client.
1424 		 */
1425 		BackendInitialize(&port);
1426 
1427 		/* Restore basic shared memory pointers */
1428 		InitShmemAccess(UsedShmemSegAddr);
1429 
1430 		/* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1431 		InitProcess();
1432 
1433 		/* Attach process to shared data structures */
1434 		CreateSharedMemoryAndSemaphores(0);
1435 
1436 		/* And run the backend */
1437 		BackendRun(&port);		/* does not return */
1438 	}
1439 	if (strcmp(argv[1], "--forkboot") == 0)
1440 	{
1441 		/* Restore basic shared memory pointers */
1442 		InitShmemAccess(UsedShmemSegAddr);
1443 
1444 		/* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1445 		InitAuxiliaryProcess();
1446 
1447 		/* Attach process to shared data structures */
1448 		CreateSharedMemoryAndSemaphores(0);
1449 
1450 		AuxiliaryProcessMain(argc - 2, argv + 2);	/* does not return */
1451 	}
1452 	if (strcmp(argv[1], "--forkavlauncher") == 0)
1453 	{
1454 		/* Restore basic shared memory pointers */
1455 		InitShmemAccess(UsedShmemSegAddr);
1456 
1457 		/* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1458 		InitProcess();
1459 
1460 		/* Attach process to shared data structures */
1461 		CreateSharedMemoryAndSemaphores(0);
1462 
1463 		AutoVacLauncherMain(argc - 2, argv + 2);	/* does not return */
1464 	}
1465 	if (strcmp(argv[1], "--forkavworker") == 0)
1466 	{
1467 		/* Restore basic shared memory pointers */
1468 		InitShmemAccess(UsedShmemSegAddr);
1469 
1470 		/* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1471 		InitProcess();
1472 
1473 		/* Attach process to shared data structures */
1474 		CreateSharedMemoryAndSemaphores(0);
1475 
1476 		AutoVacWorkerMain(argc - 2, argv + 2);	/* does not return */
1477 	}
1478 	if (strncmp(argv[1], "--forkbgworker=", 15) == 0)
1479 	{
1480 		int			shmem_slot;
1481 
1482 		/* do this as early as possible; in particular, before InitProcess() */
1483 		IsBackgroundWorker = true;
1484 
1485 		/* Restore basic shared memory pointers */
1486 		InitShmemAccess(UsedShmemSegAddr);
1487 
1488 		/* Need a PGPROC to run CreateSharedMemoryAndSemaphores */
1489 		InitProcess();
1490 
1491 		/* Attach process to shared data structures */
1492 		CreateSharedMemoryAndSemaphores(0);
1493 
1494 		/* Fetch MyBgworkerEntry from shared memory */
1495 		shmem_slot = atoi(argv[1] + 15);
1496 		MyBgworkerEntry = BackgroundWorkerEntry(shmem_slot);
1497 
1498 		StartBackgroundWorker();
1499 	}
1500 	if (strcmp(argv[1], "--forkarch") == 0)
1501 	{
1502 		/* Do not want to attach to shared memory */
1503 
1504 		PgArchiverMain(argc, argv); /* does not return */
1505 	}
1506 	if (strcmp(argv[1], "--forkcol") == 0)
1507 	{
1508 		/* Do not want to attach to shared memory */
1509 
1510 		PgstatCollectorMain(argc, argv);	/* does not return */
1511 	}
1512 	if (strcmp(argv[1], "--forklog") == 0)
1513 	{
1514 		/* Do not want to attach to shared memory */
1515 
1516 		SysLoggerMain(argc, argv);	/* does not return */
1517 	}
1518 
1519 	abort();					/* shouldn't get here */
1520 }
1521 #endif							/* EXEC_BACKEND */
1522 
1523 
1524 /*
1525  * ExitPostmaster -- cleanup
1526  *
1527  * Do NOT call exit() directly --- always go through here!
1528  */
1529 #ifdef HAVE_PTHREAD_IS_THREADED_NP
1530 #endif
1531 
1532 /*
1533  * sigusr1_handler - handle signal conditions from child processes
1534  */
1535 #ifdef WIN32
1536 #endif
1537 #ifdef USE_SYSTEMD
1538 #endif
1539 #ifdef USE_SYSTEMD
1540 #endif
1541 #ifdef WIN32
1542 #endif
1543 
1544 /*
1545  * SIGTERM while processing startup packet.
1546  * Clean up and exit(1).
1547  *
1548  * Running proc_exit() from a signal handler is pretty unsafe, since we
1549  * can't know what code we've interrupted.  But the alternative of using
1550  * _exit(2) is also unpalatable, since it'd mean that a "fast shutdown"
1551  * would cause a database crash cycle (forcing WAL replay at restart)
1552  * if any sessions are in authentication.  So we live with it for now.
1553  *
1554  * One might be tempted to try to send a message indicating why we are
1555  * disconnecting.  However, that would make this even more unsafe.  Also,
1556  * it seems undesirable to provide clues about the database's state to
1557  * a client that has not yet completed authentication.
1558  */
1559 
1560 
1561 /*
1562  * SIGQUIT while processing startup packet.
1563  *
1564  * Some backend has bought the farm,
1565  * so we need to stop what we're doing and exit.
1566  */
1567 
1568 
1569 /*
1570  * Dummy signal handler
1571  *
1572  * We use this for signals that we don't actually use in the postmaster,
1573  * but we do use in backends.  If we were to SIG_IGN such signals in the
1574  * postmaster, then a newly started backend might drop a signal that arrives
1575  * before it's able to reconfigure its signal processing.  (See notes in
1576  * tcop/postgres.c.)
1577  */
1578 
1579 
1580 /*
1581  * Timeout while processing startup packet.
1582  * As for process_startup_packet_die(), we clean up and exit(1).
1583  *
1584  * This is theoretically just as hazardous as in process_startup_packet_die(),
1585  * although in practice we're almost certainly waiting for client input,
1586  * which greatly reduces the risk.
1587  */
1588 
1589 
1590 
1591 /*
1592  * Generate a random cancel key.
1593  */
1594 #ifdef HAVE_STRONG_RANDOM
1595 #else
1596 #endif
1597 
1598 /*
1599  * Count up number of child processes of specified types (dead_end children
1600  * are always excluded).
1601  */
1602 
1603 
1604 
1605 /*
1606  * StartChildProcess -- start an auxiliary process for the postmaster
1607  *
1608  * "type" determines what kind of child will be started.  All child types
1609  * initially go to AuxiliaryProcessMain, which will handle common setup.
1610  *
1611  * Return value of StartChildProcess is subprocess' PID, or 0 if failed
1612  * to start subprocess.
1613  */
1614 #ifdef EXEC_BACKEND
1615 #endif
1616 #ifdef EXEC_BACKEND
1617 #else							/* !EXEC_BACKEND */
1618 #endif							/* EXEC_BACKEND */
1619 
1620 /*
1621  * StartAutovacuumWorker
1622  *		Start an autovac worker process.
1623  *
1624  * This function is here because it enters the resulting PID into the
1625  * postmaster's private backends list.
1626  *
1627  * NB -- this code very roughly matches BackendStartup.
1628  */
1629 #ifdef EXEC_BACKEND
1630 #endif
1631 
1632 /*
1633  * MaybeStartWalReceiver
1634  *		Start the WAL receiver process, if not running and our state allows.
1635  *
1636  * Note: if WalReceiverPID is already nonzero, it might seem that we should
1637  * clear WalReceiverRequested.  However, there's a race condition if the
1638  * walreceiver terminates and the startup process immediately requests a new
1639  * one: it's quite possible to get the signal for the request before reaping
1640  * the dead walreceiver process.  Better to risk launching an extra
1641  * walreceiver than to miss launching one we need.  (The walreceiver code
1642  * has logic to recognize that it should go away if not needed.)
1643  */
1644 
1645 
1646 
1647 /*
1648  * Create the opts file
1649  */
1650 #define OPTS_FILE	"postmaster.opts"
1651 
1652 
1653 /*
1654  * MaxLivePostmasterChildren
1655  *
1656  * This reports the number of entries needed in per-child-process arrays
1657  * (the PMChildFlags array, and if EXEC_BACKEND the ShmemBackendArray).
1658  * These arrays include regular backends, autovac workers, walsenders
1659  * and background workers, but not special children nor dead_end children.
1660  * This allows the arrays to have a fixed maximum size, to wit the same
1661  * too-many-children limit enforced by canAcceptConnections().  The exact value
1662  * isn't too critical as long as it's more than MaxBackends.
1663  */
1664 
1665 
1666 /*
1667  * Connect background worker to a database.
1668  */
1669 
1670 
1671 /*
1672  * Connect background worker to a database using OIDs.
1673  */
1674 
1675 
1676 /*
1677  * Block/unblock signals in a background worker
1678  */
1679 
1680 
1681 
1682 
1683 #ifdef EXEC_BACKEND
1684 static pid_t
1685 bgworker_forkexec(int shmem_slot)
1686 {
1687 	char	   *av[10];
1688 	int			ac = 0;
1689 	char		forkav[MAXPGPATH];
1690 
1691 	snprintf(forkav, MAXPGPATH, "--forkbgworker=%d", shmem_slot);
1692 
1693 	av[ac++] = "postgres";
1694 	av[ac++] = forkav;
1695 	av[ac++] = NULL;			/* filled in by postmaster_forkexec */
1696 	av[ac] = NULL;
1697 
1698 	Assert(ac < lengthof(av));
1699 
1700 	return postmaster_forkexec(ac, av);
1701 }
1702 #endif
1703 
1704 /*
1705  * Start a new bgworker.
1706  * Starting time conditions must have been checked already.
1707  *
1708  * Returns true on success, false on failure.
1709  * In either case, update the RegisteredBgWorker's state appropriately.
1710  *
1711  * This code is heavily based on autovacuum.c, q.v.
1712  */
1713 #ifdef EXEC_BACKEND
1714 #else
1715 #endif
1716 #ifndef EXEC_BACKEND
1717 #endif
1718 #ifdef EXEC_BACKEND
1719 #endif
1720 
1721 /*
1722  * Does the current postmaster state require starting a worker with the
1723  * specified start_time?
1724  */
1725 
1726 
1727 /*
1728  * Allocate the Backend struct for a connected background worker, but don't
1729  * add it to the list of backends just yet.
1730  *
1731  * On failure, return false without changing any worker state.
1732  *
1733  * Some info from the Backend is copied into the passed rw.
1734  */
1735 
1736 
1737 /*
1738  * If the time is right, start background worker(s).
1739  *
1740  * As a side effect, the bgworker control variables are set or reset
1741  * depending on whether more workers may need to be started.
1742  *
1743  * We limit the number of workers started per call, to avoid consuming the
1744  * postmaster's attention for too long when many such requests are pending.
1745  * As long as StartWorkerNeeded is true, ServerLoop will not block and will
1746  * call this function again after dealing with any other issues.
1747  */
1748 #define MAX_BGWORKERS_TO_LAUNCH 100
1749 
1750 /*
1751  * When a backend asks to be notified about worker state changes, we
1752  * set a flag in its backend entry.  The background worker machinery needs
1753  * to know when such backends exit.
1754  */
1755 
1756 
1757 #ifdef EXEC_BACKEND
1758 
1759 /*
1760  * The following need to be available to the save/restore_backend_variables
1761  * functions.  They are marked NON_EXEC_STATIC in their home modules.
1762  */
1763 extern slock_t *ShmemLock;
1764 extern slock_t *ProcStructLock;
1765 extern PGPROC *AuxiliaryProcs;
1766 extern PMSignalData *PMSignalState;
1767 extern pgsocket pgStatSock;
1768 extern pg_time_t first_syslogger_file_time;
1769 
1770 #ifndef WIN32
1771 #define write_inheritable_socket(dest, src, childpid) ((*(dest) = (src)), true)
1772 #define read_inheritable_socket(dest, src) (*(dest) = *(src))
1773 #else
1774 static bool write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE child);
1775 static bool write_inheritable_socket(InheritableSocket *dest, SOCKET src,
1776 						 pid_t childPid);
1777 static void read_inheritable_socket(SOCKET *dest, InheritableSocket *src);
1778 #endif
1779 
1780 
1781 /* Save critical backend variables into the BackendParameters struct */
1782 #ifndef WIN32
1783 static bool
1784 save_backend_variables(BackendParameters *param, Port *port)
1785 #else
1786 static bool
1787 save_backend_variables(BackendParameters *param, Port *port,
1788 					   HANDLE childProcess, pid_t childPid)
1789 #endif
1790 {
1791 	memcpy(&param->port, port, sizeof(Port));
1792 	if (!write_inheritable_socket(&param->portsocket, port->sock, childPid))
1793 		return false;
1794 
1795 	strlcpy(param->DataDir, DataDir, MAXPGPATH);
1796 
1797 	memcpy(&param->ListenSocket, &ListenSocket, sizeof(ListenSocket));
1798 
1799 	param->MyCancelKey = MyCancelKey;
1800 	param->MyPMChildSlot = MyPMChildSlot;
1801 
1802 #ifdef WIN32
1803 	param->ShmemProtectiveRegion = ShmemProtectiveRegion;
1804 #endif
1805 	param->UsedShmemSegID = UsedShmemSegID;
1806 	param->UsedShmemSegAddr = UsedShmemSegAddr;
1807 
1808 	param->ShmemLock = ShmemLock;
1809 	param->ShmemVariableCache = ShmemVariableCache;
1810 	param->ShmemBackendArray = ShmemBackendArray;
1811 
1812 #ifndef HAVE_SPINLOCKS
1813 	param->SpinlockSemaArray = SpinlockSemaArray;
1814 #endif
1815 	param->NamedLWLockTrancheRequests = NamedLWLockTrancheRequests;
1816 	param->NamedLWLockTrancheArray = NamedLWLockTrancheArray;
1817 	param->MainLWLockArray = MainLWLockArray;
1818 	param->ProcStructLock = ProcStructLock;
1819 	param->ProcGlobal = ProcGlobal;
1820 	param->AuxiliaryProcs = AuxiliaryProcs;
1821 	param->PreparedXactProcs = PreparedXactProcs;
1822 	param->PMSignalState = PMSignalState;
1823 	if (!write_inheritable_socket(&param->pgStatSock, pgStatSock, childPid))
1824 		return false;
1825 
1826 	param->PostmasterPid = PostmasterPid;
1827 	param->PgStartTime = PgStartTime;
1828 	param->PgReloadTime = PgReloadTime;
1829 	param->first_syslogger_file_time = first_syslogger_file_time;
1830 
1831 	param->redirection_done = redirection_done;
1832 	param->IsBinaryUpgrade = IsBinaryUpgrade;
1833 	param->max_safe_fds = max_safe_fds;
1834 
1835 	param->MaxBackends = MaxBackends;
1836 
1837 #ifdef WIN32
1838 	param->PostmasterHandle = PostmasterHandle;
1839 	if (!write_duplicated_handle(&param->initial_signal_pipe,
1840 								 pgwin32_create_signal_listener(childPid),
1841 								 childProcess))
1842 		return false;
1843 #else
1844 	memcpy(&param->postmaster_alive_fds, &postmaster_alive_fds,
1845 		   sizeof(postmaster_alive_fds));
1846 #endif
1847 
1848 	memcpy(&param->syslogPipe, &syslogPipe, sizeof(syslogPipe));
1849 
1850 	strlcpy(param->my_exec_path, my_exec_path, MAXPGPATH);
1851 
1852 	strlcpy(param->pkglib_path, pkglib_path, MAXPGPATH);
1853 
1854 	strlcpy(param->ExtraOptions, ExtraOptions, MAXPGPATH);
1855 
1856 	return true;
1857 }
1858 
1859 
1860 #ifdef WIN32
1861 /*
1862  * Duplicate a handle for usage in a child process, and write the child
1863  * process instance of the handle to the parameter file.
1864  */
1865 static bool
1866 write_duplicated_handle(HANDLE *dest, HANDLE src, HANDLE childProcess)
1867 {
1868 	HANDLE		hChild = INVALID_HANDLE_VALUE;
1869 
1870 	if (!DuplicateHandle(GetCurrentProcess(),
1871 						 src,
1872 						 childProcess,
1873 						 &hChild,
1874 						 0,
1875 						 TRUE,
1876 						 DUPLICATE_CLOSE_SOURCE | DUPLICATE_SAME_ACCESS))
1877 	{
1878 		ereport(LOG,
1879 				(errmsg_internal("could not duplicate handle to be written to backend parameter file: error code %lu",
1880 								 GetLastError())));
1881 		return false;
1882 	}
1883 
1884 	*dest = hChild;
1885 	return true;
1886 }
1887 
1888 /*
1889  * Duplicate a socket for usage in a child process, and write the resulting
1890  * structure to the parameter file.
1891  * This is required because a number of LSPs (Layered Service Providers) very
1892  * common on Windows (antivirus, firewalls, download managers etc) break
1893  * straight socket inheritance.
1894  */
1895 static bool
1896 write_inheritable_socket(InheritableSocket *dest, SOCKET src, pid_t childpid)
1897 {
1898 	dest->origsocket = src;
1899 	if (src != 0 && src != PGINVALID_SOCKET)
1900 	{
1901 		/* Actual socket */
1902 		if (WSADuplicateSocket(src, childpid, &dest->wsainfo) != 0)
1903 		{
1904 			ereport(LOG,
1905 					(errmsg("could not duplicate socket %d for use in backend: error code %d",
1906 							(int) src, WSAGetLastError())));
1907 			return false;
1908 		}
1909 	}
1910 	return true;
1911 }
1912 
1913 /*
1914  * Read a duplicate socket structure back, and get the socket descriptor.
1915  */
1916 static void
1917 read_inheritable_socket(SOCKET *dest, InheritableSocket *src)
1918 {
1919 	SOCKET		s;
1920 
1921 	if (src->origsocket == PGINVALID_SOCKET || src->origsocket == 0)
1922 	{
1923 		/* Not a real socket! */
1924 		*dest = src->origsocket;
1925 	}
1926 	else
1927 	{
1928 		/* Actual socket, so create from structure */
1929 		s = WSASocket(FROM_PROTOCOL_INFO,
1930 					  FROM_PROTOCOL_INFO,
1931 					  FROM_PROTOCOL_INFO,
1932 					  &src->wsainfo,
1933 					  0,
1934 					  0);
1935 		if (s == INVALID_SOCKET)
1936 		{
1937 			write_stderr("could not create inherited socket: error code %d\n",
1938 						 WSAGetLastError());
1939 			exit(1);
1940 		}
1941 		*dest = s;
1942 
1943 		/*
1944 		 * To make sure we don't get two references to the same socket, close
1945 		 * the original one. (This would happen when inheritance actually
1946 		 * works..
1947 		 */
1948 		closesocket(src->origsocket);
1949 	}
1950 }
1951 #endif
1952 
1953 static void
1954 read_backend_variables(char *id, Port *port)
1955 {
1956 	BackendParameters param;
1957 
1958 #ifndef WIN32
1959 	/* Non-win32 implementation reads from file */
1960 	FILE	   *fp;
1961 
1962 	/* Open file */
1963 	fp = AllocateFile(id, PG_BINARY_R);
1964 	if (!fp)
1965 	{
1966 		write_stderr("could not open backend variables file \"%s\": %s\n",
1967 					 id, strerror(errno));
1968 		exit(1);
1969 	}
1970 
1971 	if (fread(&param, sizeof(param), 1, fp) != 1)
1972 	{
1973 		write_stderr("could not read from backend variables file \"%s\": %s\n",
1974 					 id, strerror(errno));
1975 		exit(1);
1976 	}
1977 
1978 	/* Release file */
1979 	FreeFile(fp);
1980 	if (unlink(id) != 0)
1981 	{
1982 		write_stderr("could not remove file \"%s\": %s\n",
1983 					 id, strerror(errno));
1984 		exit(1);
1985 	}
1986 #else
1987 	/* Win32 version uses mapped file */
1988 	HANDLE		paramHandle;
1989 	BackendParameters *paramp;
1990 
1991 #ifdef _WIN64
1992 	paramHandle = (HANDLE) _atoi64(id);
1993 #else
1994 	paramHandle = (HANDLE) atol(id);
1995 #endif
1996 	paramp = MapViewOfFile(paramHandle, FILE_MAP_READ, 0, 0, 0);
1997 	if (!paramp)
1998 	{
1999 		write_stderr("could not map view of backend variables: error code %lu\n",
2000 					 GetLastError());
2001 		exit(1);
2002 	}
2003 
2004 	memcpy(&param, paramp, sizeof(BackendParameters));
2005 
2006 	if (!UnmapViewOfFile(paramp))
2007 	{
2008 		write_stderr("could not unmap view of backend variables: error code %lu\n",
2009 					 GetLastError());
2010 		exit(1);
2011 	}
2012 
2013 	if (!CloseHandle(paramHandle))
2014 	{
2015 		write_stderr("could not close handle to backend parameter variables: error code %lu\n",
2016 					 GetLastError());
2017 		exit(1);
2018 	}
2019 #endif
2020 
2021 	restore_backend_variables(&param, port);
2022 }
2023 
2024 /* Restore critical backend variables from the BackendParameters struct */
2025 static void
2026 restore_backend_variables(BackendParameters *param, Port *port)
2027 {
2028 	memcpy(port, &param->port, sizeof(Port));
2029 	read_inheritable_socket(&port->sock, &param->portsocket);
2030 
2031 	SetDataDir(param->DataDir);
2032 
2033 	memcpy(&ListenSocket, &param->ListenSocket, sizeof(ListenSocket));
2034 
2035 	MyCancelKey = param->MyCancelKey;
2036 	MyPMChildSlot = param->MyPMChildSlot;
2037 
2038 #ifdef WIN32
2039 	ShmemProtectiveRegion = param->ShmemProtectiveRegion;
2040 #endif
2041 	UsedShmemSegID = param->UsedShmemSegID;
2042 	UsedShmemSegAddr = param->UsedShmemSegAddr;
2043 
2044 	ShmemLock = param->ShmemLock;
2045 	ShmemVariableCache = param->ShmemVariableCache;
2046 	ShmemBackendArray = param->ShmemBackendArray;
2047 
2048 #ifndef HAVE_SPINLOCKS
2049 	SpinlockSemaArray = param->SpinlockSemaArray;
2050 #endif
2051 	NamedLWLockTrancheRequests = param->NamedLWLockTrancheRequests;
2052 	NamedLWLockTrancheArray = param->NamedLWLockTrancheArray;
2053 	MainLWLockArray = param->MainLWLockArray;
2054 	ProcStructLock = param->ProcStructLock;
2055 	ProcGlobal = param->ProcGlobal;
2056 	AuxiliaryProcs = param->AuxiliaryProcs;
2057 	PreparedXactProcs = param->PreparedXactProcs;
2058 	PMSignalState = param->PMSignalState;
2059 	read_inheritable_socket(&pgStatSock, &param->pgStatSock);
2060 
2061 	PostmasterPid = param->PostmasterPid;
2062 	PgStartTime = param->PgStartTime;
2063 	PgReloadTime = param->PgReloadTime;
2064 	first_syslogger_file_time = param->first_syslogger_file_time;
2065 
2066 	redirection_done = param->redirection_done;
2067 	IsBinaryUpgrade = param->IsBinaryUpgrade;
2068 	max_safe_fds = param->max_safe_fds;
2069 
2070 	MaxBackends = param->MaxBackends;
2071 
2072 #ifdef WIN32
2073 	PostmasterHandle = param->PostmasterHandle;
2074 	pgwin32_initial_signal_pipe = param->initial_signal_pipe;
2075 #else
2076 	memcpy(&postmaster_alive_fds, &param->postmaster_alive_fds,
2077 		   sizeof(postmaster_alive_fds));
2078 #endif
2079 
2080 	memcpy(&syslogPipe, &param->syslogPipe, sizeof(syslogPipe));
2081 
2082 	strlcpy(my_exec_path, param->my_exec_path, MAXPGPATH);
2083 
2084 	strlcpy(pkglib_path, param->pkglib_path, MAXPGPATH);
2085 
2086 	strlcpy(ExtraOptions, param->ExtraOptions, MAXPGPATH);
2087 }
2088 
2089 
2090 Size
2091 ShmemBackendArraySize(void)
2092 {
2093 	return mul_size(MaxLivePostmasterChildren(), sizeof(Backend));
2094 }
2095 
2096 void
2097 ShmemBackendArrayAllocation(void)
2098 {
2099 	Size		size = ShmemBackendArraySize();
2100 
2101 	ShmemBackendArray = (Backend *) ShmemAlloc(size);
2102 	/* Mark all slots as empty */
2103 	memset(ShmemBackendArray, 0, size);
2104 }
2105 
2106 static void
2107 ShmemBackendArrayAdd(Backend *bn)
2108 {
2109 	/* The array slot corresponding to my PMChildSlot should be free */
2110 	int			i = bn->child_slot - 1;
2111 
2112 	Assert(ShmemBackendArray[i].pid == 0);
2113 	ShmemBackendArray[i] = *bn;
2114 }
2115 
2116 static void
2117 ShmemBackendArrayRemove(Backend *bn)
2118 {
2119 	int			i = bn->child_slot - 1;
2120 
2121 	Assert(ShmemBackendArray[i].pid == bn->pid);
2122 	/* Mark the slot as empty */
2123 	ShmemBackendArray[i].pid = 0;
2124 }
2125 #endif							/* EXEC_BACKEND */
2126 
2127 
2128 #ifdef WIN32
2129 
2130 /*
2131  * Subset implementation of waitpid() for Windows.  We assume pid is -1
2132  * (that is, check all child processes) and options is WNOHANG (don't wait).
2133  */
2134 static pid_t
2135 waitpid(pid_t pid, int *exitstatus, int options)
2136 {
2137 	DWORD		dwd;
2138 	ULONG_PTR	key;
2139 	OVERLAPPED *ovl;
2140 
2141 	/*
2142 	 * Check if there are any dead children. If there are, return the pid of
2143 	 * the first one that died.
2144 	 */
2145 	if (GetQueuedCompletionStatus(win32ChildQueue, &dwd, &key, &ovl, 0))
2146 	{
2147 		*exitstatus = (int) key;
2148 		return dwd;
2149 	}
2150 
2151 	return -1;
2152 }
2153 
2154 /*
2155  * Note! Code below executes on a thread pool! All operations must
2156  * be thread safe! Note that elog() and friends must *not* be used.
2157  */
2158 static void WINAPI
2159 pgwin32_deadchild_callback(PVOID lpParameter, BOOLEAN TimerOrWaitFired)
2160 {
2161 	win32_deadchild_waitinfo *childinfo = (win32_deadchild_waitinfo *) lpParameter;
2162 	DWORD		exitcode;
2163 
2164 	if (TimerOrWaitFired)
2165 		return;					/* timeout. Should never happen, since we use
2166 								 * INFINITE as timeout value. */
2167 
2168 	/*
2169 	 * Remove handle from wait - required even though it's set to wait only
2170 	 * once
2171 	 */
2172 	UnregisterWaitEx(childinfo->waitHandle, NULL);
2173 
2174 	if (!GetExitCodeProcess(childinfo->procHandle, &exitcode))
2175 	{
2176 		/*
2177 		 * Should never happen. Inform user and set a fixed exitcode.
2178 		 */
2179 		write_stderr("could not read exit code for process\n");
2180 		exitcode = 255;
2181 	}
2182 
2183 	if (!PostQueuedCompletionStatus(win32ChildQueue, childinfo->procId, (ULONG_PTR) exitcode, NULL))
2184 		write_stderr("could not post child completion status\n");
2185 
2186 	/*
2187 	 * Handle is per-process, so we close it here instead of in the
2188 	 * originating thread
2189 	 */
2190 	CloseHandle(childinfo->procHandle);
2191 
2192 	/*
2193 	 * Free struct that was allocated before the call to
2194 	 * RegisterWaitForSingleObject()
2195 	 */
2196 	free(childinfo);
2197 
2198 	/* Queue SIGCHLD signal */
2199 	pg_queue_signal(SIGCHLD);
2200 }
2201 #endif							/* WIN32 */
2202 
2203 /*
2204  * Initialize one and only handle for monitoring postmaster death.
2205  *
2206  * Called once in the postmaster, so that child processes can subsequently
2207  * monitor if their parent is dead.
2208  */
2209 #ifndef WIN32
2210 #else
2211 #endif							/* WIN32 */
2212