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

Generated by: LCOV version 1.14