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