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