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