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

Generated by: LCOV version 1.13