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