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