LCOV - differential code coverage report
Current view: top level - src/backend/tcop - postgres.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 71.7 % 1492 1070 11 75 246 90 56 734 38 242 245 726 31 27
Current Date: 2023-04-08 15:15:32 Functions: 85.0 % 60 51 9 48 3 9 50 1
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a