1 /*-------------------------------------------------------------------------
2  *
3  * postgres.c
4  *	  POSTGRES C Backend Interface
5  *
6  * Portions Copyright (c) 1996-2018, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *	  src/backend/tcop/postgres.c
12  *
13  * NOTES
14  *	  this is the "main" module of the postgres backend and
15  *	  hence the main module of the "traffic cop".
16  *
17  *-------------------------------------------------------------------------
18  */
19 
20 #include "postgres.h"
21 
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <sys/socket.h>
27 #ifdef HAVE_SYS_SELECT_H
28 #include <sys/select.h>
29 #endif
30 #ifdef HAVE_SYS_RESOURCE_H
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #endif
34 
35 #ifndef HAVE_GETRUSAGE
36 #include "rusagestub.h"
37 #endif
38 
39 #include "access/parallel.h"
40 #include "access/printtup.h"
41 #include "access/xact.h"
42 #include "catalog/pg_type.h"
43 #include "commands/async.h"
44 #include "commands/prepare.h"
45 #include "executor/spi.h"
46 #include "jit/jit.h"
47 #include "libpq/libpq.h"
48 #include "libpq/pqformat.h"
49 #include "libpq/pqsignal.h"
50 #include "miscadmin.h"
51 #include "nodes/print.h"
52 #include "optimizer/planner.h"
53 #include "pgstat.h"
54 #include "pg_trace.h"
55 #include "parser/analyze.h"
56 #include "parser/parser.h"
57 #include "pg_getopt.h"
58 #include "postmaster/autovacuum.h"
59 #include "postmaster/postmaster.h"
60 #include "replication/logicallauncher.h"
61 #include "replication/logicalworker.h"
62 #include "replication/slot.h"
63 #include "replication/walsender.h"
64 #include "rewrite/rewriteHandler.h"
65 #include "storage/bufmgr.h"
66 #include "storage/ipc.h"
67 #include "storage/proc.h"
68 #include "storage/procsignal.h"
69 #include "storage/sinval.h"
70 #include "tcop/fastpath.h"
71 #include "tcop/pquery.h"
72 #include "tcop/tcopprot.h"
73 #include "tcop/utility.h"
74 #include "utils/lsyscache.h"
75 #include "utils/memutils.h"
76 #include "utils/ps_status.h"
77 #include "utils/snapmgr.h"
78 #include "utils/timeout.h"
79 #include "utils/timestamp.h"
80 #include "mb/pg_wchar.h"
81 
82 
83 /* ----------------
84  *		global variables
85  * ----------------
86  */
87 const char *debug_query_string; /* client-supplied query string */
88 
89 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
90 CommandDest whereToSendOutput = DestDebug;
91 
92 /* flag for logging end of session */
93 bool		Log_disconnections = false;
94 
95 int			log_statement = LOGSTMT_NONE;
96 
97 /* GUC variable for maximum stack depth (measured in kilobytes) */
98 int			max_stack_depth = 100;
99 
100 /* wait N seconds to allow attach from a debugger */
101 int			PostAuthDelay = 0;
102 
103 
104 
105 /* ----------------
106  *		private variables
107  * ----------------
108  */
109 
110 /* max_stack_depth converted to bytes for speed of checking */
111 static long max_stack_depth_bytes = 100 * 1024L;
112 
113 /*
114  * Stack base pointer -- initialized by PostmasterMain and inherited by
115  * subprocesses. This is not static because old versions of PL/Java modify
116  * it directly. Newer versions use set_stack_base(), but we want to stay
117  * binary-compatible for the time being.
118  */
119 char	   *stack_base_ptr = NULL;
120 
121 /*
122  * On IA64 we also have to remember the register stack base.
123  */
124 #if defined(__ia64__) || defined(__ia64)
125 char	   *register_stack_base_ptr = NULL;
126 #endif
127 
128 /*
129  * Flag to keep track of whether we have started a transaction.
130  * For extended query protocol this has to be remembered across messages.
131  */
132 static bool xact_started = false;
133 
134 /*
135  * Flag to indicate that we are doing the outer loop's read-from-client,
136  * as opposed to any random read from client that might happen within
137  * commands like COPY FROM STDIN.
138  */
139 static bool DoingCommandRead = false;
140 
141 /*
142  * Flags to implement skip-till-Sync-after-error behavior for messages of
143  * the extended query protocol.
144  */
145 static bool doing_extended_query_message = false;
146 static bool ignore_till_sync = false;
147 
148 /*
149  * Flag to keep track of whether statement timeout timer is active.
150  */
151 static bool stmt_timeout_active = false;
152 
153 /*
154  * If an unnamed prepared statement exists, it's stored here.
155  * We keep it separate from the hashtable kept by commands/prepare.c
156  * in order to reduce overhead for short-lived queries.
157  */
158 static CachedPlanSource *unnamed_stmt_psrc = NULL;
159 
160 /* assorted command-line switches */
161 static const char *userDoption = NULL;	/* -D switch */
162 static bool EchoQuery = false;	/* -E switch */
163 static bool UseSemiNewlineNewline = false;	/* -j switch */
164 
165 /* whether or not, and why, we were canceled by conflict with recovery */
166 static bool RecoveryConflictPending = false;
167 static bool RecoveryConflictRetryable = true;
168 static ProcSignalReason RecoveryConflictReason;
169 
170 /* reused buffer to pass to SendRowDescriptionMessage() */
171 static MemoryContext row_description_context = NULL;
172 static StringInfoData row_description_buf;
173 
174 /* ----------------------------------------------------------------
175  *		decls for routines only used in this file
176  * ----------------------------------------------------------------
177  */
178 static int	InteractiveBackend(StringInfo inBuf);
179 static int	interactive_getc(void);
180 static int	SocketBackend(StringInfo inBuf);
181 static int	ReadCommand(StringInfo inBuf);
182 static void forbidden_in_wal_sender(char firstchar);
183 static List *pg_rewrite_query(Query *query);
184 static bool check_log_statement(List *stmt_list);
185 static int	errdetail_execute(List *raw_parsetree_list);
186 static int	errdetail_params(ParamListInfo params);
187 static int	errdetail_abort(void);
188 static int	errdetail_recovery_conflict(void);
189 static void start_xact_command(void);
190 static void finish_xact_command(void);
191 static bool IsTransactionExitStmt(Node *parsetree);
192 static bool IsTransactionExitStmtList(List *pstmts);
193 static bool IsTransactionStmtList(List *pstmts);
194 static void drop_unnamed_stmt(void);
195 static void log_disconnections(int code, Datum arg);
196 static void enable_statement_timeout(void);
197 static void disable_statement_timeout(void);
198 
199 
200 /* ----------------------------------------------------------------
201  *		routines to obtain user input
202  * ----------------------------------------------------------------
203  */
204 
205 /* ----------------
206  *	InteractiveBackend() is called for user interactive connections
207  *
208  *	the string entered by the user is placed in its parameter inBuf,
209  *	and we act like a Q message was received.
210  *
211  *	EOF is returned if end-of-file input is seen; time to shut down.
212  * ----------------
213  */
214 
215 static int
InteractiveBackend(StringInfo inBuf)216 InteractiveBackend(StringInfo inBuf)
217 {
218 	int			c;				/* character read from getc() */
219 
220 	/*
221 	 * display a prompt and obtain input from the user
222 	 */
223 	printf("backend> ");
224 	fflush(stdout);
225 
226 	resetStringInfo(inBuf);
227 
228 	/*
229 	 * Read characters until EOF or the appropriate delimiter is seen.
230 	 */
231 	while ((c = interactive_getc()) != EOF)
232 	{
233 		if (c == '\n')
234 		{
235 			if (UseSemiNewlineNewline)
236 			{
237 				/*
238 				 * In -j mode, semicolon followed by two newlines ends the
239 				 * command; otherwise treat newline as regular character.
240 				 */
241 				if (inBuf->len > 1 &&
242 					inBuf->data[inBuf->len - 1] == '\n' &&
243 					inBuf->data[inBuf->len - 2] == ';')
244 				{
245 					/* might as well drop the second newline */
246 					break;
247 				}
248 			}
249 			else
250 			{
251 				/*
252 				 * In plain mode, newline ends the command unless preceded by
253 				 * backslash.
254 				 */
255 				if (inBuf->len > 0 &&
256 					inBuf->data[inBuf->len - 1] == '\\')
257 				{
258 					/* discard backslash from inBuf */
259 					inBuf->data[--inBuf->len] = '\0';
260 					/* discard newline too */
261 					continue;
262 				}
263 				else
264 				{
265 					/* keep the newline character, but end the command */
266 					appendStringInfoChar(inBuf, '\n');
267 					break;
268 				}
269 			}
270 		}
271 
272 		/* Not newline, or newline treated as regular character */
273 		appendStringInfoChar(inBuf, (char) c);
274 	}
275 
276 	/* No input before EOF signal means time to quit. */
277 	if (c == EOF && inBuf->len == 0)
278 		return EOF;
279 
280 	/*
281 	 * otherwise we have a user query so process it.
282 	 */
283 
284 	/* Add '\0' to make it look the same as message case. */
285 	appendStringInfoChar(inBuf, (char) '\0');
286 
287 	/*
288 	 * if the query echo flag was given, print the query..
289 	 */
290 	if (EchoQuery)
291 		printf("statement: %s\n", inBuf->data);
292 	fflush(stdout);
293 
294 	return 'Q';
295 }
296 
297 /*
298  * interactive_getc -- collect one character from stdin
299  *
300  * Even though we are not reading from a "client" process, we still want to
301  * respond to signals, particularly SIGTERM/SIGQUIT.
302  */
303 static int
interactive_getc(void)304 interactive_getc(void)
305 {
306 	int			c;
307 
308 	/*
309 	 * This will not process catchup interrupts or notifications while
310 	 * reading. But those can't really be relevant for a standalone backend
311 	 * anyway. To properly handle SIGTERM there's a hack in die() that
312 	 * directly processes interrupts at this stage...
313 	 */
314 	CHECK_FOR_INTERRUPTS();
315 
316 	c = getc(stdin);
317 
318 	ProcessClientReadInterrupt(false);
319 
320 	return c;
321 }
322 
323 /* ----------------
324  *	SocketBackend()		Is called for frontend-backend connections
325  *
326  *	Returns the message type code, and loads message body data into inBuf.
327  *
328  *	EOF is returned if the connection is lost.
329  * ----------------
330  */
331 static int
SocketBackend(StringInfo inBuf)332 SocketBackend(StringInfo inBuf)
333 {
334 	int			qtype;
335 
336 	/*
337 	 * Get message type code from the frontend.
338 	 */
339 	HOLD_CANCEL_INTERRUPTS();
340 	pq_startmsgread();
341 	qtype = pq_getbyte();
342 
343 	if (qtype == EOF)			/* frontend disconnected */
344 	{
345 		if (IsTransactionState())
346 			ereport(COMMERROR,
347 					(errcode(ERRCODE_CONNECTION_FAILURE),
348 					 errmsg("unexpected EOF on client connection with an open transaction")));
349 		else
350 		{
351 			/*
352 			 * Can't send DEBUG log messages to client at this point. Since
353 			 * we're disconnecting right away, we don't need to restore
354 			 * whereToSendOutput.
355 			 */
356 			whereToSendOutput = DestNone;
357 			ereport(DEBUG1,
358 					(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
359 					 errmsg("unexpected EOF on client connection")));
360 		}
361 		return qtype;
362 	}
363 
364 	/*
365 	 * Validate message type code before trying to read body; if we have lost
366 	 * sync, better to say "command unknown" than to run out of memory because
367 	 * we used garbage as a length word.
368 	 *
369 	 * This also gives us a place to set the doing_extended_query_message flag
370 	 * as soon as possible.
371 	 */
372 	switch (qtype)
373 	{
374 		case 'Q':				/* simple query */
375 			doing_extended_query_message = false;
376 			if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
377 			{
378 				/* old style without length word; convert */
379 				if (pq_getstring(inBuf))
380 				{
381 					if (IsTransactionState())
382 						ereport(COMMERROR,
383 								(errcode(ERRCODE_CONNECTION_FAILURE),
384 								 errmsg("unexpected EOF on client connection with an open transaction")));
385 					else
386 					{
387 						/*
388 						 * Can't send DEBUG log messages to client at this
389 						 * point. Since we're disconnecting right away, we
390 						 * don't need to restore whereToSendOutput.
391 						 */
392 						whereToSendOutput = DestNone;
393 						ereport(DEBUG1,
394 								(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
395 								 errmsg("unexpected EOF on client connection")));
396 					}
397 					return EOF;
398 				}
399 			}
400 			break;
401 
402 		case 'F':				/* fastpath function call */
403 			doing_extended_query_message = false;
404 			if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
405 			{
406 				if (GetOldFunctionMessage(inBuf))
407 				{
408 					if (IsTransactionState())
409 						ereport(COMMERROR,
410 								(errcode(ERRCODE_CONNECTION_FAILURE),
411 								 errmsg("unexpected EOF on client connection with an open transaction")));
412 					else
413 					{
414 						/*
415 						 * Can't send DEBUG log messages to client at this
416 						 * point. Since we're disconnecting right away, we
417 						 * don't need to restore whereToSendOutput.
418 						 */
419 						whereToSendOutput = DestNone;
420 						ereport(DEBUG1,
421 								(errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
422 								 errmsg("unexpected EOF on client connection")));
423 					}
424 					return EOF;
425 				}
426 			}
427 			break;
428 
429 		case 'X':				/* terminate */
430 			doing_extended_query_message = false;
431 			ignore_till_sync = false;
432 			break;
433 
434 		case 'B':				/* bind */
435 		case 'C':				/* close */
436 		case 'D':				/* describe */
437 		case 'E':				/* execute */
438 		case 'H':				/* flush */
439 		case 'P':				/* parse */
440 			doing_extended_query_message = true;
441 			/* these are only legal in protocol 3 */
442 			if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
443 				ereport(FATAL,
444 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
445 						 errmsg("invalid frontend message type %d", qtype)));
446 			break;
447 
448 		case 'S':				/* sync */
449 			/* stop any active skip-till-Sync */
450 			ignore_till_sync = false;
451 			/* mark not-extended, so that a new error doesn't begin skip */
452 			doing_extended_query_message = false;
453 			/* only legal in protocol 3 */
454 			if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
455 				ereport(FATAL,
456 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
457 						 errmsg("invalid frontend message type %d", qtype)));
458 			break;
459 
460 		case 'd':				/* copy data */
461 		case 'c':				/* copy done */
462 		case 'f':				/* copy fail */
463 			doing_extended_query_message = false;
464 			/* these are only legal in protocol 3 */
465 			if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
466 				ereport(FATAL,
467 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
468 						 errmsg("invalid frontend message type %d", qtype)));
469 			break;
470 
471 		default:
472 
473 			/*
474 			 * Otherwise we got garbage from the frontend.  We treat this as
475 			 * fatal because we have probably lost message boundary sync, and
476 			 * there's no good way to recover.
477 			 */
478 			ereport(FATAL,
479 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
480 					 errmsg("invalid frontend message type %d", qtype)));
481 			break;
482 	}
483 
484 	/*
485 	 * In protocol version 3, all frontend messages have a length word next
486 	 * after the type code; we can read the message contents independently of
487 	 * the type.
488 	 */
489 	if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
490 	{
491 		if (pq_getmessage(inBuf, 0))
492 			return EOF;			/* suitable message already logged */
493 	}
494 	else
495 		pq_endmsgread();
496 	RESUME_CANCEL_INTERRUPTS();
497 
498 	return qtype;
499 }
500 
501 /* ----------------
502  *		ReadCommand reads a command from either the frontend or
503  *		standard input, places it in inBuf, and returns the
504  *		message type code (first byte of the message).
505  *		EOF is returned if end of file.
506  * ----------------
507  */
508 static int
ReadCommand(StringInfo inBuf)509 ReadCommand(StringInfo inBuf)
510 {
511 	int			result;
512 
513 	if (whereToSendOutput == DestRemote)
514 		result = SocketBackend(inBuf);
515 	else
516 		result = InteractiveBackend(inBuf);
517 	return result;
518 }
519 
520 /*
521  * ProcessClientReadInterrupt() - Process interrupts specific to client reads
522  *
523  * This is called just before and after low-level reads.
524  * 'blocked' is true if no data was available to read and we plan to retry,
525  * false if about to read or done reading.
526  *
527  * Must preserve errno!
528  */
529 void
ProcessClientReadInterrupt(bool blocked)530 ProcessClientReadInterrupt(bool blocked)
531 {
532 	int			save_errno = errno;
533 
534 	if (DoingCommandRead)
535 	{
536 		/* Check for general interrupts that arrived before/while reading */
537 		CHECK_FOR_INTERRUPTS();
538 
539 		/* Process sinval catchup interrupts, if any */
540 		if (catchupInterruptPending)
541 			ProcessCatchupInterrupt();
542 
543 		/* Process notify interrupts, if any */
544 		if (notifyInterruptPending)
545 			ProcessNotifyInterrupt();
546 	}
547 	else if (ProcDiePending)
548 	{
549 		/*
550 		 * We're dying.  If there is no data available to read, then it's safe
551 		 * (and sane) to handle that now.  If we haven't tried to read yet,
552 		 * make sure the process latch is set, so that if there is no data
553 		 * then we'll come back here and die.  If we're done reading, also
554 		 * make sure the process latch is set, as we might've undesirably
555 		 * cleared it while reading.
556 		 */
557 		if (blocked)
558 			CHECK_FOR_INTERRUPTS();
559 		else
560 			SetLatch(MyLatch);
561 	}
562 
563 	errno = save_errno;
564 }
565 
566 /*
567  * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
568  *
569  * This is called just before and after low-level writes.
570  * 'blocked' is true if no data could be written and we plan to retry,
571  * false if about to write or done writing.
572  *
573  * Must preserve errno!
574  */
575 void
ProcessClientWriteInterrupt(bool blocked)576 ProcessClientWriteInterrupt(bool blocked)
577 {
578 	int			save_errno = errno;
579 
580 	if (ProcDiePending)
581 	{
582 		/*
583 		 * We're dying.  If it's not possible to write, then we should handle
584 		 * that immediately, else a stuck client could indefinitely delay our
585 		 * response to the signal.  If we haven't tried to write yet, make
586 		 * sure the process latch is set, so that if the write would block
587 		 * then we'll come back here and die.  If we're done writing, also
588 		 * make sure the process latch is set, as we might've undesirably
589 		 * cleared it while writing.
590 		 */
591 		if (blocked)
592 		{
593 			/*
594 			 * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
595 			 * service ProcDiePending.
596 			 */
597 			if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
598 			{
599 				/*
600 				 * We don't want to send the client the error message, as a)
601 				 * that would possibly block again, and b) it would likely
602 				 * lead to loss of protocol sync because we may have already
603 				 * sent a partial protocol message.
604 				 */
605 				if (whereToSendOutput == DestRemote)
606 					whereToSendOutput = DestNone;
607 
608 				CHECK_FOR_INTERRUPTS();
609 			}
610 		}
611 		else
612 			SetLatch(MyLatch);
613 	}
614 
615 	errno = save_errno;
616 }
617 
618 /*
619  * Do raw parsing (only).
620  *
621  * A list of parsetrees (RawStmt nodes) is returned, since there might be
622  * multiple commands in the given string.
623  *
624  * NOTE: for interactive queries, it is important to keep this routine
625  * separate from the analysis & rewrite stages.  Analysis and rewriting
626  * cannot be done in an aborted transaction, since they require access to
627  * database tables.  So, we rely on the raw parser to determine whether
628  * we've seen a COMMIT or ABORT command; when we are in abort state, other
629  * commands are not processed any further than the raw parse stage.
630  */
631 List *
pg_parse_query(const char * query_string)632 pg_parse_query(const char *query_string)
633 {
634 	List	   *raw_parsetree_list;
635 
636 	TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
637 
638 	if (log_parser_stats)
639 		ResetUsage();
640 
641 	raw_parsetree_list = raw_parser(query_string);
642 
643 	if (log_parser_stats)
644 		ShowUsage("PARSER STATISTICS");
645 
646 #ifdef COPY_PARSE_PLAN_TREES
647 	/* Optional debugging check: pass raw parsetrees through copyObject() */
648 	{
649 		List	   *new_list = copyObject(raw_parsetree_list);
650 
651 		/* This checks both copyObject() and the equal() routines... */
652 		if (!equal(new_list, raw_parsetree_list))
653 			elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
654 		else
655 			raw_parsetree_list = new_list;
656 	}
657 #endif
658 
659 	TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
660 
661 	return raw_parsetree_list;
662 }
663 
664 /*
665  * Given a raw parsetree (gram.y output), and optionally information about
666  * types of parameter symbols ($n), perform parse analysis and rule rewriting.
667  *
668  * A list of Query nodes is returned, since either the analyzer or the
669  * rewriter might expand one query to several.
670  *
671  * NOTE: for reasons mentioned above, this must be separate from raw parsing.
672  */
673 List *
pg_analyze_and_rewrite(RawStmt * parsetree,const char * query_string,Oid * paramTypes,int numParams,QueryEnvironment * queryEnv)674 pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string,
675 					   Oid *paramTypes, int numParams,
676 					   QueryEnvironment *queryEnv)
677 {
678 	Query	   *query;
679 	List	   *querytree_list;
680 
681 	TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
682 
683 	/*
684 	 * (1) Perform parse analysis.
685 	 */
686 	if (log_parser_stats)
687 		ResetUsage();
688 
689 	query = parse_analyze(parsetree, query_string, paramTypes, numParams,
690 						  queryEnv);
691 
692 	if (log_parser_stats)
693 		ShowUsage("PARSE ANALYSIS STATISTICS");
694 
695 	/*
696 	 * (2) Rewrite the queries, as necessary
697 	 */
698 	querytree_list = pg_rewrite_query(query);
699 
700 	TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
701 
702 	return querytree_list;
703 }
704 
705 /*
706  * Do parse analysis and rewriting.  This is the same as pg_analyze_and_rewrite
707  * except that external-parameter resolution is determined by parser callback
708  * hooks instead of a fixed list of parameter datatypes.
709  */
710 List *
pg_analyze_and_rewrite_params(RawStmt * parsetree,const char * query_string,ParserSetupHook parserSetup,void * parserSetupArg,QueryEnvironment * queryEnv)711 pg_analyze_and_rewrite_params(RawStmt *parsetree,
712 							  const char *query_string,
713 							  ParserSetupHook parserSetup,
714 							  void *parserSetupArg,
715 							  QueryEnvironment *queryEnv)
716 {
717 	ParseState *pstate;
718 	Query	   *query;
719 	List	   *querytree_list;
720 
721 	Assert(query_string != NULL);	/* required as of 8.4 */
722 
723 	TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
724 
725 	/*
726 	 * (1) Perform parse analysis.
727 	 */
728 	if (log_parser_stats)
729 		ResetUsage();
730 
731 	pstate = make_parsestate(NULL);
732 	pstate->p_sourcetext = query_string;
733 	pstate->p_queryEnv = queryEnv;
734 	(*parserSetup) (pstate, parserSetupArg);
735 
736 	query = transformTopLevelStmt(pstate, parsetree);
737 
738 	if (post_parse_analyze_hook)
739 		(*post_parse_analyze_hook) (pstate, query);
740 
741 	free_parsestate(pstate);
742 
743 	if (log_parser_stats)
744 		ShowUsage("PARSE ANALYSIS STATISTICS");
745 
746 	/*
747 	 * (2) Rewrite the queries, as necessary
748 	 */
749 	querytree_list = pg_rewrite_query(query);
750 
751 	TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
752 
753 	return querytree_list;
754 }
755 
756 /*
757  * Perform rewriting of a query produced by parse analysis.
758  *
759  * Note: query must just have come from the parser, because we do not do
760  * AcquireRewriteLocks() on it.
761  */
762 static List *
pg_rewrite_query(Query * query)763 pg_rewrite_query(Query *query)
764 {
765 	List	   *querytree_list;
766 
767 	if (Debug_print_parse)
768 		elog_node_display(LOG, "parse tree", query,
769 						  Debug_pretty_print);
770 
771 	if (log_parser_stats)
772 		ResetUsage();
773 
774 	if (query->commandType == CMD_UTILITY)
775 	{
776 		/* don't rewrite utilities, just dump 'em into result list */
777 		querytree_list = list_make1(query);
778 	}
779 	else
780 	{
781 		/* rewrite regular queries */
782 		querytree_list = QueryRewrite(query);
783 	}
784 
785 	if (log_parser_stats)
786 		ShowUsage("REWRITER STATISTICS");
787 
788 #ifdef COPY_PARSE_PLAN_TREES
789 	/* Optional debugging check: pass querytree output through copyObject() */
790 	{
791 		List	   *new_list;
792 
793 		new_list = copyObject(querytree_list);
794 		/* This checks both copyObject() and the equal() routines... */
795 		if (!equal(new_list, querytree_list))
796 			elog(WARNING, "copyObject() failed to produce equal parse tree");
797 		else
798 			querytree_list = new_list;
799 	}
800 #endif
801 
802 	if (Debug_print_rewritten)
803 		elog_node_display(LOG, "rewritten parse tree", querytree_list,
804 						  Debug_pretty_print);
805 
806 	return querytree_list;
807 }
808 
809 
810 /*
811  * Generate a plan for a single already-rewritten query.
812  * This is a thin wrapper around planner() and takes the same parameters.
813  */
814 PlannedStmt *
pg_plan_query(Query * querytree,int cursorOptions,ParamListInfo boundParams)815 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
816 {
817 	PlannedStmt *plan;
818 
819 	/* Utility commands have no plans. */
820 	if (querytree->commandType == CMD_UTILITY)
821 		return NULL;
822 
823 	/* Planner must have a snapshot in case it calls user-defined functions. */
824 	Assert(ActiveSnapshotSet());
825 
826 	TRACE_POSTGRESQL_QUERY_PLAN_START();
827 
828 	if (log_planner_stats)
829 		ResetUsage();
830 
831 	/* call the optimizer */
832 	plan = planner(querytree, cursorOptions, boundParams);
833 
834 	if (log_planner_stats)
835 		ShowUsage("PLANNER STATISTICS");
836 
837 #ifdef COPY_PARSE_PLAN_TREES
838 	/* Optional debugging check: pass plan output through copyObject() */
839 	{
840 		PlannedStmt *new_plan = copyObject(plan);
841 
842 		/*
843 		 * equal() currently does not have routines to compare Plan nodes, so
844 		 * don't try to test equality here.  Perhaps fix someday?
845 		 */
846 #ifdef NOT_USED
847 		/* This checks both copyObject() and the equal() routines... */
848 		if (!equal(new_plan, plan))
849 			elog(WARNING, "copyObject() failed to produce an equal plan tree");
850 		else
851 #endif
852 			plan = new_plan;
853 	}
854 #endif
855 
856 	/*
857 	 * Print plan if debugging.
858 	 */
859 	if (Debug_print_plan)
860 		elog_node_display(LOG, "plan", plan, Debug_pretty_print);
861 
862 	TRACE_POSTGRESQL_QUERY_PLAN_DONE();
863 
864 	return plan;
865 }
866 
867 /*
868  * Generate plans for a list of already-rewritten queries.
869  *
870  * For normal optimizable statements, invoke the planner.  For utility
871  * statements, just make a wrapper PlannedStmt node.
872  *
873  * The result is a list of PlannedStmt nodes.
874  */
875 List *
pg_plan_queries(List * querytrees,int cursorOptions,ParamListInfo boundParams)876 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
877 {
878 	List	   *stmt_list = NIL;
879 	ListCell   *query_list;
880 
881 	foreach(query_list, querytrees)
882 	{
883 		Query	   *query = lfirst_node(Query, query_list);
884 		PlannedStmt *stmt;
885 
886 		if (query->commandType == CMD_UTILITY)
887 		{
888 			/* Utility commands require no planning. */
889 			stmt = makeNode(PlannedStmt);
890 			stmt->commandType = CMD_UTILITY;
891 			stmt->canSetTag = query->canSetTag;
892 			stmt->utilityStmt = query->utilityStmt;
893 			stmt->stmt_location = query->stmt_location;
894 			stmt->stmt_len = query->stmt_len;
895 		}
896 		else
897 		{
898 			stmt = pg_plan_query(query, cursorOptions, boundParams);
899 		}
900 
901 		stmt_list = lappend(stmt_list, stmt);
902 	}
903 
904 	return stmt_list;
905 }
906 
907 
908 /*
909  * exec_simple_query
910  *
911  * Execute a "simple Query" protocol message.
912  */
913 static void
exec_simple_query(const char * query_string)914 exec_simple_query(const char *query_string)
915 {
916 	CommandDest dest = whereToSendOutput;
917 	MemoryContext oldcontext;
918 	List	   *parsetree_list;
919 	ListCell   *parsetree_item;
920 	bool		save_log_statement_stats = log_statement_stats;
921 	bool		was_logged = false;
922 	bool		use_implicit_block;
923 	char		msec_str[32];
924 
925 	/*
926 	 * Report query to various monitoring facilities.
927 	 */
928 	debug_query_string = query_string;
929 
930 	pgstat_report_activity(STATE_RUNNING, query_string);
931 
932 	TRACE_POSTGRESQL_QUERY_START(query_string);
933 
934 	/*
935 	 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
936 	 * results because ResetUsage wasn't called.
937 	 */
938 	if (save_log_statement_stats)
939 		ResetUsage();
940 
941 	/*
942 	 * Start up a transaction command.  All queries generated by the
943 	 * query_string will be in this same command block, *unless* we find a
944 	 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
945 	 * one of those, else bad things will happen in xact.c. (Note that this
946 	 * will normally change current memory context.)
947 	 */
948 	start_xact_command();
949 
950 	/*
951 	 * Zap any pre-existing unnamed statement.  (While not strictly necessary,
952 	 * it seems best to define simple-Query mode as if it used the unnamed
953 	 * statement and portal; this ensures we recover any storage used by prior
954 	 * unnamed operations.)
955 	 */
956 	drop_unnamed_stmt();
957 
958 	/*
959 	 * Switch to appropriate context for constructing parsetrees.
960 	 */
961 	oldcontext = MemoryContextSwitchTo(MessageContext);
962 
963 	/*
964 	 * Do basic parsing of the query or queries (this should be safe even if
965 	 * we are in aborted transaction state!)
966 	 */
967 	parsetree_list = pg_parse_query(query_string);
968 
969 	/* Log immediately if dictated by log_statement */
970 	if (check_log_statement(parsetree_list))
971 	{
972 		ereport(LOG,
973 				(errmsg("statement: %s", query_string),
974 				 errhidestmt(true),
975 				 errdetail_execute(parsetree_list)));
976 		was_logged = true;
977 	}
978 
979 	/*
980 	 * Switch back to transaction context to enter the loop.
981 	 */
982 	MemoryContextSwitchTo(oldcontext);
983 
984 	/*
985 	 * For historical reasons, if multiple SQL statements are given in a
986 	 * single "simple Query" message, we execute them as a single transaction,
987 	 * unless explicit transaction control commands are included to make
988 	 * portions of the list be separate transactions.  To represent this
989 	 * behavior properly in the transaction machinery, we use an "implicit"
990 	 * transaction block.
991 	 */
992 	use_implicit_block = (list_length(parsetree_list) > 1);
993 
994 	/*
995 	 * Run through the raw parsetree(s) and process each one.
996 	 */
997 	foreach(parsetree_item, parsetree_list)
998 	{
999 		RawStmt    *parsetree = lfirst_node(RawStmt, parsetree_item);
1000 		bool		snapshot_set = false;
1001 		const char *commandTag;
1002 		char		completionTag[COMPLETION_TAG_BUFSIZE];
1003 		List	   *querytree_list,
1004 				   *plantree_list;
1005 		Portal		portal;
1006 		DestReceiver *receiver;
1007 		int16		format;
1008 
1009 		/*
1010 		 * Get the command name for use in status display (it also becomes the
1011 		 * default completion tag, down inside PortalRun).  Set ps_status and
1012 		 * do any special start-of-SQL-command processing needed by the
1013 		 * destination.
1014 		 */
1015 		commandTag = CreateCommandTag(parsetree->stmt);
1016 
1017 		set_ps_display(commandTag, false);
1018 
1019 		BeginCommand(commandTag, dest);
1020 
1021 		/*
1022 		 * If we are in an aborted transaction, reject all commands except
1023 		 * COMMIT/ABORT.  It is important that this test occur before we try
1024 		 * to do parse analysis, rewrite, or planning, since all those phases
1025 		 * try to do database accesses, which may fail in abort state. (It
1026 		 * might be safe to allow some additional utility commands in this
1027 		 * state, but not many...)
1028 		 */
1029 		if (IsAbortedTransactionBlockState() &&
1030 			!IsTransactionExitStmt(parsetree->stmt))
1031 			ereport(ERROR,
1032 					(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1033 					 errmsg("current transaction is aborted, "
1034 							"commands ignored until end of transaction block"),
1035 					 errdetail_abort()));
1036 
1037 		/* Make sure we are in a transaction command */
1038 		start_xact_command();
1039 
1040 		/*
1041 		 * If using an implicit transaction block, and we're not already in a
1042 		 * transaction block, start an implicit block to force this statement
1043 		 * to be grouped together with any following ones.  (We must do this
1044 		 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1045 		 * list would cause later statements to not be grouped.)
1046 		 */
1047 		if (use_implicit_block)
1048 			BeginImplicitTransactionBlock();
1049 
1050 		/* If we got a cancel signal in parsing or prior command, quit */
1051 		CHECK_FOR_INTERRUPTS();
1052 
1053 		/*
1054 		 * Set up a snapshot if parse analysis/planning will need one.
1055 		 */
1056 		if (analyze_requires_snapshot(parsetree))
1057 		{
1058 			PushActiveSnapshot(GetTransactionSnapshot());
1059 			snapshot_set = true;
1060 		}
1061 
1062 		/*
1063 		 * OK to analyze, rewrite, and plan this query.
1064 		 *
1065 		 * Switch to appropriate context for constructing querytrees (again,
1066 		 * these must outlive the execution context).
1067 		 */
1068 		oldcontext = MemoryContextSwitchTo(MessageContext);
1069 
1070 		querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1071 												NULL, 0, NULL);
1072 
1073 		plantree_list = pg_plan_queries(querytree_list,
1074 										CURSOR_OPT_PARALLEL_OK, NULL);
1075 
1076 		/* Done with the snapshot used for parsing/planning */
1077 		if (snapshot_set)
1078 			PopActiveSnapshot();
1079 
1080 		/* If we got a cancel signal in analysis or planning, quit */
1081 		CHECK_FOR_INTERRUPTS();
1082 
1083 		/*
1084 		 * Create unnamed portal to run the query or queries in. If there
1085 		 * already is one, silently drop it.
1086 		 */
1087 		portal = CreatePortal("", true, true);
1088 		/* Don't display the portal in pg_cursors */
1089 		portal->visible = false;
1090 
1091 		/*
1092 		 * We don't have to copy anything into the portal, because everything
1093 		 * we are passing here is in MessageContext, which will outlive the
1094 		 * portal anyway.
1095 		 */
1096 		PortalDefineQuery(portal,
1097 						  NULL,
1098 						  query_string,
1099 						  commandTag,
1100 						  plantree_list,
1101 						  NULL);
1102 
1103 		/*
1104 		 * Start the portal.  No parameters here.
1105 		 */
1106 		PortalStart(portal, NULL, 0, InvalidSnapshot);
1107 
1108 		/*
1109 		 * Select the appropriate output format: text unless we are doing a
1110 		 * FETCH from a binary cursor.  (Pretty grotty to have to do this here
1111 		 * --- but it avoids grottiness in other places.  Ah, the joys of
1112 		 * backward compatibility...)
1113 		 */
1114 		format = 0;				/* TEXT is default */
1115 		if (IsA(parsetree->stmt, FetchStmt))
1116 		{
1117 			FetchStmt  *stmt = (FetchStmt *) parsetree->stmt;
1118 
1119 			if (!stmt->ismove)
1120 			{
1121 				Portal		fportal = GetPortalByName(stmt->portalname);
1122 
1123 				if (PortalIsValid(fportal) &&
1124 					(fportal->cursorOptions & CURSOR_OPT_BINARY))
1125 					format = 1; /* BINARY */
1126 			}
1127 		}
1128 		PortalSetResultFormat(portal, 1, &format);
1129 
1130 		/*
1131 		 * Now we can create the destination receiver object.
1132 		 */
1133 		receiver = CreateDestReceiver(dest);
1134 		if (dest == DestRemote)
1135 			SetRemoteDestReceiverParams(receiver, portal);
1136 
1137 		/*
1138 		 * Switch back to transaction context for execution.
1139 		 */
1140 		MemoryContextSwitchTo(oldcontext);
1141 
1142 		/*
1143 		 * Run the portal to completion, and then drop it (and the receiver).
1144 		 */
1145 		(void) PortalRun(portal,
1146 						 FETCH_ALL,
1147 						 true,	/* always top level */
1148 						 true,
1149 						 receiver,
1150 						 receiver,
1151 						 completionTag);
1152 
1153 		receiver->rDestroy(receiver);
1154 
1155 		PortalDrop(portal, false);
1156 
1157 		if (lnext(parsetree_item) == NULL)
1158 		{
1159 			/*
1160 			 * If this is the last parsetree of the query string, close down
1161 			 * transaction statement before reporting command-complete.  This
1162 			 * is so that any end-of-transaction errors are reported before
1163 			 * the command-complete message is issued, to avoid confusing
1164 			 * clients who will expect either a command-complete message or an
1165 			 * error, not one and then the other.  Also, if we're using an
1166 			 * implicit transaction block, we must close that out first.
1167 			 */
1168 			if (use_implicit_block)
1169 				EndImplicitTransactionBlock();
1170 			finish_xact_command();
1171 		}
1172 		else if (IsA(parsetree->stmt, TransactionStmt))
1173 		{
1174 			/*
1175 			 * If this was a transaction control statement, commit it. We will
1176 			 * start a new xact command for the next command.
1177 			 */
1178 			finish_xact_command();
1179 		}
1180 		else
1181 		{
1182 			/*
1183 			 * We need a CommandCounterIncrement after every query, except
1184 			 * those that start or end a transaction block.
1185 			 */
1186 			CommandCounterIncrement();
1187 		}
1188 
1189 		/*
1190 		 * Tell client that we're done with this query.  Note we emit exactly
1191 		 * one EndCommand report for each raw parsetree, thus one for each SQL
1192 		 * command the client sent, regardless of rewriting. (But a command
1193 		 * aborted by error will not send an EndCommand report at all.)
1194 		 */
1195 		EndCommand(completionTag, dest);
1196 	}							/* end loop over parsetrees */
1197 
1198 	/*
1199 	 * Close down transaction statement, if one is open.  (This will only do
1200 	 * something if the parsetree list was empty; otherwise the last loop
1201 	 * iteration already did it.)
1202 	 */
1203 	finish_xact_command();
1204 
1205 	/*
1206 	 * If there were no parsetrees, return EmptyQueryResponse message.
1207 	 */
1208 	if (!parsetree_list)
1209 		NullCommand(dest);
1210 
1211 	/*
1212 	 * Emit duration logging if appropriate.
1213 	 */
1214 	switch (check_log_duration(msec_str, was_logged))
1215 	{
1216 		case 1:
1217 			ereport(LOG,
1218 					(errmsg("duration: %s ms", msec_str),
1219 					 errhidestmt(true)));
1220 			break;
1221 		case 2:
1222 			ereport(LOG,
1223 					(errmsg("duration: %s ms  statement: %s",
1224 							msec_str, query_string),
1225 					 errhidestmt(true),
1226 					 errdetail_execute(parsetree_list)));
1227 			break;
1228 	}
1229 
1230 	if (save_log_statement_stats)
1231 		ShowUsage("QUERY STATISTICS");
1232 
1233 	TRACE_POSTGRESQL_QUERY_DONE(query_string);
1234 
1235 	debug_query_string = NULL;
1236 }
1237 
1238 /*
1239  * exec_parse_message
1240  *
1241  * Execute a "Parse" protocol message.
1242  */
1243 static void
exec_parse_message(const char * query_string,const char * stmt_name,Oid * paramTypes,int numParams)1244 exec_parse_message(const char *query_string,	/* string to execute */
1245 				   const char *stmt_name,	/* name for prepared stmt */
1246 				   Oid *paramTypes, /* parameter types */
1247 				   int numParams)	/* number of parameters */
1248 {
1249 	MemoryContext unnamed_stmt_context = NULL;
1250 	MemoryContext oldcontext;
1251 	List	   *parsetree_list;
1252 	RawStmt    *raw_parse_tree;
1253 	const char *commandTag;
1254 	List	   *querytree_list;
1255 	CachedPlanSource *psrc;
1256 	bool		is_named;
1257 	bool		save_log_statement_stats = log_statement_stats;
1258 	char		msec_str[32];
1259 
1260 	/*
1261 	 * Report query to various monitoring facilities.
1262 	 */
1263 	debug_query_string = query_string;
1264 
1265 	pgstat_report_activity(STATE_RUNNING, query_string);
1266 
1267 	set_ps_display("PARSE", false);
1268 
1269 	if (save_log_statement_stats)
1270 		ResetUsage();
1271 
1272 	ereport(DEBUG2,
1273 			(errmsg("parse %s: %s",
1274 					*stmt_name ? stmt_name : "<unnamed>",
1275 					query_string)));
1276 
1277 	/*
1278 	 * Start up a transaction command so we can run parse analysis etc. (Note
1279 	 * that this will normally change current memory context.) Nothing happens
1280 	 * if we are already in one.  This also arms the statement timeout if
1281 	 * necessary.
1282 	 */
1283 	start_xact_command();
1284 
1285 	/*
1286 	 * Switch to appropriate context for constructing parsetrees.
1287 	 *
1288 	 * We have two strategies depending on whether the prepared statement is
1289 	 * named or not.  For a named prepared statement, we do parsing in
1290 	 * MessageContext and copy the finished trees into the prepared
1291 	 * statement's plancache entry; then the reset of MessageContext releases
1292 	 * temporary space used by parsing and rewriting. For an unnamed prepared
1293 	 * statement, we assume the statement isn't going to hang around long, so
1294 	 * getting rid of temp space quickly is probably not worth the costs of
1295 	 * copying parse trees.  So in this case, we create the plancache entry's
1296 	 * query_context here, and do all the parsing work therein.
1297 	 */
1298 	is_named = (stmt_name[0] != '\0');
1299 	if (is_named)
1300 	{
1301 		/* Named prepared statement --- parse in MessageContext */
1302 		oldcontext = MemoryContextSwitchTo(MessageContext);
1303 	}
1304 	else
1305 	{
1306 		/* Unnamed prepared statement --- release any prior unnamed stmt */
1307 		drop_unnamed_stmt();
1308 		/* Create context for parsing */
1309 		unnamed_stmt_context =
1310 			AllocSetContextCreate(MessageContext,
1311 								  "unnamed prepared statement",
1312 								  ALLOCSET_DEFAULT_SIZES);
1313 		oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1314 	}
1315 
1316 	/*
1317 	 * Do basic parsing of the query or queries (this should be safe even if
1318 	 * we are in aborted transaction state!)
1319 	 */
1320 	parsetree_list = pg_parse_query(query_string);
1321 
1322 	/*
1323 	 * We only allow a single user statement in a prepared statement. This is
1324 	 * mainly to keep the protocol simple --- otherwise we'd need to worry
1325 	 * about multiple result tupdescs and things like that.
1326 	 */
1327 	if (list_length(parsetree_list) > 1)
1328 		ereport(ERROR,
1329 				(errcode(ERRCODE_SYNTAX_ERROR),
1330 				 errmsg("cannot insert multiple commands into a prepared statement")));
1331 
1332 	if (parsetree_list != NIL)
1333 	{
1334 		Query	   *query;
1335 		bool		snapshot_set = false;
1336 		int			i;
1337 
1338 		raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1339 
1340 		/*
1341 		 * Get the command name for possible use in status display.
1342 		 */
1343 		commandTag = CreateCommandTag(raw_parse_tree->stmt);
1344 
1345 		/*
1346 		 * If we are in an aborted transaction, reject all commands except
1347 		 * COMMIT/ROLLBACK.  It is important that this test occur before we
1348 		 * try to do parse analysis, rewrite, or planning, since all those
1349 		 * phases try to do database accesses, which may fail in abort state.
1350 		 * (It might be safe to allow some additional utility commands in this
1351 		 * state, but not many...)
1352 		 */
1353 		if (IsAbortedTransactionBlockState() &&
1354 			!IsTransactionExitStmt(raw_parse_tree->stmt))
1355 			ereport(ERROR,
1356 					(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1357 					 errmsg("current transaction is aborted, "
1358 							"commands ignored until end of transaction block"),
1359 					 errdetail_abort()));
1360 
1361 		/*
1362 		 * Create the CachedPlanSource before we do parse analysis, since it
1363 		 * needs to see the unmodified raw parse tree.
1364 		 */
1365 		psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1366 
1367 		/*
1368 		 * Set up a snapshot if parse analysis will need one.
1369 		 */
1370 		if (analyze_requires_snapshot(raw_parse_tree))
1371 		{
1372 			PushActiveSnapshot(GetTransactionSnapshot());
1373 			snapshot_set = true;
1374 		}
1375 
1376 		/*
1377 		 * Analyze and rewrite the query.  Note that the originally specified
1378 		 * parameter set is not required to be complete, so we have to use
1379 		 * parse_analyze_varparams().
1380 		 */
1381 		if (log_parser_stats)
1382 			ResetUsage();
1383 
1384 		query = parse_analyze_varparams(raw_parse_tree,
1385 										query_string,
1386 										&paramTypes,
1387 										&numParams);
1388 
1389 		/*
1390 		 * Check all parameter types got determined.
1391 		 */
1392 		for (i = 0; i < numParams; i++)
1393 		{
1394 			Oid			ptype = paramTypes[i];
1395 
1396 			if (ptype == InvalidOid || ptype == UNKNOWNOID)
1397 				ereport(ERROR,
1398 						(errcode(ERRCODE_INDETERMINATE_DATATYPE),
1399 						 errmsg("could not determine data type of parameter $%d",
1400 								i + 1)));
1401 		}
1402 
1403 		if (log_parser_stats)
1404 			ShowUsage("PARSE ANALYSIS STATISTICS");
1405 
1406 		querytree_list = pg_rewrite_query(query);
1407 
1408 		/* Done with the snapshot used for parsing */
1409 		if (snapshot_set)
1410 			PopActiveSnapshot();
1411 	}
1412 	else
1413 	{
1414 		/* Empty input string.  This is legal. */
1415 		raw_parse_tree = NULL;
1416 		commandTag = NULL;
1417 		psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1418 		querytree_list = NIL;
1419 	}
1420 
1421 	/*
1422 	 * CachedPlanSource must be a direct child of MessageContext before we
1423 	 * reparent unnamed_stmt_context under it, else we have a disconnected
1424 	 * circular subgraph.  Klugy, but less so than flipping contexts even more
1425 	 * above.
1426 	 */
1427 	if (unnamed_stmt_context)
1428 		MemoryContextSetParent(psrc->context, MessageContext);
1429 
1430 	/* Finish filling in the CachedPlanSource */
1431 	CompleteCachedPlan(psrc,
1432 					   querytree_list,
1433 					   unnamed_stmt_context,
1434 					   paramTypes,
1435 					   numParams,
1436 					   NULL,
1437 					   NULL,
1438 					   CURSOR_OPT_PARALLEL_OK,	/* allow parallel mode */
1439 					   true);	/* fixed result */
1440 
1441 	/* If we got a cancel signal during analysis, quit */
1442 	CHECK_FOR_INTERRUPTS();
1443 
1444 	if (is_named)
1445 	{
1446 		/*
1447 		 * Store the query as a prepared statement.
1448 		 */
1449 		StorePreparedStatement(stmt_name, psrc, false);
1450 	}
1451 	else
1452 	{
1453 		/*
1454 		 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1455 		 */
1456 		SaveCachedPlan(psrc);
1457 		unnamed_stmt_psrc = psrc;
1458 	}
1459 
1460 	MemoryContextSwitchTo(oldcontext);
1461 
1462 	/*
1463 	 * We do NOT close the open transaction command here; that only happens
1464 	 * when the client sends Sync.  Instead, do CommandCounterIncrement just
1465 	 * in case something happened during parse/plan.
1466 	 */
1467 	CommandCounterIncrement();
1468 
1469 	/*
1470 	 * Send ParseComplete.
1471 	 */
1472 	if (whereToSendOutput == DestRemote)
1473 		pq_putemptymessage('1');
1474 
1475 	/*
1476 	 * Emit duration logging if appropriate.
1477 	 */
1478 	switch (check_log_duration(msec_str, false))
1479 	{
1480 		case 1:
1481 			ereport(LOG,
1482 					(errmsg("duration: %s ms", msec_str),
1483 					 errhidestmt(true)));
1484 			break;
1485 		case 2:
1486 			ereport(LOG,
1487 					(errmsg("duration: %s ms  parse %s: %s",
1488 							msec_str,
1489 							*stmt_name ? stmt_name : "<unnamed>",
1490 							query_string),
1491 					 errhidestmt(true)));
1492 			break;
1493 	}
1494 
1495 	if (save_log_statement_stats)
1496 		ShowUsage("PARSE MESSAGE STATISTICS");
1497 
1498 	debug_query_string = NULL;
1499 }
1500 
1501 /*
1502  * exec_bind_message
1503  *
1504  * Process a "Bind" message to create a portal from a prepared statement
1505  */
1506 static void
exec_bind_message(StringInfo input_message)1507 exec_bind_message(StringInfo input_message)
1508 {
1509 	const char *portal_name;
1510 	const char *stmt_name;
1511 	int			numPFormats;
1512 	int16	   *pformats = NULL;
1513 	int			numParams;
1514 	int			numRFormats;
1515 	int16	   *rformats = NULL;
1516 	CachedPlanSource *psrc;
1517 	CachedPlan *cplan;
1518 	Portal		portal;
1519 	char	   *query_string;
1520 	char	   *saved_stmt_name;
1521 	ParamListInfo params;
1522 	MemoryContext oldContext;
1523 	bool		save_log_statement_stats = log_statement_stats;
1524 	bool		snapshot_set = false;
1525 	char		msec_str[32];
1526 
1527 	/* Get the fixed part of the message */
1528 	portal_name = pq_getmsgstring(input_message);
1529 	stmt_name = pq_getmsgstring(input_message);
1530 
1531 	ereport(DEBUG2,
1532 			(errmsg("bind %s to %s",
1533 					*portal_name ? portal_name : "<unnamed>",
1534 					*stmt_name ? stmt_name : "<unnamed>")));
1535 
1536 	/* Find prepared statement */
1537 	if (stmt_name[0] != '\0')
1538 	{
1539 		PreparedStatement *pstmt;
1540 
1541 		pstmt = FetchPreparedStatement(stmt_name, true);
1542 		psrc = pstmt->plansource;
1543 	}
1544 	else
1545 	{
1546 		/* special-case the unnamed statement */
1547 		psrc = unnamed_stmt_psrc;
1548 		if (!psrc)
1549 			ereport(ERROR,
1550 					(errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1551 					 errmsg("unnamed prepared statement does not exist")));
1552 	}
1553 
1554 	/*
1555 	 * Report query to various monitoring facilities.
1556 	 */
1557 	debug_query_string = psrc->query_string;
1558 
1559 	pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1560 
1561 	set_ps_display("BIND", false);
1562 
1563 	if (save_log_statement_stats)
1564 		ResetUsage();
1565 
1566 	/*
1567 	 * Start up a transaction command so we can call functions etc. (Note that
1568 	 * this will normally change current memory context.) Nothing happens if
1569 	 * we are already in one.  This also arms the statement timeout if
1570 	 * necessary.
1571 	 */
1572 	start_xact_command();
1573 
1574 	/* Switch back to message context */
1575 	MemoryContextSwitchTo(MessageContext);
1576 
1577 	/* Get the parameter format codes */
1578 	numPFormats = pq_getmsgint(input_message, 2);
1579 	if (numPFormats > 0)
1580 	{
1581 		int			i;
1582 
1583 		pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1584 		for (i = 0; i < numPFormats; i++)
1585 			pformats[i] = pq_getmsgint(input_message, 2);
1586 	}
1587 
1588 	/* Get the parameter value count */
1589 	numParams = pq_getmsgint(input_message, 2);
1590 
1591 	if (numPFormats > 1 && numPFormats != numParams)
1592 		ereport(ERROR,
1593 				(errcode(ERRCODE_PROTOCOL_VIOLATION),
1594 				 errmsg("bind message has %d parameter formats but %d parameters",
1595 						numPFormats, numParams)));
1596 
1597 	if (numParams != psrc->num_params)
1598 		ereport(ERROR,
1599 				(errcode(ERRCODE_PROTOCOL_VIOLATION),
1600 				 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1601 						numParams, stmt_name, psrc->num_params)));
1602 
1603 	/*
1604 	 * If we are in aborted transaction state, the only portals we can
1605 	 * actually run are those containing COMMIT or ROLLBACK commands. We
1606 	 * disallow binding anything else to avoid problems with infrastructure
1607 	 * that expects to run inside a valid transaction.  We also disallow
1608 	 * binding any parameters, since we can't risk calling user-defined I/O
1609 	 * functions.
1610 	 */
1611 	if (IsAbortedTransactionBlockState() &&
1612 		(!(psrc->raw_parse_tree &&
1613 		   IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
1614 		 numParams != 0))
1615 		ereport(ERROR,
1616 				(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1617 				 errmsg("current transaction is aborted, "
1618 						"commands ignored until end of transaction block"),
1619 				 errdetail_abort()));
1620 
1621 	/*
1622 	 * Create the portal.  Allow silent replacement of an existing portal only
1623 	 * if the unnamed portal is specified.
1624 	 */
1625 	if (portal_name[0] == '\0')
1626 		portal = CreatePortal(portal_name, true, true);
1627 	else
1628 		portal = CreatePortal(portal_name, false, false);
1629 
1630 	/*
1631 	 * Prepare to copy stuff into the portal's memory context.  We do all this
1632 	 * copying first, because it could possibly fail (out-of-memory) and we
1633 	 * don't want a failure to occur between GetCachedPlan and
1634 	 * PortalDefineQuery; that would result in leaking our plancache refcount.
1635 	 */
1636 	oldContext = MemoryContextSwitchTo(portal->portalContext);
1637 
1638 	/* Copy the plan's query string into the portal */
1639 	query_string = pstrdup(psrc->query_string);
1640 
1641 	/* Likewise make a copy of the statement name, unless it's unnamed */
1642 	if (stmt_name[0])
1643 		saved_stmt_name = pstrdup(stmt_name);
1644 	else
1645 		saved_stmt_name = NULL;
1646 
1647 	/*
1648 	 * Set a snapshot if we have parameters to fetch (since the input
1649 	 * functions might need it) or the query isn't a utility command (and
1650 	 * hence could require redoing parse analysis and planning).  We keep the
1651 	 * snapshot active till we're done, so that plancache.c doesn't have to
1652 	 * take new ones.
1653 	 */
1654 	if (numParams > 0 ||
1655 		(psrc->raw_parse_tree &&
1656 		 analyze_requires_snapshot(psrc->raw_parse_tree)))
1657 	{
1658 		PushActiveSnapshot(GetTransactionSnapshot());
1659 		snapshot_set = true;
1660 	}
1661 
1662 	/*
1663 	 * Fetch parameters, if any, and store in the portal's memory context.
1664 	 */
1665 	if (numParams > 0)
1666 	{
1667 		int			paramno;
1668 
1669 		params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1670 										numParams * sizeof(ParamExternData));
1671 		/* we have static list of params, so no hooks needed */
1672 		params->paramFetch = NULL;
1673 		params->paramFetchArg = NULL;
1674 		params->paramCompile = NULL;
1675 		params->paramCompileArg = NULL;
1676 		params->parserSetup = NULL;
1677 		params->parserSetupArg = NULL;
1678 		params->numParams = numParams;
1679 
1680 		for (paramno = 0; paramno < numParams; paramno++)
1681 		{
1682 			Oid			ptype = psrc->param_types[paramno];
1683 			int32		plength;
1684 			Datum		pval;
1685 			bool		isNull;
1686 			StringInfoData pbuf;
1687 			char		csave;
1688 			int16		pformat;
1689 
1690 			plength = pq_getmsgint(input_message, 4);
1691 			isNull = (plength == -1);
1692 
1693 			if (!isNull)
1694 			{
1695 				const char *pvalue = pq_getmsgbytes(input_message, plength);
1696 
1697 				/*
1698 				 * Rather than copying data around, we just set up a phony
1699 				 * StringInfo pointing to the correct portion of the message
1700 				 * buffer.  We assume we can scribble on the message buffer so
1701 				 * as to maintain the convention that StringInfos have a
1702 				 * trailing null.  This is grotty but is a big win when
1703 				 * dealing with very large parameter strings.
1704 				 */
1705 				pbuf.data = (char *) pvalue;
1706 				pbuf.maxlen = plength + 1;
1707 				pbuf.len = plength;
1708 				pbuf.cursor = 0;
1709 
1710 				csave = pbuf.data[plength];
1711 				pbuf.data[plength] = '\0';
1712 			}
1713 			else
1714 			{
1715 				pbuf.data = NULL;	/* keep compiler quiet */
1716 				csave = 0;
1717 			}
1718 
1719 			if (numPFormats > 1)
1720 				pformat = pformats[paramno];
1721 			else if (numPFormats > 0)
1722 				pformat = pformats[0];
1723 			else
1724 				pformat = 0;	/* default = text */
1725 
1726 			if (pformat == 0)	/* text mode */
1727 			{
1728 				Oid			typinput;
1729 				Oid			typioparam;
1730 				char	   *pstring;
1731 
1732 				getTypeInputInfo(ptype, &typinput, &typioparam);
1733 
1734 				/*
1735 				 * We have to do encoding conversion before calling the
1736 				 * typinput routine.
1737 				 */
1738 				if (isNull)
1739 					pstring = NULL;
1740 				else
1741 					pstring = pg_client_to_server(pbuf.data, plength);
1742 
1743 				pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1744 
1745 				/* Free result of encoding conversion, if any */
1746 				if (pstring && pstring != pbuf.data)
1747 					pfree(pstring);
1748 			}
1749 			else if (pformat == 1)	/* binary mode */
1750 			{
1751 				Oid			typreceive;
1752 				Oid			typioparam;
1753 				StringInfo	bufptr;
1754 
1755 				/*
1756 				 * Call the parameter type's binary input converter
1757 				 */
1758 				getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1759 
1760 				if (isNull)
1761 					bufptr = NULL;
1762 				else
1763 					bufptr = &pbuf;
1764 
1765 				pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1766 
1767 				/* Trouble if it didn't eat the whole buffer */
1768 				if (!isNull && pbuf.cursor != pbuf.len)
1769 					ereport(ERROR,
1770 							(errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1771 							 errmsg("incorrect binary data format in bind parameter %d",
1772 									paramno + 1)));
1773 			}
1774 			else
1775 			{
1776 				ereport(ERROR,
1777 						(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1778 						 errmsg("unsupported format code: %d",
1779 								pformat)));
1780 				pval = 0;		/* keep compiler quiet */
1781 			}
1782 
1783 			/* Restore message buffer contents */
1784 			if (!isNull)
1785 				pbuf.data[plength] = csave;
1786 
1787 			params->params[paramno].value = pval;
1788 			params->params[paramno].isnull = isNull;
1789 
1790 			/*
1791 			 * We mark the params as CONST.  This ensures that any custom plan
1792 			 * makes full use of the parameter values.
1793 			 */
1794 			params->params[paramno].pflags = PARAM_FLAG_CONST;
1795 			params->params[paramno].ptype = ptype;
1796 		}
1797 	}
1798 	else
1799 		params = NULL;
1800 
1801 	/* Done storing stuff in portal's context */
1802 	MemoryContextSwitchTo(oldContext);
1803 
1804 	/* Get the result format codes */
1805 	numRFormats = pq_getmsgint(input_message, 2);
1806 	if (numRFormats > 0)
1807 	{
1808 		int			i;
1809 
1810 		rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1811 		for (i = 0; i < numRFormats; i++)
1812 			rformats[i] = pq_getmsgint(input_message, 2);
1813 	}
1814 
1815 	pq_getmsgend(input_message);
1816 
1817 	/*
1818 	 * Obtain a plan from the CachedPlanSource.  Any cruft from (re)planning
1819 	 * will be generated in MessageContext.  The plan refcount will be
1820 	 * assigned to the Portal, so it will be released at portal destruction.
1821 	 */
1822 	cplan = GetCachedPlan(psrc, params, false, NULL);
1823 
1824 	/*
1825 	 * Now we can define the portal.
1826 	 *
1827 	 * DO NOT put any code that could possibly throw an error between the
1828 	 * above GetCachedPlan call and here.
1829 	 */
1830 	PortalDefineQuery(portal,
1831 					  saved_stmt_name,
1832 					  query_string,
1833 					  psrc->commandTag,
1834 					  cplan->stmt_list,
1835 					  cplan);
1836 
1837 	/* Done with the snapshot used for parameter I/O and parsing/planning */
1838 	if (snapshot_set)
1839 		PopActiveSnapshot();
1840 
1841 	/*
1842 	 * And we're ready to start portal execution.
1843 	 */
1844 	PortalStart(portal, params, 0, InvalidSnapshot);
1845 
1846 	/*
1847 	 * Apply the result format requests to the portal.
1848 	 */
1849 	PortalSetResultFormat(portal, numRFormats, rformats);
1850 
1851 	/*
1852 	 * Send BindComplete.
1853 	 */
1854 	if (whereToSendOutput == DestRemote)
1855 		pq_putemptymessage('2');
1856 
1857 	/*
1858 	 * Emit duration logging if appropriate.
1859 	 */
1860 	switch (check_log_duration(msec_str, false))
1861 	{
1862 		case 1:
1863 			ereport(LOG,
1864 					(errmsg("duration: %s ms", msec_str),
1865 					 errhidestmt(true)));
1866 			break;
1867 		case 2:
1868 			ereport(LOG,
1869 					(errmsg("duration: %s ms  bind %s%s%s: %s",
1870 							msec_str,
1871 							*stmt_name ? stmt_name : "<unnamed>",
1872 							*portal_name ? "/" : "",
1873 							*portal_name ? portal_name : "",
1874 							psrc->query_string),
1875 					 errhidestmt(true),
1876 					 errdetail_params(params)));
1877 			break;
1878 	}
1879 
1880 	if (save_log_statement_stats)
1881 		ShowUsage("BIND MESSAGE STATISTICS");
1882 
1883 	debug_query_string = NULL;
1884 }
1885 
1886 /*
1887  * exec_execute_message
1888  *
1889  * Process an "Execute" message for a portal
1890  */
1891 static void
exec_execute_message(const char * portal_name,long max_rows)1892 exec_execute_message(const char *portal_name, long max_rows)
1893 {
1894 	CommandDest dest;
1895 	DestReceiver *receiver;
1896 	Portal		portal;
1897 	bool		completed;
1898 	char		completionTag[COMPLETION_TAG_BUFSIZE];
1899 	const char *sourceText;
1900 	const char *prepStmtName;
1901 	ParamListInfo portalParams;
1902 	bool		save_log_statement_stats = log_statement_stats;
1903 	bool		is_xact_command;
1904 	bool		execute_is_fetch;
1905 	bool		was_logged = false;
1906 	char		msec_str[32];
1907 
1908 	/* Adjust destination to tell printtup.c what to do */
1909 	dest = whereToSendOutput;
1910 	if (dest == DestRemote)
1911 		dest = DestRemoteExecute;
1912 
1913 	portal = GetPortalByName(portal_name);
1914 	if (!PortalIsValid(portal))
1915 		ereport(ERROR,
1916 				(errcode(ERRCODE_UNDEFINED_CURSOR),
1917 				 errmsg("portal \"%s\" does not exist", portal_name)));
1918 
1919 	/*
1920 	 * If the original query was a null string, just return
1921 	 * EmptyQueryResponse.
1922 	 */
1923 	if (portal->commandTag == NULL)
1924 	{
1925 		Assert(portal->stmts == NIL);
1926 		NullCommand(dest);
1927 		return;
1928 	}
1929 
1930 	/* Does the portal contain a transaction command? */
1931 	is_xact_command = IsTransactionStmtList(portal->stmts);
1932 
1933 	/*
1934 	 * We must copy the sourceText and prepStmtName into MessageContext in
1935 	 * case the portal is destroyed during finish_xact_command. Can avoid the
1936 	 * copy if it's not an xact command, though.
1937 	 */
1938 	if (is_xact_command)
1939 	{
1940 		sourceText = pstrdup(portal->sourceText);
1941 		if (portal->prepStmtName)
1942 			prepStmtName = pstrdup(portal->prepStmtName);
1943 		else
1944 			prepStmtName = "<unnamed>";
1945 
1946 		/*
1947 		 * An xact command shouldn't have any parameters, which is a good
1948 		 * thing because they wouldn't be around after finish_xact_command.
1949 		 */
1950 		portalParams = NULL;
1951 	}
1952 	else
1953 	{
1954 		sourceText = portal->sourceText;
1955 		if (portal->prepStmtName)
1956 			prepStmtName = portal->prepStmtName;
1957 		else
1958 			prepStmtName = "<unnamed>";
1959 		portalParams = portal->portalParams;
1960 	}
1961 
1962 	/*
1963 	 * Report query to various monitoring facilities.
1964 	 */
1965 	debug_query_string = sourceText;
1966 
1967 	pgstat_report_activity(STATE_RUNNING, sourceText);
1968 
1969 	set_ps_display(portal->commandTag, false);
1970 
1971 	if (save_log_statement_stats)
1972 		ResetUsage();
1973 
1974 	BeginCommand(portal->commandTag, dest);
1975 
1976 	/*
1977 	 * Create dest receiver in MessageContext (we don't want it in transaction
1978 	 * context, because that may get deleted if portal contains VACUUM).
1979 	 */
1980 	receiver = CreateDestReceiver(dest);
1981 	if (dest == DestRemoteExecute)
1982 		SetRemoteDestReceiverParams(receiver, portal);
1983 
1984 	/*
1985 	 * Ensure we are in a transaction command (this should normally be the
1986 	 * case already due to prior BIND).
1987 	 */
1988 	start_xact_command();
1989 
1990 	/*
1991 	 * If we re-issue an Execute protocol request against an existing portal,
1992 	 * then we are only fetching more rows rather than completely re-executing
1993 	 * the query from the start. atStart is never reset for a v3 portal, so we
1994 	 * are safe to use this check.
1995 	 */
1996 	execute_is_fetch = !portal->atStart;
1997 
1998 	/* Log immediately if dictated by log_statement */
1999 	if (check_log_statement(portal->stmts))
2000 	{
2001 		ereport(LOG,
2002 				(errmsg("%s %s%s%s: %s",
2003 						execute_is_fetch ?
2004 						_("execute fetch from") :
2005 						_("execute"),
2006 						prepStmtName,
2007 						*portal_name ? "/" : "",
2008 						*portal_name ? portal_name : "",
2009 						sourceText),
2010 				 errhidestmt(true),
2011 				 errdetail_params(portalParams)));
2012 		was_logged = true;
2013 	}
2014 
2015 	/*
2016 	 * If we are in aborted transaction state, the only portals we can
2017 	 * actually run are those containing COMMIT or ROLLBACK commands.
2018 	 */
2019 	if (IsAbortedTransactionBlockState() &&
2020 		!IsTransactionExitStmtList(portal->stmts))
2021 		ereport(ERROR,
2022 				(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2023 				 errmsg("current transaction is aborted, "
2024 						"commands ignored until end of transaction block"),
2025 				 errdetail_abort()));
2026 
2027 	/* Check for cancel signal before we start execution */
2028 	CHECK_FOR_INTERRUPTS();
2029 
2030 	/*
2031 	 * Okay to run the portal.
2032 	 */
2033 	if (max_rows <= 0)
2034 		max_rows = FETCH_ALL;
2035 
2036 	completed = PortalRun(portal,
2037 						  max_rows,
2038 						  true, /* always top level */
2039 						  !execute_is_fetch && max_rows == FETCH_ALL,
2040 						  receiver,
2041 						  receiver,
2042 						  completionTag);
2043 
2044 	receiver->rDestroy(receiver);
2045 
2046 	if (completed)
2047 	{
2048 		if (is_xact_command)
2049 		{
2050 			/*
2051 			 * If this was a transaction control statement, commit it.  We
2052 			 * will start a new xact command for the next command (if any).
2053 			 */
2054 			finish_xact_command();
2055 		}
2056 		else
2057 		{
2058 			/*
2059 			 * We need a CommandCounterIncrement after every query, except
2060 			 * those that start or end a transaction block.
2061 			 */
2062 			CommandCounterIncrement();
2063 
2064 			/* full command has been executed, reset timeout */
2065 			disable_statement_timeout();
2066 		}
2067 
2068 		/* Send appropriate CommandComplete to client */
2069 		EndCommand(completionTag, dest);
2070 	}
2071 	else
2072 	{
2073 		/* Portal run not complete, so send PortalSuspended */
2074 		if (whereToSendOutput == DestRemote)
2075 			pq_putemptymessage('s');
2076 	}
2077 
2078 	/*
2079 	 * Emit duration logging if appropriate.
2080 	 */
2081 	switch (check_log_duration(msec_str, was_logged))
2082 	{
2083 		case 1:
2084 			ereport(LOG,
2085 					(errmsg("duration: %s ms", msec_str),
2086 					 errhidestmt(true)));
2087 			break;
2088 		case 2:
2089 			ereport(LOG,
2090 					(errmsg("duration: %s ms  %s %s%s%s: %s",
2091 							msec_str,
2092 							execute_is_fetch ?
2093 							_("execute fetch from") :
2094 							_("execute"),
2095 							prepStmtName,
2096 							*portal_name ? "/" : "",
2097 							*portal_name ? portal_name : "",
2098 							sourceText),
2099 					 errhidestmt(true),
2100 					 errdetail_params(portalParams)));
2101 			break;
2102 	}
2103 
2104 	if (save_log_statement_stats)
2105 		ShowUsage("EXECUTE MESSAGE STATISTICS");
2106 
2107 	debug_query_string = NULL;
2108 }
2109 
2110 /*
2111  * check_log_statement
2112  *		Determine whether command should be logged because of log_statement
2113  *
2114  * stmt_list can be either raw grammar output or a list of planned
2115  * statements
2116  */
2117 static bool
check_log_statement(List * stmt_list)2118 check_log_statement(List *stmt_list)
2119 {
2120 	ListCell   *stmt_item;
2121 
2122 	if (log_statement == LOGSTMT_NONE)
2123 		return false;
2124 	if (log_statement == LOGSTMT_ALL)
2125 		return true;
2126 
2127 	/* Else we have to inspect the statement(s) to see whether to log */
2128 	foreach(stmt_item, stmt_list)
2129 	{
2130 		Node	   *stmt = (Node *) lfirst(stmt_item);
2131 
2132 		if (GetCommandLogLevel(stmt) <= log_statement)
2133 			return true;
2134 	}
2135 
2136 	return false;
2137 }
2138 
2139 /*
2140  * check_log_duration
2141  *		Determine whether current command's duration should be logged
2142  *
2143  * Returns:
2144  *		0 if no logging is needed
2145  *		1 if just the duration should be logged
2146  *		2 if duration and query details should be logged
2147  *
2148  * If logging is needed, the duration in msec is formatted into msec_str[],
2149  * which must be a 32-byte buffer.
2150  *
2151  * was_logged should be true if caller already logged query details (this
2152  * essentially prevents 2 from being returned).
2153  */
2154 int
check_log_duration(char * msec_str,bool was_logged)2155 check_log_duration(char *msec_str, bool was_logged)
2156 {
2157 	if (log_duration || log_min_duration_statement >= 0)
2158 	{
2159 		long		secs;
2160 		int			usecs;
2161 		int			msecs;
2162 		bool		exceeded;
2163 
2164 		TimestampDifference(GetCurrentStatementStartTimestamp(),
2165 							GetCurrentTimestamp(),
2166 							&secs, &usecs);
2167 		msecs = usecs / 1000;
2168 
2169 		/*
2170 		 * This odd-looking test for log_min_duration_statement being exceeded
2171 		 * is designed to avoid integer overflow with very long durations:
2172 		 * don't compute secs * 1000 until we've verified it will fit in int.
2173 		 */
2174 		exceeded = (log_min_duration_statement == 0 ||
2175 					(log_min_duration_statement > 0 &&
2176 					 (secs > log_min_duration_statement / 1000 ||
2177 					  secs * 1000 + msecs >= log_min_duration_statement)));
2178 
2179 		if (exceeded || log_duration)
2180 		{
2181 			snprintf(msec_str, 32, "%ld.%03d",
2182 					 secs * 1000 + msecs, usecs % 1000);
2183 			if (exceeded && !was_logged)
2184 				return 2;
2185 			else
2186 				return 1;
2187 		}
2188 	}
2189 
2190 	return 0;
2191 }
2192 
2193 /*
2194  * errdetail_execute
2195  *
2196  * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2197  * The argument is the raw parsetree list.
2198  */
2199 static int
errdetail_execute(List * raw_parsetree_list)2200 errdetail_execute(List *raw_parsetree_list)
2201 {
2202 	ListCell   *parsetree_item;
2203 
2204 	foreach(parsetree_item, raw_parsetree_list)
2205 	{
2206 		RawStmt    *parsetree = lfirst_node(RawStmt, parsetree_item);
2207 
2208 		if (IsA(parsetree->stmt, ExecuteStmt))
2209 		{
2210 			ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2211 			PreparedStatement *pstmt;
2212 
2213 			pstmt = FetchPreparedStatement(stmt->name, false);
2214 			if (pstmt)
2215 			{
2216 				errdetail("prepare: %s", pstmt->plansource->query_string);
2217 				return 0;
2218 			}
2219 		}
2220 	}
2221 
2222 	return 0;
2223 }
2224 
2225 /*
2226  * errdetail_params
2227  *
2228  * Add an errdetail() line showing bind-parameter data, if available.
2229  */
2230 static int
errdetail_params(ParamListInfo params)2231 errdetail_params(ParamListInfo params)
2232 {
2233 	/* We mustn't call user-defined I/O functions when in an aborted xact */
2234 	if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2235 	{
2236 		StringInfoData param_str;
2237 		MemoryContext oldcontext;
2238 		int			paramno;
2239 
2240 		/* This code doesn't support dynamic param lists */
2241 		Assert(params->paramFetch == NULL);
2242 
2243 		/* Make sure any trash is generated in MessageContext */
2244 		oldcontext = MemoryContextSwitchTo(MessageContext);
2245 
2246 		initStringInfo(&param_str);
2247 
2248 		for (paramno = 0; paramno < params->numParams; paramno++)
2249 		{
2250 			ParamExternData *prm = &params->params[paramno];
2251 			Oid			typoutput;
2252 			bool		typisvarlena;
2253 			char	   *pstring;
2254 			char	   *p;
2255 
2256 			appendStringInfo(&param_str, "%s$%d = ",
2257 							 paramno > 0 ? ", " : "",
2258 							 paramno + 1);
2259 
2260 			if (prm->isnull || !OidIsValid(prm->ptype))
2261 			{
2262 				appendStringInfoString(&param_str, "NULL");
2263 				continue;
2264 			}
2265 
2266 			getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2267 
2268 			pstring = OidOutputFunctionCall(typoutput, prm->value);
2269 
2270 			appendStringInfoCharMacro(&param_str, '\'');
2271 			for (p = pstring; *p; p++)
2272 			{
2273 				if (*p == '\'') /* double single quotes */
2274 					appendStringInfoCharMacro(&param_str, *p);
2275 				appendStringInfoCharMacro(&param_str, *p);
2276 			}
2277 			appendStringInfoCharMacro(&param_str, '\'');
2278 
2279 			pfree(pstring);
2280 		}
2281 
2282 		errdetail("parameters: %s", param_str.data);
2283 
2284 		pfree(param_str.data);
2285 
2286 		MemoryContextSwitchTo(oldcontext);
2287 	}
2288 
2289 	return 0;
2290 }
2291 
2292 /*
2293  * errdetail_abort
2294  *
2295  * Add an errdetail() line showing abort reason, if any.
2296  */
2297 static int
errdetail_abort(void)2298 errdetail_abort(void)
2299 {
2300 	if (MyProc->recoveryConflictPending)
2301 		errdetail("abort reason: recovery conflict");
2302 
2303 	return 0;
2304 }
2305 
2306 /*
2307  * errdetail_recovery_conflict
2308  *
2309  * Add an errdetail() line showing conflict source.
2310  */
2311 static int
errdetail_recovery_conflict(void)2312 errdetail_recovery_conflict(void)
2313 {
2314 	switch (RecoveryConflictReason)
2315 	{
2316 		case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2317 			errdetail("User was holding shared buffer pin for too long.");
2318 			break;
2319 		case PROCSIG_RECOVERY_CONFLICT_LOCK:
2320 			errdetail("User was holding a relation lock for too long.");
2321 			break;
2322 		case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2323 			errdetail("User was or might have been using tablespace that must be dropped.");
2324 			break;
2325 		case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2326 			errdetail("User query might have needed to see row versions that must be removed.");
2327 			break;
2328 		case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2329 			errdetail("User transaction caused buffer deadlock with recovery.");
2330 			break;
2331 		case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2332 			errdetail("User was connected to a database that must be dropped.");
2333 			break;
2334 		default:
2335 			break;
2336 			/* no errdetail */
2337 	}
2338 
2339 	return 0;
2340 }
2341 
2342 /*
2343  * exec_describe_statement_message
2344  *
2345  * Process a "Describe" message for a prepared statement
2346  */
2347 static void
exec_describe_statement_message(const char * stmt_name)2348 exec_describe_statement_message(const char *stmt_name)
2349 {
2350 	CachedPlanSource *psrc;
2351 	int			i;
2352 
2353 	/*
2354 	 * Start up a transaction command. (Note that this will normally change
2355 	 * current memory context.) Nothing happens if we are already in one.
2356 	 */
2357 	start_xact_command();
2358 
2359 	/* Switch back to message context */
2360 	MemoryContextSwitchTo(MessageContext);
2361 
2362 	/* Find prepared statement */
2363 	if (stmt_name[0] != '\0')
2364 	{
2365 		PreparedStatement *pstmt;
2366 
2367 		pstmt = FetchPreparedStatement(stmt_name, true);
2368 		psrc = pstmt->plansource;
2369 	}
2370 	else
2371 	{
2372 		/* special-case the unnamed statement */
2373 		psrc = unnamed_stmt_psrc;
2374 		if (!psrc)
2375 			ereport(ERROR,
2376 					(errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2377 					 errmsg("unnamed prepared statement does not exist")));
2378 	}
2379 
2380 	/* Prepared statements shouldn't have changeable result descs */
2381 	Assert(psrc->fixed_result);
2382 
2383 	/*
2384 	 * If we are in aborted transaction state, we can't run
2385 	 * SendRowDescriptionMessage(), because that needs catalog accesses.
2386 	 * Hence, refuse to Describe statements that return data.  (We shouldn't
2387 	 * just refuse all Describes, since that might break the ability of some
2388 	 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2389 	 * blindly Describes whatever it does.)  We can Describe parameters
2390 	 * without doing anything dangerous, so we don't restrict that.
2391 	 */
2392 	if (IsAbortedTransactionBlockState() &&
2393 		psrc->resultDesc)
2394 		ereport(ERROR,
2395 				(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2396 				 errmsg("current transaction is aborted, "
2397 						"commands ignored until end of transaction block"),
2398 				 errdetail_abort()));
2399 
2400 	if (whereToSendOutput != DestRemote)
2401 		return;					/* can't actually do anything... */
2402 
2403 	/*
2404 	 * First describe the parameters...
2405 	 */
2406 	pq_beginmessage_reuse(&row_description_buf, 't');	/* parameter description
2407 														 * message type */
2408 	pq_sendint16(&row_description_buf, psrc->num_params);
2409 
2410 	for (i = 0; i < psrc->num_params; i++)
2411 	{
2412 		Oid			ptype = psrc->param_types[i];
2413 
2414 		pq_sendint32(&row_description_buf, (int) ptype);
2415 	}
2416 	pq_endmessage_reuse(&row_description_buf);
2417 
2418 	/*
2419 	 * Next send RowDescription or NoData to describe the result...
2420 	 */
2421 	if (psrc->resultDesc)
2422 	{
2423 		List	   *tlist;
2424 
2425 		/* Get the plan's primary targetlist */
2426 		tlist = CachedPlanGetTargetList(psrc, NULL);
2427 
2428 		SendRowDescriptionMessage(&row_description_buf,
2429 								  psrc->resultDesc,
2430 								  tlist,
2431 								  NULL);
2432 	}
2433 	else
2434 		pq_putemptymessage('n');	/* NoData */
2435 
2436 }
2437 
2438 /*
2439  * exec_describe_portal_message
2440  *
2441  * Process a "Describe" message for a portal
2442  */
2443 static void
exec_describe_portal_message(const char * portal_name)2444 exec_describe_portal_message(const char *portal_name)
2445 {
2446 	Portal		portal;
2447 
2448 	/*
2449 	 * Start up a transaction command. (Note that this will normally change
2450 	 * current memory context.) Nothing happens if we are already in one.
2451 	 */
2452 	start_xact_command();
2453 
2454 	/* Switch back to message context */
2455 	MemoryContextSwitchTo(MessageContext);
2456 
2457 	portal = GetPortalByName(portal_name);
2458 	if (!PortalIsValid(portal))
2459 		ereport(ERROR,
2460 				(errcode(ERRCODE_UNDEFINED_CURSOR),
2461 				 errmsg("portal \"%s\" does not exist", portal_name)));
2462 
2463 	/*
2464 	 * If we are in aborted transaction state, we can't run
2465 	 * SendRowDescriptionMessage(), because that needs catalog accesses.
2466 	 * Hence, refuse to Describe portals that return data.  (We shouldn't just
2467 	 * refuse all Describes, since that might break the ability of some
2468 	 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2469 	 * blindly Describes whatever it does.)
2470 	 */
2471 	if (IsAbortedTransactionBlockState() &&
2472 		portal->tupDesc)
2473 		ereport(ERROR,
2474 				(errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2475 				 errmsg("current transaction is aborted, "
2476 						"commands ignored until end of transaction block"),
2477 				 errdetail_abort()));
2478 
2479 	if (whereToSendOutput != DestRemote)
2480 		return;					/* can't actually do anything... */
2481 
2482 	if (portal->tupDesc)
2483 		SendRowDescriptionMessage(&row_description_buf,
2484 								  portal->tupDesc,
2485 								  FetchPortalTargetList(portal),
2486 								  portal->formats);
2487 	else
2488 		pq_putemptymessage('n');	/* NoData */
2489 }
2490 
2491 
2492 /*
2493  * Convenience routines for starting/committing a single command.
2494  */
2495 static void
start_xact_command(void)2496 start_xact_command(void)
2497 {
2498 	if (!xact_started)
2499 	{
2500 		StartTransactionCommand();
2501 
2502 		xact_started = true;
2503 	}
2504 
2505 	/*
2506 	 * Start statement timeout if necessary.  Note that this'll intentionally
2507 	 * not reset the clock on an already started timeout, to avoid the timing
2508 	 * overhead when start_xact_command() is invoked repeatedly, without an
2509 	 * interceding finish_xact_command() (e.g. parse/bind/execute).  If that's
2510 	 * not desired, the timeout has to be disabled explicitly.
2511 	 */
2512 	enable_statement_timeout();
2513 }
2514 
2515 static void
finish_xact_command(void)2516 finish_xact_command(void)
2517 {
2518 	/* cancel active statement timeout after each command */
2519 	disable_statement_timeout();
2520 
2521 	if (xact_started)
2522 	{
2523 		CommitTransactionCommand();
2524 
2525 #ifdef MEMORY_CONTEXT_CHECKING
2526 		/* Check all memory contexts that weren't freed during commit */
2527 		/* (those that were, were checked before being deleted) */
2528 		MemoryContextCheck(TopMemoryContext);
2529 #endif
2530 
2531 #ifdef SHOW_MEMORY_STATS
2532 		/* Print mem stats after each commit for leak tracking */
2533 		MemoryContextStats(TopMemoryContext);
2534 #endif
2535 
2536 		xact_started = false;
2537 	}
2538 }
2539 
2540 
2541 /*
2542  * Convenience routines for checking whether a statement is one of the
2543  * ones that we allow in transaction-aborted state.
2544  */
2545 
2546 /* Test a bare parsetree */
2547 static bool
IsTransactionExitStmt(Node * parsetree)2548 IsTransactionExitStmt(Node *parsetree)
2549 {
2550 	if (parsetree && IsA(parsetree, TransactionStmt))
2551 	{
2552 		TransactionStmt *stmt = (TransactionStmt *) parsetree;
2553 
2554 		if (stmt->kind == TRANS_STMT_COMMIT ||
2555 			stmt->kind == TRANS_STMT_PREPARE ||
2556 			stmt->kind == TRANS_STMT_ROLLBACK ||
2557 			stmt->kind == TRANS_STMT_ROLLBACK_TO)
2558 			return true;
2559 	}
2560 	return false;
2561 }
2562 
2563 /* Test a list that contains PlannedStmt nodes */
2564 static bool
IsTransactionExitStmtList(List * pstmts)2565 IsTransactionExitStmtList(List *pstmts)
2566 {
2567 	if (list_length(pstmts) == 1)
2568 	{
2569 		PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2570 
2571 		if (pstmt->commandType == CMD_UTILITY &&
2572 			IsTransactionExitStmt(pstmt->utilityStmt))
2573 			return true;
2574 	}
2575 	return false;
2576 }
2577 
2578 /* Test a list that contains PlannedStmt nodes */
2579 static bool
IsTransactionStmtList(List * pstmts)2580 IsTransactionStmtList(List *pstmts)
2581 {
2582 	if (list_length(pstmts) == 1)
2583 	{
2584 		PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2585 
2586 		if (pstmt->commandType == CMD_UTILITY &&
2587 			IsA(pstmt->utilityStmt, TransactionStmt))
2588 			return true;
2589 	}
2590 	return false;
2591 }
2592 
2593 /* Release any existing unnamed prepared statement */
2594 static void
drop_unnamed_stmt(void)2595 drop_unnamed_stmt(void)
2596 {
2597 	/* paranoia to avoid a dangling pointer in case of error */
2598 	if (unnamed_stmt_psrc)
2599 	{
2600 		CachedPlanSource *psrc = unnamed_stmt_psrc;
2601 
2602 		unnamed_stmt_psrc = NULL;
2603 		DropCachedPlan(psrc);
2604 	}
2605 }
2606 
2607 
2608 /* --------------------------------
2609  *		signal handler routines used in PostgresMain()
2610  * --------------------------------
2611  */
2612 
2613 /*
2614  * quickdie() occurs when signalled SIGQUIT by the postmaster.
2615  *
2616  * Some backend has bought the farm,
2617  * so we need to stop what we're doing and exit.
2618  */
2619 void
quickdie(SIGNAL_ARGS)2620 quickdie(SIGNAL_ARGS)
2621 {
2622 	sigaddset(&BlockSig, SIGQUIT);	/* prevent nested calls */
2623 	PG_SETMASK(&BlockSig);
2624 
2625 	/*
2626 	 * Prevent interrupts while exiting; though we just blocked signals that
2627 	 * would queue new interrupts, one may have been pending.  We don't want a
2628 	 * quickdie() downgraded to a mere query cancel.
2629 	 */
2630 	HOLD_INTERRUPTS();
2631 
2632 	/*
2633 	 * If we're aborting out of client auth, don't risk trying to send
2634 	 * anything to the client; we will likely violate the protocol, not to
2635 	 * mention that we may have interrupted the guts of OpenSSL or some
2636 	 * authentication library.
2637 	 */
2638 	if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2639 		whereToSendOutput = DestNone;
2640 
2641 	/*
2642 	 * Notify the client before exiting, to give a clue on what happened.
2643 	 *
2644 	 * It's dubious to call ereport() from a signal handler.  It is certainly
2645 	 * not async-signal safe.  But it seems better to try, than to disconnect
2646 	 * abruptly and leave the client wondering what happened.  It's remotely
2647 	 * possible that we crash or hang while trying to send the message, but
2648 	 * receiving a SIGQUIT is a sign that something has already gone badly
2649 	 * wrong, so there's not much to lose.  Assuming the postmaster is still
2650 	 * running, it will SIGKILL us soon if we get stuck for some reason.
2651 	 *
2652 	 * Ideally this should be ereport(FATAL), but then we'd not get control
2653 	 * back...
2654 	 */
2655 	ereport(WARNING,
2656 			(errcode(ERRCODE_CRASH_SHUTDOWN),
2657 			 errmsg("terminating connection because of crash of another server process"),
2658 			 errdetail("The postmaster has commanded this server process to roll back"
2659 					   " the current transaction and exit, because another"
2660 					   " server process exited abnormally and possibly corrupted"
2661 					   " shared memory."),
2662 			 errhint("In a moment you should be able to reconnect to the"
2663 					 " database and repeat your command.")));
2664 
2665 	/*
2666 	 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2667 	 * because shared memory may be corrupted, so we don't want to try to
2668 	 * clean up our transaction.  Just nail the windows shut and get out of
2669 	 * town.  The callbacks wouldn't be safe to run from a signal handler,
2670 	 * anyway.
2671 	 *
2672 	 * Note we do _exit(2) not _exit(0).  This is to force the postmaster into
2673 	 * a system reset cycle if someone sends a manual SIGQUIT to a random
2674 	 * backend.  This is necessary precisely because we don't clean up our
2675 	 * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
2676 	 * should ensure the postmaster sees this as a crash, too, but no harm in
2677 	 * being doubly sure.)
2678 	 */
2679 	_exit(2);
2680 }
2681 
2682 /*
2683  * Shutdown signal from postmaster: abort transaction and exit
2684  * at soonest convenient time
2685  */
2686 void
die(SIGNAL_ARGS)2687 die(SIGNAL_ARGS)
2688 {
2689 	int			save_errno = errno;
2690 
2691 	/* Don't joggle the elbow of proc_exit */
2692 	if (!proc_exit_inprogress)
2693 	{
2694 		InterruptPending = true;
2695 		ProcDiePending = true;
2696 	}
2697 
2698 	/* If we're still here, waken anything waiting on the process latch */
2699 	SetLatch(MyLatch);
2700 
2701 	/*
2702 	 * If we're in single user mode, we want to quit immediately - we can't
2703 	 * rely on latches as they wouldn't work when stdin/stdout is a file.
2704 	 * Rather ugly, but it's unlikely to be worthwhile to invest much more
2705 	 * effort just for the benefit of single user mode.
2706 	 */
2707 	if (DoingCommandRead && whereToSendOutput != DestRemote)
2708 		ProcessInterrupts();
2709 
2710 	errno = save_errno;
2711 }
2712 
2713 /*
2714  * Query-cancel signal from postmaster: abort current transaction
2715  * at soonest convenient time
2716  */
2717 void
StatementCancelHandler(SIGNAL_ARGS)2718 StatementCancelHandler(SIGNAL_ARGS)
2719 {
2720 	int			save_errno = errno;
2721 
2722 	/*
2723 	 * Don't joggle the elbow of proc_exit
2724 	 */
2725 	if (!proc_exit_inprogress)
2726 	{
2727 		InterruptPending = true;
2728 		QueryCancelPending = true;
2729 	}
2730 
2731 	/* If we're still here, waken anything waiting on the process latch */
2732 	SetLatch(MyLatch);
2733 
2734 	errno = save_errno;
2735 }
2736 
2737 /* signal handler for floating point exception */
2738 void
FloatExceptionHandler(SIGNAL_ARGS)2739 FloatExceptionHandler(SIGNAL_ARGS)
2740 {
2741 	/* We're not returning, so no need to save errno */
2742 	ereport(ERROR,
2743 			(errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2744 			 errmsg("floating-point exception"),
2745 			 errdetail("An invalid floating-point operation was signaled. "
2746 					   "This probably means an out-of-range result or an "
2747 					   "invalid operation, such as division by zero.")));
2748 }
2749 
2750 /*
2751  * SIGHUP: set flag to re-read config file at next convenient time.
2752  *
2753  * Sets the ConfigReloadPending flag, which should be checked at convenient
2754  * places inside main loops. (Better than doing the reading in the signal
2755  * handler, ey?)
2756  */
2757 void
PostgresSigHupHandler(SIGNAL_ARGS)2758 PostgresSigHupHandler(SIGNAL_ARGS)
2759 {
2760 	int			save_errno = errno;
2761 
2762 	ConfigReloadPending = true;
2763 	SetLatch(MyLatch);
2764 
2765 	errno = save_errno;
2766 }
2767 
2768 /*
2769  * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2770  * handling following receipt of SIGUSR1. Designed to be similar to die()
2771  * and StatementCancelHandler(). Called only by a normal user backend
2772  * that begins a transaction during recovery.
2773  */
2774 void
RecoveryConflictInterrupt(ProcSignalReason reason)2775 RecoveryConflictInterrupt(ProcSignalReason reason)
2776 {
2777 	int			save_errno = errno;
2778 
2779 	/*
2780 	 * Don't joggle the elbow of proc_exit
2781 	 */
2782 	if (!proc_exit_inprogress)
2783 	{
2784 		RecoveryConflictReason = reason;
2785 		switch (reason)
2786 		{
2787 			case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2788 
2789 				/*
2790 				 * If we aren't waiting for a lock we can never deadlock.
2791 				 */
2792 				if (!IsWaitingForLock())
2793 					return;
2794 
2795 				/* Intentional fall through to check wait for pin */
2796 				/* FALLTHROUGH */
2797 
2798 			case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2799 
2800 				/*
2801 				 * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
2802 				 * aren't blocking the Startup process there is nothing more
2803 				 * to do.
2804 				 *
2805 				 * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is
2806 				 * requested, if we're waiting for locks and the startup
2807 				 * process is not waiting for buffer pin (i.e., also waiting
2808 				 * for locks), we set the flag so that ProcSleep() will check
2809 				 * for deadlocks.
2810 				 */
2811 				if (!HoldingBufferPinThatDelaysRecovery())
2812 				{
2813 					if (reason == PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK &&
2814 						GetStartupBufferPinWaitBufId() < 0)
2815 						CheckDeadLockAlert();
2816 					return;
2817 				}
2818 
2819 				MyProc->recoveryConflictPending = true;
2820 
2821 				/* Intentional fall through to error handling */
2822 				/* FALLTHROUGH */
2823 
2824 			case PROCSIG_RECOVERY_CONFLICT_LOCK:
2825 			case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2826 			case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2827 
2828 				/*
2829 				 * If we aren't in a transaction any longer then ignore.
2830 				 */
2831 				if (!IsTransactionOrTransactionBlock())
2832 					return;
2833 
2834 				/*
2835 				 * If we can abort just the current subtransaction then we are
2836 				 * OK to throw an ERROR to resolve the conflict. Otherwise
2837 				 * drop through to the FATAL case.
2838 				 *
2839 				 * XXX other times that we can throw just an ERROR *may* be
2840 				 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2841 				 * parent transactions
2842 				 *
2843 				 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2844 				 * by parent transactions and the transaction is not
2845 				 * transaction-snapshot mode
2846 				 *
2847 				 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2848 				 * cursors open in parent transactions
2849 				 */
2850 				if (!IsSubTransaction())
2851 				{
2852 					/*
2853 					 * If we already aborted then we no longer need to cancel.
2854 					 * We do this here since we do not wish to ignore aborted
2855 					 * subtransactions, which must cause FATAL, currently.
2856 					 */
2857 					if (IsAbortedTransactionBlockState())
2858 						return;
2859 
2860 					RecoveryConflictPending = true;
2861 					QueryCancelPending = true;
2862 					InterruptPending = true;
2863 					break;
2864 				}
2865 
2866 				/* Intentional fall through to session cancel */
2867 				/* FALLTHROUGH */
2868 
2869 			case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2870 				RecoveryConflictPending = true;
2871 				ProcDiePending = true;
2872 				InterruptPending = true;
2873 				break;
2874 
2875 			default:
2876 				elog(FATAL, "unrecognized conflict mode: %d",
2877 					 (int) reason);
2878 		}
2879 
2880 		Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
2881 
2882 		/*
2883 		 * All conflicts apart from database cause dynamic errors where the
2884 		 * command or transaction can be retried at a later point with some
2885 		 * potential for success. No need to reset this, since non-retryable
2886 		 * conflict errors are currently FATAL.
2887 		 */
2888 		if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2889 			RecoveryConflictRetryable = false;
2890 	}
2891 
2892 	/*
2893 	 * Set the process latch. This function essentially emulates signal
2894 	 * handlers like die() and StatementCancelHandler() and it seems prudent
2895 	 * to behave similarly as they do.
2896 	 */
2897 	SetLatch(MyLatch);
2898 
2899 	errno = save_errno;
2900 }
2901 
2902 /*
2903  * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2904  *
2905  * If an interrupt condition is pending, and it's safe to service it,
2906  * then clear the flag and accept the interrupt.  Called only when
2907  * InterruptPending is true.
2908  *
2909  * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
2910  * is guaranteed to clear the InterruptPending flag before returning.
2911  * (This is not the same as guaranteeing that it's still clear when we
2912  * return; another interrupt could have arrived.  But we promise that
2913  * any pre-existing one will have been serviced.)
2914  */
2915 void
ProcessInterrupts(void)2916 ProcessInterrupts(void)
2917 {
2918 	/* OK to accept any interrupts now? */
2919 	if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2920 		return;
2921 	InterruptPending = false;
2922 
2923 	if (ProcDiePending)
2924 	{
2925 		ProcDiePending = false;
2926 		QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2927 		LockErrorCleanup();
2928 		/* As in quickdie, don't risk sending to client during auth */
2929 		if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2930 			whereToSendOutput = DestNone;
2931 		if (ClientAuthInProgress)
2932 			ereport(FATAL,
2933 					(errcode(ERRCODE_QUERY_CANCELED),
2934 					 errmsg("canceling authentication due to timeout")));
2935 		else if (IsAutoVacuumWorkerProcess())
2936 			ereport(FATAL,
2937 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
2938 					 errmsg("terminating autovacuum process due to administrator command")));
2939 		else if (IsLogicalWorker())
2940 			ereport(FATAL,
2941 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
2942 					 errmsg("terminating logical replication worker due to administrator command")));
2943 		else if (IsLogicalLauncher())
2944 		{
2945 			ereport(DEBUG1,
2946 					(errmsg("logical replication launcher shutting down")));
2947 
2948 			/*
2949 			 * The logical replication launcher can be stopped at any time.
2950 			 * Use exit status 1 so the background worker is restarted.
2951 			 */
2952 			proc_exit(1);
2953 		}
2954 		else if (RecoveryConflictPending && RecoveryConflictRetryable)
2955 		{
2956 			pgstat_report_recovery_conflict(RecoveryConflictReason);
2957 			ereport(FATAL,
2958 					(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2959 					 errmsg("terminating connection due to conflict with recovery"),
2960 					 errdetail_recovery_conflict()));
2961 		}
2962 		else if (RecoveryConflictPending)
2963 		{
2964 			/* Currently there is only one non-retryable recovery conflict */
2965 			Assert(RecoveryConflictReason == PROCSIG_RECOVERY_CONFLICT_DATABASE);
2966 			pgstat_report_recovery_conflict(RecoveryConflictReason);
2967 			ereport(FATAL,
2968 					(errcode(ERRCODE_DATABASE_DROPPED),
2969 					 errmsg("terminating connection due to conflict with recovery"),
2970 					 errdetail_recovery_conflict()));
2971 		}
2972 		else
2973 			ereport(FATAL,
2974 					(errcode(ERRCODE_ADMIN_SHUTDOWN),
2975 					 errmsg("terminating connection due to administrator command")));
2976 	}
2977 	if (ClientConnectionLost)
2978 	{
2979 		QueryCancelPending = false; /* lost connection trumps QueryCancel */
2980 		LockErrorCleanup();
2981 		/* don't send to client, we already know the connection to be dead. */
2982 		whereToSendOutput = DestNone;
2983 		ereport(FATAL,
2984 				(errcode(ERRCODE_CONNECTION_FAILURE),
2985 				 errmsg("connection to client lost")));
2986 	}
2987 
2988 	/*
2989 	 * If a recovery conflict happens while we are waiting for input from the
2990 	 * client, the client is presumably just sitting idle in a transaction,
2991 	 * preventing recovery from making progress.  Terminate the connection to
2992 	 * dislodge it.
2993 	 */
2994 	if (RecoveryConflictPending && DoingCommandRead)
2995 	{
2996 		QueryCancelPending = false; /* this trumps QueryCancel */
2997 		RecoveryConflictPending = false;
2998 		LockErrorCleanup();
2999 		pgstat_report_recovery_conflict(RecoveryConflictReason);
3000 		ereport(FATAL,
3001 				(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3002 				 errmsg("terminating connection due to conflict with recovery"),
3003 				 errdetail_recovery_conflict(),
3004 				 errhint("In a moment you should be able to reconnect to the"
3005 						 " database and repeat your command.")));
3006 	}
3007 
3008 	/*
3009 	 * Don't allow query cancel interrupts while reading input from the
3010 	 * client, because we might lose sync in the FE/BE protocol.  (Die
3011 	 * interrupts are OK, because we won't read any further messages from the
3012 	 * client in that case.)
3013 	 */
3014 	if (QueryCancelPending && QueryCancelHoldoffCount != 0)
3015 	{
3016 		/*
3017 		 * Re-arm InterruptPending so that we process the cancel request as
3018 		 * soon as we're done reading the message.  (XXX this is seriously
3019 		 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3020 		 * can't use that macro directly as the initial test in this function,
3021 		 * meaning that this code also creates opportunities for other bugs to
3022 		 * appear.)
3023 		 */
3024 		InterruptPending = true;
3025 	}
3026 	else if (QueryCancelPending)
3027 	{
3028 		bool		lock_timeout_occurred;
3029 		bool		stmt_timeout_occurred;
3030 
3031 		QueryCancelPending = false;
3032 
3033 		/*
3034 		 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3035 		 * need to clear both, so always fetch both.
3036 		 */
3037 		lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3038 		stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3039 
3040 		/*
3041 		 * If both were set, we want to report whichever timeout completed
3042 		 * earlier; this ensures consistent behavior if the machine is slow
3043 		 * enough that the second timeout triggers before we get here.  A tie
3044 		 * is arbitrarily broken in favor of reporting a lock timeout.
3045 		 */
3046 		if (lock_timeout_occurred && stmt_timeout_occurred &&
3047 			get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
3048 			lock_timeout_occurred = false;	/* report stmt timeout */
3049 
3050 		if (lock_timeout_occurred)
3051 		{
3052 			LockErrorCleanup();
3053 			ereport(ERROR,
3054 					(errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3055 					 errmsg("canceling statement due to lock timeout")));
3056 		}
3057 		if (stmt_timeout_occurred)
3058 		{
3059 			LockErrorCleanup();
3060 			ereport(ERROR,
3061 					(errcode(ERRCODE_QUERY_CANCELED),
3062 					 errmsg("canceling statement due to statement timeout")));
3063 		}
3064 		if (IsAutoVacuumWorkerProcess())
3065 		{
3066 			LockErrorCleanup();
3067 			ereport(ERROR,
3068 					(errcode(ERRCODE_QUERY_CANCELED),
3069 					 errmsg("canceling autovacuum task")));
3070 		}
3071 		if (RecoveryConflictPending)
3072 		{
3073 			RecoveryConflictPending = false;
3074 			LockErrorCleanup();
3075 			pgstat_report_recovery_conflict(RecoveryConflictReason);
3076 			ereport(ERROR,
3077 					(errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3078 					 errmsg("canceling statement due to conflict with recovery"),
3079 					 errdetail_recovery_conflict()));
3080 		}
3081 
3082 		/*
3083 		 * If we are reading a command from the client, just ignore the cancel
3084 		 * request --- sending an extra error message won't accomplish
3085 		 * anything.  Otherwise, go ahead and throw the error.
3086 		 */
3087 		if (!DoingCommandRead)
3088 		{
3089 			LockErrorCleanup();
3090 			ereport(ERROR,
3091 					(errcode(ERRCODE_QUERY_CANCELED),
3092 					 errmsg("canceling statement due to user request")));
3093 		}
3094 	}
3095 
3096 	if (IdleInTransactionSessionTimeoutPending)
3097 	{
3098 		/* Has the timeout setting changed since last we looked? */
3099 		if (IdleInTransactionSessionTimeout > 0)
3100 			ereport(FATAL,
3101 					(errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3102 					 errmsg("terminating connection due to idle-in-transaction timeout")));
3103 		else
3104 			IdleInTransactionSessionTimeoutPending = false;
3105 
3106 	}
3107 
3108 	if (ParallelMessagePending)
3109 		HandleParallelMessages();
3110 }
3111 
3112 
3113 /*
3114  * IA64-specific code to fetch the AR.BSP register for stack depth checks.
3115  *
3116  * We currently support gcc, icc, and HP-UX's native compiler here.
3117  *
3118  * Note: while icc accepts gcc asm blocks on x86[_64], this is not true on
3119  * ia64 (at least not in icc versions before 12.x).  So we have to carry a
3120  * separate implementation for it.
3121  */
3122 #if defined(__ia64__) || defined(__ia64)
3123 
3124 #if defined(__hpux) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
3125 /* Assume it's HP-UX native compiler */
3126 #include <ia64/sys/inline.h>
3127 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3128 #elif defined(__INTEL_COMPILER)
3129 /* icc */
3130 #include <asm/ia64regs.h>
3131 #define ia64_get_bsp() ((char *) __getReg(_IA64_REG_AR_BSP))
3132 #else
3133 /* gcc */
3134 static __inline__ char *
ia64_get_bsp(void)3135 ia64_get_bsp(void)
3136 {
3137 	char	   *ret;
3138 
3139 	/* the ;; is a "stop", seems to be required before fetching BSP */
3140 	__asm__ __volatile__(
3141 						 ";;\n"
3142 						 "	mov	%0=ar.bsp	\n"
3143 :						 "=r"(ret));
3144 
3145 	return ret;
3146 }
3147 #endif
3148 #endif							/* IA64 */
3149 
3150 
3151 /*
3152  * set_stack_base: set up reference point for stack depth checking
3153  *
3154  * Returns the old reference point, if any.
3155  */
3156 pg_stack_base_t
set_stack_base(void)3157 set_stack_base(void)
3158 {
3159 	char		stack_base;
3160 	pg_stack_base_t old;
3161 
3162 #if defined(__ia64__) || defined(__ia64)
3163 	old.stack_base_ptr = stack_base_ptr;
3164 	old.register_stack_base_ptr = register_stack_base_ptr;
3165 #else
3166 	old = stack_base_ptr;
3167 #endif
3168 
3169 	/* Set up reference point for stack depth checking */
3170 	stack_base_ptr = &stack_base;
3171 #if defined(__ia64__) || defined(__ia64)
3172 	register_stack_base_ptr = ia64_get_bsp();
3173 #endif
3174 
3175 	return old;
3176 }
3177 
3178 /*
3179  * restore_stack_base: restore reference point for stack depth checking
3180  *
3181  * This can be used after set_stack_base() to restore the old value. This
3182  * is currently only used in PL/Java. When PL/Java calls a backend function
3183  * from different thread, the thread's stack is at a different location than
3184  * the main thread's stack, so it sets the base pointer before the call, and
3185  * restores it afterwards.
3186  */
3187 void
restore_stack_base(pg_stack_base_t base)3188 restore_stack_base(pg_stack_base_t base)
3189 {
3190 #if defined(__ia64__) || defined(__ia64)
3191 	stack_base_ptr = base.stack_base_ptr;
3192 	register_stack_base_ptr = base.register_stack_base_ptr;
3193 #else
3194 	stack_base_ptr = base;
3195 #endif
3196 }
3197 
3198 /*
3199  * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3200  *
3201  * This should be called someplace in any recursive routine that might possibly
3202  * recurse deep enough to overflow the stack.  Most Unixen treat stack
3203  * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3204  * before hitting the hardware limit.
3205  *
3206  * check_stack_depth() just throws an error summarily.  stack_is_too_deep()
3207  * can be used by code that wants to handle the error condition itself.
3208  */
3209 void
check_stack_depth(void)3210 check_stack_depth(void)
3211 {
3212 	if (stack_is_too_deep())
3213 	{
3214 		ereport(ERROR,
3215 				(errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3216 				 errmsg("stack depth limit exceeded"),
3217 				 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3218 						 "after ensuring the platform's stack depth limit is adequate.",
3219 						 max_stack_depth)));
3220 	}
3221 }
3222 
3223 bool
stack_is_too_deep(void)3224 stack_is_too_deep(void)
3225 {
3226 	char		stack_top_loc;
3227 	long		stack_depth;
3228 
3229 	/*
3230 	 * Compute distance from reference point to my local variables
3231 	 */
3232 	stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3233 
3234 	/*
3235 	 * Take abs value, since stacks grow up on some machines, down on others
3236 	 */
3237 	if (stack_depth < 0)
3238 		stack_depth = -stack_depth;
3239 
3240 	/*
3241 	 * Trouble?
3242 	 *
3243 	 * The test on stack_base_ptr prevents us from erroring out if called
3244 	 * during process setup or in a non-backend process.  Logically it should
3245 	 * be done first, but putting it here avoids wasting cycles during normal
3246 	 * cases.
3247 	 */
3248 	if (stack_depth > max_stack_depth_bytes &&
3249 		stack_base_ptr != NULL)
3250 		return true;
3251 
3252 	/*
3253 	 * On IA64 there is a separate "register" stack that requires its own
3254 	 * independent check.  For this, we have to measure the change in the
3255 	 * "BSP" pointer from PostgresMain to here.  Logic is just as above,
3256 	 * except that we know IA64's register stack grows up.
3257 	 *
3258 	 * Note we assume that the same max_stack_depth applies to both stacks.
3259 	 */
3260 #if defined(__ia64__) || defined(__ia64)
3261 	stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3262 
3263 	if (stack_depth > max_stack_depth_bytes &&
3264 		register_stack_base_ptr != NULL)
3265 		return true;
3266 #endif							/* IA64 */
3267 
3268 	return false;
3269 }
3270 
3271 /* GUC check hook for max_stack_depth */
3272 bool
check_max_stack_depth(int * newval,void ** extra,GucSource source)3273 check_max_stack_depth(int *newval, void **extra, GucSource source)
3274 {
3275 	long		newval_bytes = *newval * 1024L;
3276 	long		stack_rlimit = get_stack_depth_rlimit();
3277 
3278 	if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3279 	{
3280 		GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3281 							(stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3282 		GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3283 		return false;
3284 	}
3285 	return true;
3286 }
3287 
3288 /* GUC assign hook for max_stack_depth */
3289 void
assign_max_stack_depth(int newval,void * extra)3290 assign_max_stack_depth(int newval, void *extra)
3291 {
3292 	long		newval_bytes = newval * 1024L;
3293 
3294 	max_stack_depth_bytes = newval_bytes;
3295 }
3296 
3297 
3298 /*
3299  * set_debug_options --- apply "-d N" command line option
3300  *
3301  * -d is not quite the same as setting log_min_messages because it enables
3302  * other output options.
3303  */
3304 void
set_debug_options(int debug_flag,GucContext context,GucSource source)3305 set_debug_options(int debug_flag, GucContext context, GucSource source)
3306 {
3307 	if (debug_flag > 0)
3308 	{
3309 		char		debugstr[64];
3310 
3311 		sprintf(debugstr, "debug%d", debug_flag);
3312 		SetConfigOption("log_min_messages", debugstr, context, source);
3313 	}
3314 	else
3315 		SetConfigOption("log_min_messages", "notice", context, source);
3316 
3317 	if (debug_flag >= 1 && context == PGC_POSTMASTER)
3318 	{
3319 		SetConfigOption("log_connections", "true", context, source);
3320 		SetConfigOption("log_disconnections", "true", context, source);
3321 	}
3322 	if (debug_flag >= 2)
3323 		SetConfigOption("log_statement", "all", context, source);
3324 	if (debug_flag >= 3)
3325 		SetConfigOption("debug_print_parse", "true", context, source);
3326 	if (debug_flag >= 4)
3327 		SetConfigOption("debug_print_plan", "true", context, source);
3328 	if (debug_flag >= 5)
3329 		SetConfigOption("debug_print_rewritten", "true", context, source);
3330 }
3331 
3332 
3333 bool
set_plan_disabling_options(const char * arg,GucContext context,GucSource source)3334 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3335 {
3336 	const char *tmp = NULL;
3337 
3338 	switch (arg[0])
3339 	{
3340 		case 's':				/* seqscan */
3341 			tmp = "enable_seqscan";
3342 			break;
3343 		case 'i':				/* indexscan */
3344 			tmp = "enable_indexscan";
3345 			break;
3346 		case 'o':				/* indexonlyscan */
3347 			tmp = "enable_indexonlyscan";
3348 			break;
3349 		case 'b':				/* bitmapscan */
3350 			tmp = "enable_bitmapscan";
3351 			break;
3352 		case 't':				/* tidscan */
3353 			tmp = "enable_tidscan";
3354 			break;
3355 		case 'n':				/* nestloop */
3356 			tmp = "enable_nestloop";
3357 			break;
3358 		case 'm':				/* mergejoin */
3359 			tmp = "enable_mergejoin";
3360 			break;
3361 		case 'h':				/* hashjoin */
3362 			tmp = "enable_hashjoin";
3363 			break;
3364 	}
3365 	if (tmp)
3366 	{
3367 		SetConfigOption(tmp, "false", context, source);
3368 		return true;
3369 	}
3370 	else
3371 		return false;
3372 }
3373 
3374 
3375 const char *
get_stats_option_name(const char * arg)3376 get_stats_option_name(const char *arg)
3377 {
3378 	switch (arg[0])
3379 	{
3380 		case 'p':
3381 			if (optarg[1] == 'a')	/* "parser" */
3382 				return "log_parser_stats";
3383 			else if (optarg[1] == 'l')	/* "planner" */
3384 				return "log_planner_stats";
3385 			break;
3386 
3387 		case 'e':				/* "executor" */
3388 			return "log_executor_stats";
3389 			break;
3390 	}
3391 
3392 	return NULL;
3393 }
3394 
3395 
3396 /* ----------------------------------------------------------------
3397  * process_postgres_switches
3398  *	   Parse command line arguments for PostgresMain
3399  *
3400  * This is called twice, once for the "secure" options coming from the
3401  * postmaster or command line, and once for the "insecure" options coming
3402  * from the client's startup packet.  The latter have the same syntax but
3403  * may be restricted in what they can do.
3404  *
3405  * argv[0] is ignored in either case (it's assumed to be the program name).
3406  *
3407  * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3408  * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3409  * a superuser client.
3410  *
3411  * If a database name is present in the command line arguments, it's
3412  * returned into *dbname (this is allowed only if *dbname is initially NULL).
3413  * ----------------------------------------------------------------
3414  */
3415 void
process_postgres_switches(int argc,char * argv[],GucContext ctx,const char ** dbname)3416 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3417 						  const char **dbname)
3418 {
3419 	bool		secure = (ctx == PGC_POSTMASTER);
3420 	int			errs = 0;
3421 	GucSource	gucsource;
3422 	int			flag;
3423 
3424 	if (secure)
3425 	{
3426 		gucsource = PGC_S_ARGV; /* switches came from command line */
3427 
3428 		/* Ignore the initial --single argument, if present */
3429 		if (argc > 1 && strcmp(argv[1], "--single") == 0)
3430 		{
3431 			argv++;
3432 			argc--;
3433 		}
3434 	}
3435 	else
3436 	{
3437 		gucsource = PGC_S_CLIENT;	/* switches came from client */
3438 	}
3439 
3440 #ifdef HAVE_INT_OPTERR
3441 
3442 	/*
3443 	 * Turn this off because it's either printed to stderr and not the log
3444 	 * where we'd want it, or argv[0] is now "--single", which would make for
3445 	 * a weird error message.  We print our own error message below.
3446 	 */
3447 	opterr = 0;
3448 #endif
3449 
3450 	/*
3451 	 * Parse command-line options.  CAUTION: keep this in sync with
3452 	 * postmaster/postmaster.c (the option sets should not conflict) and with
3453 	 * the common help() function in main/main.c.
3454 	 */
3455 	while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3456 	{
3457 		switch (flag)
3458 		{
3459 			case 'B':
3460 				SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3461 				break;
3462 
3463 			case 'b':
3464 				/* Undocumented flag used for binary upgrades */
3465 				if (secure)
3466 					IsBinaryUpgrade = true;
3467 				break;
3468 
3469 			case 'C':
3470 				/* ignored for consistency with the postmaster */
3471 				break;
3472 
3473 			case 'D':
3474 				if (secure)
3475 					userDoption = strdup(optarg);
3476 				break;
3477 
3478 			case 'd':
3479 				set_debug_options(atoi(optarg), ctx, gucsource);
3480 				break;
3481 
3482 			case 'E':
3483 				if (secure)
3484 					EchoQuery = true;
3485 				break;
3486 
3487 			case 'e':
3488 				SetConfigOption("datestyle", "euro", ctx, gucsource);
3489 				break;
3490 
3491 			case 'F':
3492 				SetConfigOption("fsync", "false", ctx, gucsource);
3493 				break;
3494 
3495 			case 'f':
3496 				if (!set_plan_disabling_options(optarg, ctx, gucsource))
3497 					errs++;
3498 				break;
3499 
3500 			case 'h':
3501 				SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3502 				break;
3503 
3504 			case 'i':
3505 				SetConfigOption("listen_addresses", "*", ctx, gucsource);
3506 				break;
3507 
3508 			case 'j':
3509 				if (secure)
3510 					UseSemiNewlineNewline = true;
3511 				break;
3512 
3513 			case 'k':
3514 				SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3515 				break;
3516 
3517 			case 'l':
3518 				SetConfigOption("ssl", "true", ctx, gucsource);
3519 				break;
3520 
3521 			case 'N':
3522 				SetConfigOption("max_connections", optarg, ctx, gucsource);
3523 				break;
3524 
3525 			case 'n':
3526 				/* ignored for consistency with postmaster */
3527 				break;
3528 
3529 			case 'O':
3530 				SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3531 				break;
3532 
3533 			case 'o':
3534 				errs++;
3535 				break;
3536 
3537 			case 'P':
3538 				SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3539 				break;
3540 
3541 			case 'p':
3542 				SetConfigOption("port", optarg, ctx, gucsource);
3543 				break;
3544 
3545 			case 'r':
3546 				/* send output (stdout and stderr) to the given file */
3547 				if (secure)
3548 					strlcpy(OutputFileName, optarg, MAXPGPATH);
3549 				break;
3550 
3551 			case 'S':
3552 				SetConfigOption("work_mem", optarg, ctx, gucsource);
3553 				break;
3554 
3555 			case 's':
3556 				SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3557 				break;
3558 
3559 			case 'T':
3560 				/* ignored for consistency with the postmaster */
3561 				break;
3562 
3563 			case 't':
3564 				{
3565 					const char *tmp = get_stats_option_name(optarg);
3566 
3567 					if (tmp)
3568 						SetConfigOption(tmp, "true", ctx, gucsource);
3569 					else
3570 						errs++;
3571 					break;
3572 				}
3573 
3574 			case 'v':
3575 
3576 				/*
3577 				 * -v is no longer used in normal operation, since
3578 				 * FrontendProtocol is already set before we get here. We keep
3579 				 * the switch only for possible use in standalone operation,
3580 				 * in case we ever support using normal FE/BE protocol with a
3581 				 * standalone backend.
3582 				 */
3583 				if (secure)
3584 					FrontendProtocol = (ProtocolVersion) atoi(optarg);
3585 				break;
3586 
3587 			case 'W':
3588 				SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3589 				break;
3590 
3591 			case 'c':
3592 			case '-':
3593 				{
3594 					char	   *name,
3595 							   *value;
3596 
3597 					ParseLongOption(optarg, &name, &value);
3598 					if (!value)
3599 					{
3600 						if (flag == '-')
3601 							ereport(ERROR,
3602 									(errcode(ERRCODE_SYNTAX_ERROR),
3603 									 errmsg("--%s requires a value",
3604 											optarg)));
3605 						else
3606 							ereport(ERROR,
3607 									(errcode(ERRCODE_SYNTAX_ERROR),
3608 									 errmsg("-c %s requires a value",
3609 											optarg)));
3610 					}
3611 					SetConfigOption(name, value, ctx, gucsource);
3612 					free(name);
3613 					if (value)
3614 						free(value);
3615 					break;
3616 				}
3617 
3618 			default:
3619 				errs++;
3620 				break;
3621 		}
3622 
3623 		if (errs)
3624 			break;
3625 	}
3626 
3627 	/*
3628 	 * Optional database name should be there only if *dbname is NULL.
3629 	 */
3630 	if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3631 		*dbname = strdup(argv[optind++]);
3632 
3633 	if (errs || argc != optind)
3634 	{
3635 		if (errs)
3636 			optind--;			/* complain about the previous argument */
3637 
3638 		/* spell the error message a bit differently depending on context */
3639 		if (IsUnderPostmaster)
3640 			ereport(FATAL,
3641 					(errcode(ERRCODE_SYNTAX_ERROR),
3642 					 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3643 					 errhint("Try \"%s --help\" for more information.", progname)));
3644 		else
3645 			ereport(FATAL,
3646 					(errcode(ERRCODE_SYNTAX_ERROR),
3647 					 errmsg("%s: invalid command-line argument: %s",
3648 							progname, argv[optind]),
3649 					 errhint("Try \"%s --help\" for more information.", progname)));
3650 	}
3651 
3652 	/*
3653 	 * Reset getopt(3) library so that it will work correctly in subprocesses
3654 	 * or when this function is called a second time with another array.
3655 	 */
3656 	optind = 1;
3657 #ifdef HAVE_INT_OPTRESET
3658 	optreset = 1;				/* some systems need this too */
3659 #endif
3660 }
3661 
3662 
3663 /* ----------------------------------------------------------------
3664  * PostgresMain
3665  *	   postgres main loop -- all backends, interactive or otherwise start here
3666  *
3667  * argc/argv are the command line arguments to be used.  (When being forked
3668  * by the postmaster, these are not the original argv array of the process.)
3669  * dbname is the name of the database to connect to, or NULL if the database
3670  * name should be extracted from the command line arguments or defaulted.
3671  * username is the PostgreSQL user name to be used for the session.
3672  * ----------------------------------------------------------------
3673  */
3674 void
PostgresMain(int argc,char * argv[],const char * dbname,const char * username)3675 PostgresMain(int argc, char *argv[],
3676 			 const char *dbname,
3677 			 const char *username)
3678 {
3679 	int			firstchar;
3680 	StringInfoData input_message;
3681 	sigjmp_buf	local_sigjmp_buf;
3682 	volatile bool send_ready_for_query = true;
3683 	bool		disable_idle_in_transaction_timeout = false;
3684 
3685 	/* Initialize startup process environment if necessary. */
3686 	if (!IsUnderPostmaster)
3687 		InitStandaloneProcess(argv[0]);
3688 
3689 	SetProcessingMode(InitProcessing);
3690 
3691 	/*
3692 	 * Set default values for command-line options.
3693 	 */
3694 	if (!IsUnderPostmaster)
3695 		InitializeGUCOptions();
3696 
3697 	/*
3698 	 * Parse command-line options.
3699 	 */
3700 	process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3701 
3702 	/* Must have gotten a database name, or have a default (the username) */
3703 	if (dbname == NULL)
3704 	{
3705 		dbname = username;
3706 		if (dbname == NULL)
3707 			ereport(FATAL,
3708 					(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3709 					 errmsg("%s: no database nor user name specified",
3710 							progname)));
3711 	}
3712 
3713 	/* Acquire configuration parameters, unless inherited from postmaster */
3714 	if (!IsUnderPostmaster)
3715 	{
3716 		if (!SelectConfigFiles(userDoption, progname))
3717 			proc_exit(1);
3718 	}
3719 
3720 	/*
3721 	 * Set up signal handlers and masks.
3722 	 *
3723 	 * Note that postmaster blocked all signals before forking child process,
3724 	 * so there is no race condition whereby we might receive a signal before
3725 	 * we have set up the handler.
3726 	 *
3727 	 * Also note: it's best not to use any signals that are SIG_IGNored in the
3728 	 * postmaster.  If such a signal arrives before we are able to change the
3729 	 * handler to non-SIG_IGN, it'll get dropped.  Instead, make a dummy
3730 	 * handler in the postmaster to reserve the signal. (Of course, this isn't
3731 	 * an issue for signals that are locally generated, such as SIGALRM and
3732 	 * SIGPIPE.)
3733 	 */
3734 	if (am_walsender)
3735 		WalSndSignals();
3736 	else
3737 	{
3738 		pqsignal(SIGHUP, PostgresSigHupHandler);	/* set flag to read config
3739 													 * file */
3740 		pqsignal(SIGINT, StatementCancelHandler);	/* cancel current query */
3741 		pqsignal(SIGTERM, die); /* cancel current query and exit */
3742 
3743 		/*
3744 		 * In a standalone backend, SIGQUIT can be generated from the keyboard
3745 		 * easily, while SIGTERM cannot, so we make both signals do die()
3746 		 * rather than quickdie().
3747 		 */
3748 		if (IsUnderPostmaster)
3749 			pqsignal(SIGQUIT, quickdie);	/* hard crash time */
3750 		else
3751 			pqsignal(SIGQUIT, die); /* cancel current query and exit */
3752 		InitializeTimeouts();	/* establishes SIGALRM handler */
3753 
3754 		/*
3755 		 * Ignore failure to write to frontend. Note: if frontend closes
3756 		 * connection, we will notice it and exit cleanly when control next
3757 		 * returns to outer loop.  This seems safer than forcing exit in the
3758 		 * midst of output during who-knows-what operation...
3759 		 */
3760 		pqsignal(SIGPIPE, SIG_IGN);
3761 		pqsignal(SIGUSR1, procsignal_sigusr1_handler);
3762 		pqsignal(SIGUSR2, SIG_IGN);
3763 		pqsignal(SIGFPE, FloatExceptionHandler);
3764 
3765 		/*
3766 		 * Reset some signals that are accepted by postmaster but not by
3767 		 * backend
3768 		 */
3769 		pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3770 									 * platforms */
3771 	}
3772 
3773 	pqinitmask();
3774 
3775 	if (IsUnderPostmaster)
3776 	{
3777 		/* We allow SIGQUIT (quickdie) at all times */
3778 		sigdelset(&BlockSig, SIGQUIT);
3779 	}
3780 
3781 	PG_SETMASK(&BlockSig);		/* block everything except SIGQUIT */
3782 
3783 	if (!IsUnderPostmaster)
3784 	{
3785 		/*
3786 		 * Validate we have been given a reasonable-looking DataDir (if under
3787 		 * postmaster, assume postmaster did this already).
3788 		 */
3789 		checkDataDir();
3790 
3791 		/* Change into DataDir (if under postmaster, was done already) */
3792 		ChangeToDataDir();
3793 
3794 		/*
3795 		 * Create lockfile for data directory.
3796 		 */
3797 		CreateDataDirLockFile(false);
3798 
3799 		/* read control file (error checking and contains config ) */
3800 		LocalProcessControlFile(false);
3801 
3802 		/* Initialize MaxBackends (if under postmaster, was done already) */
3803 		InitializeMaxBackends();
3804 	}
3805 
3806 	/* Early initialization */
3807 	BaseInit();
3808 
3809 	/*
3810 	 * Create a per-backend PGPROC struct in shared memory, except in the
3811 	 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3812 	 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3813 	 * had to do some stuff with LWLocks).
3814 	 */
3815 #ifdef EXEC_BACKEND
3816 	if (!IsUnderPostmaster)
3817 		InitProcess();
3818 #else
3819 	InitProcess();
3820 #endif
3821 
3822 	/* We need to allow SIGINT, etc during the initial transaction */
3823 	PG_SETMASK(&UnBlockSig);
3824 
3825 	/*
3826 	 * General initialization.
3827 	 *
3828 	 * NOTE: if you are tempted to add code in this vicinity, consider putting
3829 	 * it inside InitPostgres() instead.  In particular, anything that
3830 	 * involves database access should be there, not here.
3831 	 */
3832 	InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL, false);
3833 
3834 	/*
3835 	 * If the PostmasterContext is still around, recycle the space; we don't
3836 	 * need it anymore after InitPostgres completes.  Note this does not trash
3837 	 * *MyProcPort, because ConnCreate() allocated that space with malloc()
3838 	 * ... else we'd need to copy the Port data first.  Also, subsidiary data
3839 	 * such as the username isn't lost either; see ProcessStartupPacket().
3840 	 */
3841 	if (PostmasterContext)
3842 	{
3843 		MemoryContextDelete(PostmasterContext);
3844 		PostmasterContext = NULL;
3845 	}
3846 
3847 	SetProcessingMode(NormalProcessing);
3848 
3849 	/*
3850 	 * Now all GUC states are fully set up.  Report them to client if
3851 	 * appropriate.
3852 	 */
3853 	BeginReportingGUCOptions();
3854 
3855 	/*
3856 	 * Also set up handler to log session end; we have to wait till now to be
3857 	 * sure Log_disconnections has its final value.
3858 	 */
3859 	if (IsUnderPostmaster && Log_disconnections)
3860 		on_proc_exit(log_disconnections, 0);
3861 
3862 	/* Perform initialization specific to a WAL sender process. */
3863 	if (am_walsender)
3864 		InitWalSender();
3865 
3866 	/*
3867 	 * process any libraries that should be preloaded at backend start (this
3868 	 * likewise can't be done until GUC settings are complete)
3869 	 */
3870 	process_session_preload_libraries();
3871 
3872 	/*
3873 	 * Send this backend's cancellation info to the frontend.
3874 	 */
3875 	if (whereToSendOutput == DestRemote)
3876 	{
3877 		StringInfoData buf;
3878 
3879 		pq_beginmessage(&buf, 'K');
3880 		pq_sendint32(&buf, (int32) MyProcPid);
3881 		pq_sendint32(&buf, (int32) MyCancelKey);
3882 		pq_endmessage(&buf);
3883 		/* Need not flush since ReadyForQuery will do it. */
3884 	}
3885 
3886 	/* Welcome banner for standalone case */
3887 	if (whereToSendOutput == DestDebug)
3888 		printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3889 
3890 	/*
3891 	 * Create the memory context we will use in the main loop.
3892 	 *
3893 	 * MessageContext is reset once per iteration of the main loop, ie, upon
3894 	 * completion of processing of each command message from the client.
3895 	 */
3896 	MessageContext = AllocSetContextCreate(TopMemoryContext,
3897 										   "MessageContext",
3898 										   ALLOCSET_DEFAULT_SIZES);
3899 
3900 	/*
3901 	 * Create memory context and buffer used for RowDescription messages. As
3902 	 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3903 	 * frequently executed for ever single statement, we don't want to
3904 	 * allocate a separate buffer every time.
3905 	 */
3906 	row_description_context = AllocSetContextCreate(TopMemoryContext,
3907 													"RowDescriptionContext",
3908 													ALLOCSET_DEFAULT_SIZES);
3909 	MemoryContextSwitchTo(row_description_context);
3910 	initStringInfo(&row_description_buf);
3911 	MemoryContextSwitchTo(TopMemoryContext);
3912 
3913 	/*
3914 	 * Remember stand-alone backend startup time
3915 	 */
3916 	if (!IsUnderPostmaster)
3917 		PgStartTime = GetCurrentTimestamp();
3918 
3919 	/*
3920 	 * POSTGRES main processing loop begins here
3921 	 *
3922 	 * If an exception is encountered, processing resumes here so we abort the
3923 	 * current transaction and start a new one.
3924 	 *
3925 	 * You might wonder why this isn't coded as an infinite loop around a
3926 	 * PG_TRY construct.  The reason is that this is the bottom of the
3927 	 * exception stack, and so with PG_TRY there would be no exception handler
3928 	 * in force at all during the CATCH part.  By leaving the outermost setjmp
3929 	 * always active, we have at least some chance of recovering from an error
3930 	 * during error recovery.  (If we get into an infinite loop thereby, it
3931 	 * will soon be stopped by overflow of elog.c's internal state stack.)
3932 	 *
3933 	 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3934 	 * (to wit, UnBlockSig) will be restored when longjmp'ing to here.  This
3935 	 * is essential in case we longjmp'd out of a signal handler on a platform
3936 	 * where that leaves the signal blocked.  It's not redundant with the
3937 	 * unblock in AbortTransaction() because the latter is only called if we
3938 	 * were inside a transaction.
3939 	 */
3940 
3941 	if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3942 	{
3943 		/*
3944 		 * NOTE: if you are tempted to add more code in this if-block,
3945 		 * consider the high probability that it should be in
3946 		 * AbortTransaction() instead.  The only stuff done directly here
3947 		 * should be stuff that is guaranteed to apply *only* for outer-level
3948 		 * error recovery, such as adjusting the FE/BE protocol status.
3949 		 */
3950 
3951 		/* Since not using PG_TRY, must reset error stack by hand */
3952 		error_context_stack = NULL;
3953 
3954 		/* Prevent interrupts while cleaning up */
3955 		HOLD_INTERRUPTS();
3956 
3957 		/*
3958 		 * Forget any pending QueryCancel request, since we're returning to
3959 		 * the idle loop anyway, and cancel any active timeout requests.  (In
3960 		 * future we might want to allow some timeout requests to survive, but
3961 		 * at minimum it'd be necessary to do reschedule_timeouts(), in case
3962 		 * we got here because of a query cancel interrupting the SIGALRM
3963 		 * interrupt handler.)	Note in particular that we must clear the
3964 		 * statement and lock timeout indicators, to prevent any future plain
3965 		 * query cancels from being misreported as timeouts in case we're
3966 		 * forgetting a timeout cancel.
3967 		 */
3968 		disable_all_timeouts(false);
3969 		QueryCancelPending = false; /* second to avoid race condition */
3970 		stmt_timeout_active = false;
3971 
3972 		/* Not reading from the client anymore. */
3973 		DoingCommandRead = false;
3974 
3975 		/* Make sure libpq is in a good state */
3976 		pq_comm_reset();
3977 
3978 		/* Report the error to the client and/or server log */
3979 		EmitErrorReport();
3980 
3981 		/*
3982 		 * Make sure debug_query_string gets reset before we possibly clobber
3983 		 * the storage it points at.
3984 		 */
3985 		debug_query_string = NULL;
3986 
3987 		/*
3988 		 * Abort the current transaction in order to recover.
3989 		 */
3990 		AbortCurrentTransaction();
3991 
3992 		if (am_walsender)
3993 			WalSndErrorCleanup();
3994 
3995 		PortalErrorCleanup();
3996 		SPICleanup();
3997 
3998 		/*
3999 		 * We can't release replication slots inside AbortTransaction() as we
4000 		 * need to be able to start and abort transactions while having a slot
4001 		 * acquired. But we never need to hold them across top level errors,
4002 		 * so releasing here is fine. There's another cleanup in ProcKill()
4003 		 * ensuring we'll correctly cleanup on FATAL errors as well.
4004 		 */
4005 		if (MyReplicationSlot != NULL)
4006 			ReplicationSlotRelease();
4007 
4008 		/* We also want to cleanup temporary slots on error. */
4009 		ReplicationSlotCleanup();
4010 
4011 		jit_reset_after_error();
4012 
4013 		/*
4014 		 * Now return to normal top-level context and clear ErrorContext for
4015 		 * next time.
4016 		 */
4017 		MemoryContextSwitchTo(TopMemoryContext);
4018 		FlushErrorState();
4019 
4020 		/*
4021 		 * If we were handling an extended-query-protocol message, initiate
4022 		 * skip till next Sync.  This also causes us not to issue
4023 		 * ReadyForQuery (until we get Sync).
4024 		 */
4025 		if (doing_extended_query_message)
4026 			ignore_till_sync = true;
4027 
4028 		/* We don't have a transaction command open anymore */
4029 		xact_started = false;
4030 
4031 		/*
4032 		 * If an error occurred while we were reading a message from the
4033 		 * client, we have potentially lost track of where the previous
4034 		 * message ends and the next one begins.  Even though we have
4035 		 * otherwise recovered from the error, we cannot safely read any more
4036 		 * messages from the client, so there isn't much we can do with the
4037 		 * connection anymore.
4038 		 */
4039 		if (pq_is_reading_msg())
4040 			ereport(FATAL,
4041 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
4042 					 errmsg("terminating connection because protocol synchronization was lost")));
4043 
4044 		/* Now we can allow interrupts again */
4045 		RESUME_INTERRUPTS();
4046 	}
4047 
4048 	/* We can now handle ereport(ERROR) */
4049 	PG_exception_stack = &local_sigjmp_buf;
4050 
4051 	if (!ignore_till_sync)
4052 		send_ready_for_query = true;	/* initially, or after error */
4053 
4054 	/*
4055 	 * Non-error queries loop here.
4056 	 */
4057 
4058 	for (;;)
4059 	{
4060 		/*
4061 		 * At top of loop, reset extended-query-message flag, so that any
4062 		 * errors encountered in "idle" state don't provoke skip.
4063 		 */
4064 		doing_extended_query_message = false;
4065 
4066 		/*
4067 		 * Release storage left over from prior query cycle, and create a new
4068 		 * query input buffer in the cleared MessageContext.
4069 		 */
4070 		MemoryContextSwitchTo(MessageContext);
4071 		MemoryContextResetAndDeleteChildren(MessageContext);
4072 
4073 		initStringInfo(&input_message);
4074 
4075 		/*
4076 		 * Also consider releasing our catalog snapshot if any, so that it's
4077 		 * not preventing advance of global xmin while we wait for the client.
4078 		 */
4079 		InvalidateCatalogSnapshotConditionally();
4080 
4081 		/*
4082 		 * (1) If we've reached idle state, tell the frontend we're ready for
4083 		 * a new query.
4084 		 *
4085 		 * Note: this includes fflush()'ing the last of the prior output.
4086 		 *
4087 		 * This is also a good time to send collected statistics to the
4088 		 * collector, and to update the PS stats display.  We avoid doing
4089 		 * those every time through the message loop because it'd slow down
4090 		 * processing of batched messages, and because we don't want to report
4091 		 * uncommitted updates (that confuses autovacuum).  The notification
4092 		 * processor wants a call too, if we are not in a transaction block.
4093 		 */
4094 		if (send_ready_for_query)
4095 		{
4096 			if (IsAbortedTransactionBlockState())
4097 			{
4098 				set_ps_display("idle in transaction (aborted)", false);
4099 				pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
4100 
4101 				/* Start the idle-in-transaction timer */
4102 				if (IdleInTransactionSessionTimeout > 0)
4103 				{
4104 					disable_idle_in_transaction_timeout = true;
4105 					enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4106 										 IdleInTransactionSessionTimeout);
4107 				}
4108 			}
4109 			else if (IsTransactionOrTransactionBlock())
4110 			{
4111 				set_ps_display("idle in transaction", false);
4112 				pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
4113 
4114 				/* Start the idle-in-transaction timer */
4115 				if (IdleInTransactionSessionTimeout > 0)
4116 				{
4117 					disable_idle_in_transaction_timeout = true;
4118 					enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4119 										 IdleInTransactionSessionTimeout);
4120 				}
4121 			}
4122 			else
4123 			{
4124 				/* Send out notify signals and transmit self-notifies */
4125 				ProcessCompletedNotifies();
4126 
4127 				/*
4128 				 * Also process incoming notifies, if any.  This is mostly to
4129 				 * ensure stable behavior in tests: if any notifies were
4130 				 * received during the just-finished transaction, they'll be
4131 				 * seen by the client before ReadyForQuery is.
4132 				 */
4133 				if (notifyInterruptPending)
4134 					ProcessNotifyInterrupt();
4135 
4136 				pgstat_report_stat(false);
4137 
4138 				set_ps_display("idle", false);
4139 				pgstat_report_activity(STATE_IDLE, NULL);
4140 			}
4141 
4142 			ReadyForQuery(whereToSendOutput);
4143 			send_ready_for_query = false;
4144 		}
4145 
4146 		/*
4147 		 * (2) Allow asynchronous signals to be executed immediately if they
4148 		 * come in while we are waiting for client input. (This must be
4149 		 * conditional since we don't want, say, reads on behalf of COPY FROM
4150 		 * STDIN doing the same thing.)
4151 		 */
4152 		DoingCommandRead = true;
4153 
4154 		/*
4155 		 * (3) read a command (loop blocks here)
4156 		 */
4157 		firstchar = ReadCommand(&input_message);
4158 
4159 		/*
4160 		 * (4) turn off the idle-in-transaction timeout, if active.  We do
4161 		 * this before step (5) so that any last-moment timeout is certain to
4162 		 * be detected in step (5).
4163 		 */
4164 		if (disable_idle_in_transaction_timeout)
4165 		{
4166 			disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
4167 			disable_idle_in_transaction_timeout = false;
4168 		}
4169 
4170 		/*
4171 		 * (5) disable async signal conditions again.
4172 		 *
4173 		 * Query cancel is supposed to be a no-op when there is no query in
4174 		 * progress, so if a query cancel arrived while we were idle, just
4175 		 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4176 		 * it's called when DoingCommandRead is set, so check for interrupts
4177 		 * before resetting DoingCommandRead.
4178 		 */
4179 		CHECK_FOR_INTERRUPTS();
4180 		DoingCommandRead = false;
4181 
4182 		/*
4183 		 * (6) check for any other interesting events that happened while we
4184 		 * slept.
4185 		 */
4186 		if (ConfigReloadPending)
4187 		{
4188 			ConfigReloadPending = false;
4189 			ProcessConfigFile(PGC_SIGHUP);
4190 		}
4191 
4192 		/*
4193 		 * (7) process the command.  But ignore it if we're skipping till
4194 		 * Sync.
4195 		 */
4196 		if (ignore_till_sync && firstchar != EOF)
4197 			continue;
4198 
4199 		switch (firstchar)
4200 		{
4201 			case 'Q':			/* simple query */
4202 				{
4203 					const char *query_string;
4204 
4205 					/* Set statement_timestamp() */
4206 					SetCurrentStatementStartTimestamp();
4207 
4208 					query_string = pq_getmsgstring(&input_message);
4209 					pq_getmsgend(&input_message);
4210 
4211 					if (am_walsender)
4212 					{
4213 						if (!exec_replication_command(query_string))
4214 							exec_simple_query(query_string);
4215 					}
4216 					else
4217 						exec_simple_query(query_string);
4218 
4219 					send_ready_for_query = true;
4220 				}
4221 				break;
4222 
4223 			case 'P':			/* parse */
4224 				{
4225 					const char *stmt_name;
4226 					const char *query_string;
4227 					int			numParams;
4228 					Oid		   *paramTypes = NULL;
4229 
4230 					forbidden_in_wal_sender(firstchar);
4231 
4232 					/* Set statement_timestamp() */
4233 					SetCurrentStatementStartTimestamp();
4234 
4235 					stmt_name = pq_getmsgstring(&input_message);
4236 					query_string = pq_getmsgstring(&input_message);
4237 					numParams = pq_getmsgint(&input_message, 2);
4238 					if (numParams > 0)
4239 					{
4240 						int			i;
4241 
4242 						paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4243 						for (i = 0; i < numParams; i++)
4244 							paramTypes[i] = pq_getmsgint(&input_message, 4);
4245 					}
4246 					pq_getmsgend(&input_message);
4247 
4248 					exec_parse_message(query_string, stmt_name,
4249 									   paramTypes, numParams);
4250 				}
4251 				break;
4252 
4253 			case 'B':			/* bind */
4254 				forbidden_in_wal_sender(firstchar);
4255 
4256 				/* Set statement_timestamp() */
4257 				SetCurrentStatementStartTimestamp();
4258 
4259 				/*
4260 				 * this message is complex enough that it seems best to put
4261 				 * the field extraction out-of-line
4262 				 */
4263 				exec_bind_message(&input_message);
4264 				break;
4265 
4266 			case 'E':			/* execute */
4267 				{
4268 					const char *portal_name;
4269 					int			max_rows;
4270 
4271 					forbidden_in_wal_sender(firstchar);
4272 
4273 					/* Set statement_timestamp() */
4274 					SetCurrentStatementStartTimestamp();
4275 
4276 					portal_name = pq_getmsgstring(&input_message);
4277 					max_rows = pq_getmsgint(&input_message, 4);
4278 					pq_getmsgend(&input_message);
4279 
4280 					exec_execute_message(portal_name, max_rows);
4281 				}
4282 				break;
4283 
4284 			case 'F':			/* fastpath function call */
4285 				forbidden_in_wal_sender(firstchar);
4286 
4287 				/* Set statement_timestamp() */
4288 				SetCurrentStatementStartTimestamp();
4289 
4290 				/* Report query to various monitoring facilities. */
4291 				pgstat_report_activity(STATE_FASTPATH, NULL);
4292 				set_ps_display("<FASTPATH>", false);
4293 
4294 				/* start an xact for this function invocation */
4295 				start_xact_command();
4296 
4297 				/*
4298 				 * Note: we may at this point be inside an aborted
4299 				 * transaction.  We can't throw error for that until we've
4300 				 * finished reading the function-call message, so
4301 				 * HandleFunctionRequest() must check for it after doing so.
4302 				 * Be careful not to do anything that assumes we're inside a
4303 				 * valid transaction here.
4304 				 */
4305 
4306 				/* switch back to message context */
4307 				MemoryContextSwitchTo(MessageContext);
4308 
4309 				HandleFunctionRequest(&input_message);
4310 
4311 				/* commit the function-invocation transaction */
4312 				finish_xact_command();
4313 
4314 				send_ready_for_query = true;
4315 				break;
4316 
4317 			case 'C':			/* close */
4318 				{
4319 					int			close_type;
4320 					const char *close_target;
4321 
4322 					forbidden_in_wal_sender(firstchar);
4323 
4324 					close_type = pq_getmsgbyte(&input_message);
4325 					close_target = pq_getmsgstring(&input_message);
4326 					pq_getmsgend(&input_message);
4327 
4328 					switch (close_type)
4329 					{
4330 						case 'S':
4331 							if (close_target[0] != '\0')
4332 								DropPreparedStatement(close_target, false);
4333 							else
4334 							{
4335 								/* special-case the unnamed statement */
4336 								drop_unnamed_stmt();
4337 							}
4338 							break;
4339 						case 'P':
4340 							{
4341 								Portal		portal;
4342 
4343 								portal = GetPortalByName(close_target);
4344 								if (PortalIsValid(portal))
4345 									PortalDrop(portal, false);
4346 							}
4347 							break;
4348 						default:
4349 							ereport(ERROR,
4350 									(errcode(ERRCODE_PROTOCOL_VIOLATION),
4351 									 errmsg("invalid CLOSE message subtype %d",
4352 											close_type)));
4353 							break;
4354 					}
4355 
4356 					if (whereToSendOutput == DestRemote)
4357 						pq_putemptymessage('3');	/* CloseComplete */
4358 				}
4359 				break;
4360 
4361 			case 'D':			/* describe */
4362 				{
4363 					int			describe_type;
4364 					const char *describe_target;
4365 
4366 					forbidden_in_wal_sender(firstchar);
4367 
4368 					/* Set statement_timestamp() (needed for xact) */
4369 					SetCurrentStatementStartTimestamp();
4370 
4371 					describe_type = pq_getmsgbyte(&input_message);
4372 					describe_target = pq_getmsgstring(&input_message);
4373 					pq_getmsgend(&input_message);
4374 
4375 					switch (describe_type)
4376 					{
4377 						case 'S':
4378 							exec_describe_statement_message(describe_target);
4379 							break;
4380 						case 'P':
4381 							exec_describe_portal_message(describe_target);
4382 							break;
4383 						default:
4384 							ereport(ERROR,
4385 									(errcode(ERRCODE_PROTOCOL_VIOLATION),
4386 									 errmsg("invalid DESCRIBE message subtype %d",
4387 											describe_type)));
4388 							break;
4389 					}
4390 				}
4391 				break;
4392 
4393 			case 'H':			/* flush */
4394 				pq_getmsgend(&input_message);
4395 				if (whereToSendOutput == DestRemote)
4396 					pq_flush();
4397 				break;
4398 
4399 			case 'S':			/* sync */
4400 				pq_getmsgend(&input_message);
4401 				finish_xact_command();
4402 				send_ready_for_query = true;
4403 				break;
4404 
4405 				/*
4406 				 * 'X' means that the frontend is closing down the socket. EOF
4407 				 * means unexpected loss of frontend connection. Either way,
4408 				 * perform normal shutdown.
4409 				 */
4410 			case 'X':
4411 			case EOF:
4412 
4413 				/*
4414 				 * Reset whereToSendOutput to prevent ereport from attempting
4415 				 * to send any more messages to client.
4416 				 */
4417 				if (whereToSendOutput == DestRemote)
4418 					whereToSendOutput = DestNone;
4419 
4420 				/*
4421 				 * NOTE: if you are tempted to add more code here, DON'T!
4422 				 * Whatever you had in mind to do should be set up as an
4423 				 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4424 				 * it will fail to be called during other backend-shutdown
4425 				 * scenarios.
4426 				 */
4427 				proc_exit(0);
4428 
4429 			case 'd':			/* copy data */
4430 			case 'c':			/* copy done */
4431 			case 'f':			/* copy fail */
4432 
4433 				/*
4434 				 * Accept but ignore these messages, per protocol spec; we
4435 				 * probably got here because a COPY failed, and the frontend
4436 				 * is still sending data.
4437 				 */
4438 				break;
4439 
4440 			default:
4441 				ereport(FATAL,
4442 						(errcode(ERRCODE_PROTOCOL_VIOLATION),
4443 						 errmsg("invalid frontend message type %d",
4444 								firstchar)));
4445 		}
4446 	}							/* end of input-reading loop */
4447 }
4448 
4449 /*
4450  * Throw an error if we're a WAL sender process.
4451  *
4452  * This is used to forbid anything else than simple query protocol messages
4453  * in a WAL sender process.  'firstchar' specifies what kind of a forbidden
4454  * message was received, and is used to construct the error message.
4455  */
4456 static void
forbidden_in_wal_sender(char firstchar)4457 forbidden_in_wal_sender(char firstchar)
4458 {
4459 	if (am_walsender)
4460 	{
4461 		if (firstchar == 'F')
4462 			ereport(ERROR,
4463 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
4464 					 errmsg("fastpath function calls not supported in a replication connection")));
4465 		else
4466 			ereport(ERROR,
4467 					(errcode(ERRCODE_PROTOCOL_VIOLATION),
4468 					 errmsg("extended query protocol not supported in a replication connection")));
4469 	}
4470 }
4471 
4472 
4473 /*
4474  * Obtain platform stack depth limit (in bytes)
4475  *
4476  * Return -1 if unknown
4477  */
4478 long
get_stack_depth_rlimit(void)4479 get_stack_depth_rlimit(void)
4480 {
4481 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4482 	static long val = 0;
4483 
4484 	/* This won't change after process launch, so check just once */
4485 	if (val == 0)
4486 	{
4487 		struct rlimit rlim;
4488 
4489 		if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4490 			val = -1;
4491 		else if (rlim.rlim_cur == RLIM_INFINITY)
4492 			val = LONG_MAX;
4493 		/* rlim_cur is probably of an unsigned type, so check for overflow */
4494 		else if (rlim.rlim_cur >= LONG_MAX)
4495 			val = LONG_MAX;
4496 		else
4497 			val = rlim.rlim_cur;
4498 	}
4499 	return val;
4500 #else							/* no getrlimit */
4501 #if defined(WIN32) || defined(__CYGWIN__)
4502 	/* On Windows we set the backend stack size in src/backend/Makefile */
4503 	return WIN32_STACK_RLIMIT;
4504 #else							/* not windows ... give up */
4505 	return -1;
4506 #endif
4507 #endif
4508 }
4509 
4510 
4511 static struct rusage Save_r;
4512 static struct timeval Save_t;
4513 
4514 void
ResetUsage(void)4515 ResetUsage(void)
4516 {
4517 	getrusage(RUSAGE_SELF, &Save_r);
4518 	gettimeofday(&Save_t, NULL);
4519 }
4520 
4521 void
ShowUsage(const char * title)4522 ShowUsage(const char *title)
4523 {
4524 	StringInfoData str;
4525 	struct timeval user,
4526 				sys;
4527 	struct timeval elapse_t;
4528 	struct rusage r;
4529 
4530 	getrusage(RUSAGE_SELF, &r);
4531 	gettimeofday(&elapse_t, NULL);
4532 	memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4533 	memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4534 	if (elapse_t.tv_usec < Save_t.tv_usec)
4535 	{
4536 		elapse_t.tv_sec--;
4537 		elapse_t.tv_usec += 1000000;
4538 	}
4539 	if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4540 	{
4541 		r.ru_utime.tv_sec--;
4542 		r.ru_utime.tv_usec += 1000000;
4543 	}
4544 	if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4545 	{
4546 		r.ru_stime.tv_sec--;
4547 		r.ru_stime.tv_usec += 1000000;
4548 	}
4549 
4550 	/*
4551 	 * The only stats we don't show here are ixrss, idrss, isrss.  It takes
4552 	 * some work to interpret them, and most platforms don't fill them in.
4553 	 */
4554 	initStringInfo(&str);
4555 
4556 	appendStringInfoString(&str, "! system usage stats:\n");
4557 	appendStringInfo(&str,
4558 					 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4559 					 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4560 					 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4561 					 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4562 					 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4563 					 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4564 					 (long) (elapse_t.tv_usec - Save_t.tv_usec));
4565 	appendStringInfo(&str,
4566 					 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4567 					 (long) user.tv_sec,
4568 					 (long) user.tv_usec,
4569 					 (long) sys.tv_sec,
4570 					 (long) sys.tv_usec);
4571 #if defined(HAVE_GETRUSAGE)
4572 	appendStringInfo(&str,
4573 					 "!\t%ld kB max resident size\n",
4574 #if defined(__darwin__)
4575 	/* in bytes on macOS */
4576 					 r.ru_maxrss / 1024
4577 #else
4578 	/* in kilobytes on most other platforms */
4579 					 r.ru_maxrss
4580 #endif
4581 		);
4582 	appendStringInfo(&str,
4583 					 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4584 					 r.ru_inblock - Save_r.ru_inblock,
4585 	/* they only drink coffee at dec */
4586 					 r.ru_oublock - Save_r.ru_oublock,
4587 					 r.ru_inblock, r.ru_oublock);
4588 	appendStringInfo(&str,
4589 					 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4590 					 r.ru_majflt - Save_r.ru_majflt,
4591 					 r.ru_minflt - Save_r.ru_minflt,
4592 					 r.ru_majflt, r.ru_minflt,
4593 					 r.ru_nswap - Save_r.ru_nswap,
4594 					 r.ru_nswap);
4595 	appendStringInfo(&str,
4596 					 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4597 					 r.ru_nsignals - Save_r.ru_nsignals,
4598 					 r.ru_nsignals,
4599 					 r.ru_msgrcv - Save_r.ru_msgrcv,
4600 					 r.ru_msgsnd - Save_r.ru_msgsnd,
4601 					 r.ru_msgrcv, r.ru_msgsnd);
4602 	appendStringInfo(&str,
4603 					 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4604 					 r.ru_nvcsw - Save_r.ru_nvcsw,
4605 					 r.ru_nivcsw - Save_r.ru_nivcsw,
4606 					 r.ru_nvcsw, r.ru_nivcsw);
4607 #endif							/* HAVE_GETRUSAGE */
4608 
4609 	/* remove trailing newline */
4610 	if (str.data[str.len - 1] == '\n')
4611 		str.data[--str.len] = '\0';
4612 
4613 	ereport(LOG,
4614 			(errmsg_internal("%s", title),
4615 			 errdetail_internal("%s", str.data)));
4616 
4617 	pfree(str.data);
4618 }
4619 
4620 /*
4621  * on_proc_exit handler to log end of session
4622  */
4623 static void
log_disconnections(int code,Datum arg)4624 log_disconnections(int code, Datum arg)
4625 {
4626 	Port	   *port = MyProcPort;
4627 	long		secs;
4628 	int			usecs;
4629 	int			msecs;
4630 	int			hours,
4631 				minutes,
4632 				seconds;
4633 
4634 	TimestampDifference(port->SessionStartTime,
4635 						GetCurrentTimestamp(),
4636 						&secs, &usecs);
4637 	msecs = usecs / 1000;
4638 
4639 	hours = secs / SECS_PER_HOUR;
4640 	secs %= SECS_PER_HOUR;
4641 	minutes = secs / SECS_PER_MINUTE;
4642 	seconds = secs % SECS_PER_MINUTE;
4643 
4644 	ereport(LOG,
4645 			(errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4646 					"user=%s database=%s host=%s%s%s",
4647 					hours, minutes, seconds, msecs,
4648 					port->user_name, port->database_name, port->remote_host,
4649 					port->remote_port[0] ? " port=" : "", port->remote_port)));
4650 }
4651 
4652 /*
4653  * Start statement timeout timer, if enabled.
4654  *
4655  * If there's already a timeout running, don't restart the timer.  That
4656  * enables compromises between accuracy of timeouts and cost of starting a
4657  * timeout.
4658  */
4659 static void
enable_statement_timeout(void)4660 enable_statement_timeout(void)
4661 {
4662 	/* must be within an xact */
4663 	Assert(xact_started);
4664 
4665 	if (StatementTimeout > 0)
4666 	{
4667 		if (!stmt_timeout_active)
4668 		{
4669 			enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
4670 			stmt_timeout_active = true;
4671 		}
4672 	}
4673 	else
4674 		disable_timeout(STATEMENT_TIMEOUT, false);
4675 }
4676 
4677 /*
4678  * Disable statement timeout, if active.
4679  */
4680 static void
disable_statement_timeout(void)4681 disable_statement_timeout(void)
4682 {
4683 	if (stmt_timeout_active)
4684 	{
4685 		disable_timeout(STATEMENT_TIMEOUT, false);
4686 
4687 		stmt_timeout_active = false;
4688 	}
4689 }
4690