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