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