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