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

Generated by: LCOV version 1.14