LCOV - code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13devel Lines: 871 1326 65.7 %
Date: 2019-11-21 13:06:38 Functions: 43 55 78.2 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.13