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

Generated by: LCOV version 1.14