LCOV - code coverage report
Current view: top level - src/backend/utils/error - elog.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 59.8 % 1441 861
Test Date: 2026-01-26 10:56:24 Functions: 85.0 % 80 68
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 35.6 % 1048 373

             Branch data     Line data    Source code
       1                 :             : /*-------------------------------------------------------------------------
       2                 :             :  *
       3                 :             :  * elog.c
       4                 :             :  *        error logging and reporting
       5                 :             :  *
       6                 :             :  * Because of the extremely high rate at which log messages can be generated,
       7                 :             :  * we need to be mindful of the performance cost of obtaining any information
       8                 :             :  * that may be logged.  Also, it's important to keep in mind that this code may
       9                 :             :  * get called from within an aborted transaction, in which case operations
      10                 :             :  * such as syscache lookups are unsafe.
      11                 :             :  *
      12                 :             :  * Some notes about recursion and errors during error processing:
      13                 :             :  *
      14                 :             :  * We need to be robust about recursive-error scenarios --- for example,
      15                 :             :  * if we run out of memory, it's important to be able to report that fact.
      16                 :             :  * There are a number of considerations that go into this.
      17                 :             :  *
      18                 :             :  * First, distinguish between re-entrant use and actual recursion.  It
      19                 :             :  * is possible for an error or warning message to be emitted while the
      20                 :             :  * parameters for an error message are being computed.  In this case
      21                 :             :  * errstart has been called for the outer message, and some field values
      22                 :             :  * may have already been saved, but we are not actually recursing.  We handle
      23                 :             :  * this by providing a (small) stack of ErrorData records.  The inner message
      24                 :             :  * can be computed and sent without disturbing the state of the outer message.
      25                 :             :  * (If the inner message is actually an error, this isn't very interesting
      26                 :             :  * because control won't come back to the outer message generator ... but
      27                 :             :  * if the inner message is only debug or log data, this is critical.)
      28                 :             :  *
      29                 :             :  * Second, actual recursion will occur if an error is reported by one of
      30                 :             :  * the elog.c routines or something they call.  By far the most probable
      31                 :             :  * scenario of this sort is "out of memory"; and it's also the nastiest
      32                 :             :  * to handle because we'd likely also run out of memory while trying to
      33                 :             :  * report this error!  Our escape hatch for this case is to reset the
      34                 :             :  * ErrorContext to empty before trying to process the inner error.  Since
      35                 :             :  * ErrorContext is guaranteed to have at least 8K of space in it (see mcxt.c),
      36                 :             :  * we should be able to process an "out of memory" message successfully.
      37                 :             :  * Since we lose the prior error state due to the reset, we won't be able
      38                 :             :  * to return to processing the original error, but we wouldn't have anyway.
      39                 :             :  * (NOTE: the escape hatch is not used for recursive situations where the
      40                 :             :  * inner message is of less than ERROR severity; in that case we just
      41                 :             :  * try to process it and return normally.  Usually this will work, but if
      42                 :             :  * it ends up in infinite recursion, we will PANIC due to error stack
      43                 :             :  * overflow.)
      44                 :             :  *
      45                 :             :  *
      46                 :             :  * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
      47                 :             :  * Portions Copyright (c) 1994, Regents of the University of California
      48                 :             :  *
      49                 :             :  *
      50                 :             :  * IDENTIFICATION
      51                 :             :  *        src/backend/utils/error/elog.c
      52                 :             :  *
      53                 :             :  *-------------------------------------------------------------------------
      54                 :             :  */
      55                 :             : #include "postgres.h"
      56                 :             : 
      57                 :             : #include <fcntl.h>
      58                 :             : #include <time.h>
      59                 :             : #include <unistd.h>
      60                 :             : #include <signal.h>
      61                 :             : #include <ctype.h>
      62                 :             : #ifdef HAVE_SYSLOG
      63                 :             : #include <syslog.h>
      64                 :             : #endif
      65                 :             : #ifdef HAVE_EXECINFO_H
      66                 :             : #include <execinfo.h>
      67                 :             : #endif
      68                 :             : 
      69                 :             : #include "access/xact.h"
      70                 :             : #include "common/ip.h"
      71                 :             : #include "libpq/libpq.h"
      72                 :             : #include "libpq/pqformat.h"
      73                 :             : #include "mb/pg_wchar.h"
      74                 :             : #include "miscadmin.h"
      75                 :             : #include "nodes/miscnodes.h"
      76                 :             : #include "pgstat.h"
      77                 :             : #include "postmaster/bgworker.h"
      78                 :             : #include "postmaster/postmaster.h"
      79                 :             : #include "postmaster/syslogger.h"
      80                 :             : #include "storage/ipc.h"
      81                 :             : #include "storage/proc.h"
      82                 :             : #include "tcop/tcopprot.h"
      83                 :             : #include "utils/guc_hooks.h"
      84                 :             : #include "utils/memutils.h"
      85                 :             : #include "utils/ps_status.h"
      86                 :             : #include "utils/varlena.h"
      87                 :             : 
      88                 :             : 
      89                 :             : /* In this module, access gettext() via err_gettext() */
      90                 :             : #undef _
      91                 :             : #define _(x) err_gettext(x)
      92                 :             : 
      93                 :             : 
      94                 :             : /* Global variables */
      95                 :             : ErrorContextCallback *error_context_stack = NULL;
      96                 :             : 
      97                 :             : sigjmp_buf *PG_exception_stack = NULL;
      98                 :             : 
      99                 :             : /*
     100                 :             :  * Hook for intercepting messages before they are sent to the server log.
     101                 :             :  * Note that the hook will not get called for messages that are suppressed
     102                 :             :  * by log_min_messages.  Also note that logging hooks implemented in preload
     103                 :             :  * libraries will miss any log messages that are generated before the
     104                 :             :  * library is loaded.
     105                 :             :  */
     106                 :             : emit_log_hook_type emit_log_hook = NULL;
     107                 :             : 
     108                 :             : /* GUC parameters */
     109                 :             : int                     Log_error_verbosity = PGERROR_DEFAULT;
     110                 :             : char       *Log_line_prefix = NULL; /* format for extra log line info */
     111                 :             : int                     Log_destination = LOG_DESTINATION_STDERR;
     112                 :             : char       *Log_destination_string = NULL;
     113                 :             : bool            syslog_sequence_numbers = true;
     114                 :             : bool            syslog_split_messages = true;
     115                 :             : 
     116                 :             : /* Processed form of backtrace_functions GUC */
     117                 :             : static char *backtrace_function_list;
     118                 :             : 
     119                 :             : #ifdef HAVE_SYSLOG
     120                 :             : 
     121                 :             : /*
     122                 :             :  * Max string length to send to syslog().  Note that this doesn't count the
     123                 :             :  * sequence-number prefix we add, and of course it doesn't count the prefix
     124                 :             :  * added by syslog itself.  Solaris and sysklogd truncate the final message
     125                 :             :  * at 1024 bytes, so this value leaves 124 bytes for those prefixes.  (Most
     126                 :             :  * other syslog implementations seem to have limits of 2KB or so.)
     127                 :             :  */
     128                 :             : #ifndef PG_SYSLOG_LIMIT
     129                 :             : #define PG_SYSLOG_LIMIT 900
     130                 :             : #endif
     131                 :             : 
     132                 :             : static bool openlog_done = false;
     133                 :             : static char *syslog_ident = NULL;
     134                 :             : static int      syslog_facility = LOG_LOCAL0;
     135                 :             : 
     136                 :             : static void write_syslog(int level, const char *line);
     137                 :             : #endif
     138                 :             : 
     139                 :             : #ifdef WIN32
     140                 :             : static void write_eventlog(int level, const char *line, int len);
     141                 :             : #endif
     142                 :             : 
     143                 :             : /* We provide a small stack of ErrorData records for re-entrant cases */
     144                 :             : #define ERRORDATA_STACK_SIZE  5
     145                 :             : 
     146                 :             : static ErrorData errordata[ERRORDATA_STACK_SIZE];
     147                 :             : 
     148                 :             : static int      errordata_stack_depth = -1; /* index of topmost active frame */
     149                 :             : 
     150                 :             : static int      recursion_depth = 0;    /* to detect actual recursion */
     151                 :             : 
     152                 :             : /*
     153                 :             :  * Saved timeval and buffers for formatted timestamps that might be used by
     154                 :             :  * log_line_prefix, csv logs and JSON logs.
     155                 :             :  */
     156                 :             : static struct timeval saved_timeval;
     157                 :             : static bool saved_timeval_set = false;
     158                 :             : 
     159                 :             : #define FORMATTED_TS_LEN 128
     160                 :             : static char formatted_start_time[FORMATTED_TS_LEN];
     161                 :             : static char formatted_log_time[FORMATTED_TS_LEN];
     162                 :             : 
     163                 :             : 
     164                 :             : /* Macro for checking errordata_stack_depth is reasonable */
     165                 :             : #define CHECK_STACK_DEPTH() \
     166                 :             :         do { \
     167                 :             :                 if (errordata_stack_depth < 0) \
     168                 :             :                 { \
     169                 :             :                         errordata_stack_depth = -1; \
     170                 :             :                         ereport(ERROR, (errmsg_internal("errstart was not called"))); \
     171                 :             :                 } \
     172                 :             :         } while (0)
     173                 :             : 
     174                 :             : 
     175                 :             : static const char *err_gettext(const char *str) pg_attribute_format_arg(1);
     176                 :             : static ErrorData *get_error_stack_entry(void);
     177                 :             : static void set_stack_entry_domain(ErrorData *edata, const char *domain);
     178                 :             : static void set_stack_entry_location(ErrorData *edata,
     179                 :             :                                                                          const char *filename, int lineno,
     180                 :             :                                                                          const char *funcname);
     181                 :             : static bool matches_backtrace_functions(const char *funcname);
     182                 :             : static pg_noinline void set_backtrace(ErrorData *edata, int num_skip);
     183                 :             : static void set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str);
     184                 :             : static void FreeErrorDataContents(ErrorData *edata);
     185                 :             : static void write_console(const char *line, int len);
     186                 :             : static const char *process_log_prefix_padding(const char *p, int *ppadding);
     187                 :             : static void log_line_prefix(StringInfo buf, ErrorData *edata);
     188                 :             : static void send_message_to_server_log(ErrorData *edata);
     189                 :             : static void send_message_to_frontend(ErrorData *edata);
     190                 :             : static void append_with_tabs(StringInfo buf, const char *str);
     191                 :             : 
     192                 :             : 
     193                 :             : /*
     194                 :             :  * is_log_level_output -- is elevel logically >= log_min_level?
     195                 :             :  *
     196                 :             :  * We use this for tests that should consider LOG to sort out-of-order,
     197                 :             :  * between ERROR and FATAL.  Generally this is the right thing for testing
     198                 :             :  * whether a message should go to the postmaster log, whereas a simple >=
     199                 :             :  * test is correct for testing whether the message should go to the client.
     200                 :             :  */
     201                 :             : static inline bool
     202                 :      749255 : is_log_level_output(int elevel, int log_min_level)
     203                 :             : {
     204   [ +  +  +  + ]:      749255 :         if (elevel == LOG || elevel == LOG_SERVER_ONLY)
     205                 :             :         {
     206   [ +  -  +  - ]:      115866 :                 if (log_min_level == LOG || log_min_level <= ERROR)
     207                 :      115866 :                         return true;
     208                 :           0 :         }
     209         [ -  + ]:      633389 :         else if (elevel == WARNING_CLIENT_ONLY)
     210                 :             :         {
     211                 :             :                 /* never sent to log, regardless of log_min_level */
     212                 :           0 :                 return false;
     213                 :             :         }
     214         [ -  + ]:      633389 :         else if (log_min_level == LOG)
     215                 :             :         {
     216                 :             :                 /* elevel != LOG */
     217         [ #  # ]:           0 :                 if (elevel >= FATAL)
     218                 :           0 :                         return true;
     219                 :           0 :         }
     220                 :             :         /* Neither is LOG */
     221         [ +  + ]:      633389 :         else if (elevel >= log_min_level)
     222                 :       15525 :                 return true;
     223                 :             : 
     224                 :      617864 :         return false;
     225                 :      749255 : }
     226                 :             : 
     227                 :             : /*
     228                 :             :  * Policy-setting subroutines.  These are fairly simple, but it seems wise
     229                 :             :  * to have the code in just one place.
     230                 :             :  */
     231                 :             : 
     232                 :             : /*
     233                 :             :  * should_output_to_server --- should message of given elevel go to the log?
     234                 :             :  */
     235                 :             : static inline bool
     236                 :      683581 : should_output_to_server(int elevel)
     237                 :             : {
     238                 :      683581 :         return is_log_level_output(elevel, log_min_messages);
     239                 :             : }
     240                 :             : 
     241                 :             : /*
     242                 :             :  * should_output_to_client --- should message of given elevel go to the client?
     243                 :             :  */
     244                 :             : static inline bool
     245                 :      683581 : should_output_to_client(int elevel)
     246                 :             : {
     247   [ +  +  +  + ]:      683581 :         if (whereToSendOutput == DestRemote && elevel != LOG_SERVER_ONLY)
     248                 :             :         {
     249                 :             :                 /*
     250                 :             :                  * client_min_messages is honored only after we complete the
     251                 :             :                  * authentication handshake.  This is required both for security
     252                 :             :                  * reasons and because many clients can't handle NOTICE messages
     253                 :             :                  * during authentication.
     254                 :             :                  */
     255         [ +  + ]:      333518 :                 if (ClientAuthInProgress)
     256                 :         732 :                         return (elevel >= ERROR);
     257                 :             :                 else
     258         [ +  + ]:      332786 :                         return (elevel >= client_min_messages || elevel == INFO);
     259                 :             :         }
     260                 :      350063 :         return false;
     261                 :      683581 : }
     262                 :             : 
     263                 :             : 
     264                 :             : /*
     265                 :             :  * message_level_is_interesting --- would ereport/elog do anything?
     266                 :             :  *
     267                 :             :  * Returns true if ereport/elog with this elevel will not be a no-op.
     268                 :             :  * This is useful to short-circuit any expensive preparatory work that
     269                 :             :  * might be needed for a logging message.  There is no point in
     270                 :             :  * prepending this to a bare ereport/elog call, however.
     271                 :             :  */
     272                 :             : bool
     273                 :      113877 : message_level_is_interesting(int elevel)
     274                 :             : {
     275                 :             :         /*
     276                 :             :          * Keep this in sync with the decision-making in errstart().
     277                 :             :          */
     278         [ +  - ]:      113877 :         if (elevel >= ERROR ||
     279   [ +  -  +  + ]:      113877 :                 should_output_to_server(elevel) ||
     280                 :      113877 :                 should_output_to_client(elevel))
     281                 :         368 :                 return true;
     282                 :      113509 :         return false;
     283                 :      113877 : }
     284                 :             : 
     285                 :             : 
     286                 :             : /*
     287                 :             :  * in_error_recursion_trouble --- are we at risk of infinite error recursion?
     288                 :             :  *
     289                 :             :  * This function exists to provide common control of various fallback steps
     290                 :             :  * that we take if we think we are facing infinite error recursion.  See the
     291                 :             :  * callers for details.
     292                 :             :  */
     293                 :             : bool
     294                 :      240311 : in_error_recursion_trouble(void)
     295                 :             : {
     296                 :             :         /* Pull the plug if recurse more than once */
     297                 :      240311 :         return (recursion_depth > 2);
     298                 :             : }
     299                 :             : 
     300                 :             : /*
     301                 :             :  * One of those fallback steps is to stop trying to localize the error
     302                 :             :  * message, since there's a significant probability that that's exactly
     303                 :             :  * what's causing the recursion.
     304                 :             :  */
     305                 :             : static inline const char *
     306                 :       87006 : err_gettext(const char *str)
     307                 :             : {
     308                 :             : #ifdef ENABLE_NLS
     309         [ -  + ]:       87006 :         if (in_error_recursion_trouble())
     310                 :           0 :                 return str;
     311                 :             :         else
     312                 :       87006 :                 return gettext(str);
     313                 :             : #else
     314                 :             :         return str;
     315                 :             : #endif
     316                 :       87006 : }
     317                 :             : 
     318                 :             : /*
     319                 :             :  * errstart_cold
     320                 :             :  *              A simple wrapper around errstart, but hinted to be "cold".  Supporting
     321                 :             :  *              compilers are more likely to move code for branches containing this
     322                 :             :  *              function into an area away from the calling function's code.  This can
     323                 :             :  *              result in more commonly executed code being more compact and fitting
     324                 :             :  *              on fewer cache lines.
     325                 :             :  */
     326                 :             : pg_attribute_cold bool
     327                 :        6341 : errstart_cold(int elevel, const char *domain)
     328                 :             : {
     329                 :        6341 :         return errstart(elevel, domain);
     330                 :             : }
     331                 :             : 
     332                 :             : /*
     333                 :             :  * errstart --- begin an error-reporting cycle
     334                 :             :  *
     335                 :             :  * Create and initialize error stack entry.  Subsequently, errmsg() and
     336                 :             :  * perhaps other routines will be called to further populate the stack entry.
     337                 :             :  * Finally, errfinish() will be called to actually process the error report.
     338                 :             :  *
     339                 :             :  * Returns true in normal case.  Returns false to short-circuit the error
     340                 :             :  * report (if it's a warning or lower and not to be reported anywhere).
     341                 :             :  */
     342                 :             : bool
     343                 :      569704 : errstart(int elevel, const char *domain)
     344                 :             : {
     345                 :      569704 :         ErrorData  *edata;
     346                 :      569704 :         bool            output_to_server;
     347                 :      569704 :         bool            output_to_client = false;
     348                 :      569704 :         int                     i;
     349                 :             : 
     350                 :             :         /*
     351                 :             :          * Check some cases in which we want to promote an error into a more
     352                 :             :          * severe error.  None of this logic applies for non-error messages.
     353                 :             :          */
     354         [ +  + ]:      569704 :         if (elevel >= ERROR)
     355                 :             :         {
     356                 :             :                 /*
     357                 :             :                  * If we are inside a critical section, all errors become PANIC
     358                 :             :                  * errors.  See miscadmin.h.
     359                 :             :                  */
     360         [ +  - ]:        7784 :                 if (CritSectionCount > 0)
     361                 :           0 :                         elevel = PANIC;
     362                 :             : 
     363                 :             :                 /*
     364                 :             :                  * Check reasons for treating ERROR as FATAL:
     365                 :             :                  *
     366                 :             :                  * 1. we have no handler to pass the error to (implies we are in the
     367                 :             :                  * postmaster or in backend startup).
     368                 :             :                  *
     369                 :             :                  * 2. ExitOnAnyError mode switch is set (initdb uses this).
     370                 :             :                  *
     371                 :             :                  * 3. the error occurred after proc_exit has begun to run.  (It's
     372                 :             :                  * proc_exit's responsibility to see that this doesn't turn into
     373                 :             :                  * infinite recursion!)
     374                 :             :                  */
     375         [ +  + ]:        7784 :                 if (elevel == ERROR)
     376                 :             :                 {
     377         [ +  - ]:        7783 :                         if (PG_exception_stack == NULL ||
     378   [ +  -  -  + ]:        7783 :                                 ExitOnAnyError ||
     379                 :        7783 :                                 proc_exit_inprogress)
     380                 :           0 :                                 elevel = FATAL;
     381                 :        7783 :                 }
     382                 :             : 
     383                 :             :                 /*
     384                 :             :                  * If the error level is ERROR or more, errfinish is not going to
     385                 :             :                  * return to caller; therefore, if there is any stacked error already
     386                 :             :                  * in progress it will be lost.  This is more or less okay, except we
     387                 :             :                  * do not want to have a FATAL or PANIC error downgraded because the
     388                 :             :                  * reporting process was interrupted by a lower-grade error.  So check
     389                 :             :                  * the stack and make sure we panic if panic is warranted.
     390                 :             :                  */
     391         [ -  + ]:        7784 :                 for (i = 0; i <= errordata_stack_depth; i++)
     392         [ #  # ]:           0 :                         elevel = Max(elevel, errordata[i].elevel);
     393                 :        7784 :         }
     394                 :             : 
     395                 :             :         /*
     396                 :             :          * Now decide whether we need to process this report at all; if it's
     397                 :             :          * warning or less and not enabled for logging, just return false without
     398                 :             :          * starting up any error logging machinery.
     399                 :             :          */
     400                 :      569704 :         output_to_server = should_output_to_server(elevel);
     401                 :      569704 :         output_to_client = should_output_to_client(elevel);
     402   [ +  +  +  +  :      569704 :         if (elevel < ERROR && !output_to_server && !output_to_client)
                   +  + ]
     403                 :      500584 :                 return false;
     404                 :             : 
     405                 :             :         /*
     406                 :             :          * We need to do some actual work.  Make sure that memory context
     407                 :             :          * initialization has finished, else we can't do anything useful.
     408                 :             :          */
     409         [ +  - ]:       69120 :         if (ErrorContext == NULL)
     410                 :             :         {
     411                 :             :                 /* Oops, hard crash time; very little we can do safely here */
     412                 :           0 :                 write_stderr("error occurred before error message processing is available\n");
     413                 :           0 :                 exit(2);
     414                 :             :         }
     415                 :             : 
     416                 :             :         /*
     417                 :             :          * Okay, crank up a stack entry to store the info in.
     418                 :             :          */
     419                 :             : 
     420   [ -  +  #  # ]:       69120 :         if (recursion_depth++ > 0 && elevel >= ERROR)
     421                 :             :         {
     422                 :             :                 /*
     423                 :             :                  * Oops, error during error processing.  Clear ErrorContext as
     424                 :             :                  * discussed at top of file.  We will not return to the original
     425                 :             :                  * error's reporter or handler, so we don't need it.
     426                 :             :                  */
     427                 :           0 :                 MemoryContextReset(ErrorContext);
     428                 :             : 
     429                 :             :                 /*
     430                 :             :                  * Infinite error recursion might be due to something broken in a
     431                 :             :                  * context traceback routine.  Abandon them too.  We also abandon
     432                 :             :                  * attempting to print the error statement (which, if long, could
     433                 :             :                  * itself be the source of the recursive failure).
     434                 :             :                  */
     435         [ #  # ]:           0 :                 if (in_error_recursion_trouble())
     436                 :             :                 {
     437                 :           0 :                         error_context_stack = NULL;
     438                 :           0 :                         debug_query_string = NULL;
     439                 :           0 :                 }
     440                 :           0 :         }
     441                 :             : 
     442                 :             :         /* Initialize data for this error frame */
     443                 :       69120 :         edata = get_error_stack_entry();
     444                 :       69120 :         edata->elevel = elevel;
     445                 :       69120 :         edata->output_to_server = output_to_server;
     446                 :       69120 :         edata->output_to_client = output_to_client;
     447                 :       69120 :         set_stack_entry_domain(edata, domain);
     448                 :             :         /* Select default errcode based on elevel */
     449         [ +  + ]:       69120 :         if (elevel >= ERROR)
     450                 :        7784 :                 edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
     451         [ +  + ]:       61336 :         else if (elevel >= WARNING)
     452                 :         975 :                 edata->sqlerrcode = ERRCODE_WARNING;
     453                 :             :         else
     454                 :       60361 :                 edata->sqlerrcode = ERRCODE_SUCCESSFUL_COMPLETION;
     455                 :             : 
     456                 :             :         /*
     457                 :             :          * Any allocations for this error state level should go into ErrorContext
     458                 :             :          */
     459                 :       69120 :         edata->assoc_context = ErrorContext;
     460                 :             : 
     461                 :       69120 :         recursion_depth--;
     462                 :       69120 :         return true;
     463                 :      569704 : }
     464                 :             : 
     465                 :             : /*
     466                 :             :  * errfinish --- end an error-reporting cycle
     467                 :             :  *
     468                 :             :  * Produce the appropriate error report(s) and pop the error stack.
     469                 :             :  *
     470                 :             :  * If elevel, as passed to errstart(), is ERROR or worse, control does not
     471                 :             :  * return to the caller.  See elog.h for the error level definitions.
     472                 :             :  */
     473                 :             : void
     474                 :       69120 : errfinish(const char *filename, int lineno, const char *funcname)
     475                 :             : {
     476                 :       69120 :         ErrorData  *edata = &errordata[errordata_stack_depth];
     477                 :       69120 :         int                     elevel;
     478                 :       69120 :         MemoryContext oldcontext;
     479                 :       69120 :         ErrorContextCallback *econtext;
     480                 :             : 
     481                 :       69120 :         recursion_depth++;
     482   [ +  -  #  #  :       69120 :         CHECK_STACK_DEPTH();
                   #  # ]
     483                 :             : 
     484                 :             :         /* Save the last few bits of error state into the stack entry */
     485                 :       69120 :         set_stack_entry_location(edata, filename, lineno, funcname);
     486                 :             : 
     487                 :       69120 :         elevel = edata->elevel;
     488                 :             : 
     489                 :             :         /*
     490                 :             :          * Do processing in ErrorContext, which we hope has enough reserved space
     491                 :             :          * to report an error.
     492                 :             :          */
     493                 :       69120 :         oldcontext = MemoryContextSwitchTo(ErrorContext);
     494                 :             : 
     495                 :             :         /* Collect backtrace, if enabled and we didn't already */
     496         [ +  - ]:       69120 :         if (!edata->backtrace &&
     497         [ +  - ]:       69120 :                 edata->funcname &&
     498   [ +  -  +  - ]:       69120 :                 backtrace_functions &&
     499                 :       69120 :                 matches_backtrace_functions(edata->funcname))
     500                 :           0 :                 set_backtrace(edata, 2);
     501                 :             : 
     502                 :             :         /*
     503                 :             :          * Call any context callback functions.  Errors occurring in callback
     504                 :             :          * functions will be treated as recursive errors --- this ensures we will
     505                 :             :          * avoid infinite recursion (see errstart).
     506                 :             :          */
     507         [ +  + ]:       78164 :         for (econtext = error_context_stack;
     508                 :       78164 :                  econtext != NULL;
     509                 :        9044 :                  econtext = econtext->previous)
     510                 :        9044 :                 econtext->callback(econtext->arg);
     511                 :             : 
     512                 :             :         /*
     513                 :             :          * If ERROR (not more nor less) we pass it off to the current handler.
     514                 :             :          * Printing it and popping the stack is the responsibility of the handler.
     515                 :             :          */
     516         [ +  + ]:       69120 :         if (elevel == ERROR)
     517                 :             :         {
     518                 :             :                 /*
     519                 :             :                  * We do some minimal cleanup before longjmp'ing so that handlers can
     520                 :             :                  * execute in a reasonably sane state.
     521                 :             :                  *
     522                 :             :                  * Reset InterruptHoldoffCount in case we ereport'd from inside an
     523                 :             :                  * interrupt holdoff section.  (We assume here that no handler will
     524                 :             :                  * itself be inside a holdoff section.  If necessary, such a handler
     525                 :             :                  * could save and restore InterruptHoldoffCount for itself, but this
     526                 :             :                  * should make life easier for most.)
     527                 :             :                  */
     528                 :        7783 :                 InterruptHoldoffCount = 0;
     529                 :        7783 :                 QueryCancelHoldoffCount = 0;
     530                 :             : 
     531                 :        7783 :                 CritSectionCount = 0;   /* should be unnecessary, but... */
     532                 :             : 
     533                 :             :                 /*
     534                 :             :                  * Note that we leave CurrentMemoryContext set to ErrorContext. The
     535                 :             :                  * handler should reset it to something else soon.
     536                 :             :                  */
     537                 :             : 
     538                 :        7783 :                 recursion_depth--;
     539                 :        7783 :                 PG_RE_THROW();
     540                 :             :         }
     541                 :             : 
     542                 :             :         /* Emit the message to the right places */
     543                 :       61337 :         EmitErrorReport();
     544                 :             : 
     545                 :             :         /*
     546                 :             :          * If this is the outermost recursion level, we can clean up by resetting
     547                 :             :          * ErrorContext altogether (compare FlushErrorState), which is good
     548                 :             :          * because it cleans up any random leakages that might have occurred in
     549                 :             :          * places such as context callback functions.  If we're nested, we can
     550                 :             :          * only safely remove the subsidiary data of the current stack entry.
     551                 :             :          */
     552   [ +  -  -  + ]:       61337 :         if (errordata_stack_depth == 0 && recursion_depth == 1)
     553                 :       61337 :                 MemoryContextReset(ErrorContext);
     554                 :             :         else
     555                 :           0 :                 FreeErrorDataContents(edata);
     556                 :             : 
     557                 :             :         /* Release stack entry and exit error-handling context */
     558                 :       61337 :         errordata_stack_depth--;
     559                 :       61337 :         MemoryContextSwitchTo(oldcontext);
     560                 :       61337 :         recursion_depth--;
     561                 :             : 
     562                 :             :         /*
     563                 :             :          * Perform error recovery action as specified by elevel.
     564                 :             :          */
     565         [ +  + ]:       61337 :         if (elevel == FATAL)
     566                 :             :         {
     567                 :             :                 /*
     568                 :             :                  * For a FATAL error, we let proc_exit clean up and exit.
     569                 :             :                  *
     570                 :             :                  * If we just reported a startup failure, the client will disconnect
     571                 :             :                  * on receiving it, so don't send any more to the client.
     572                 :             :                  */
     573   [ -  +  #  # ]:           1 :                 if (PG_exception_stack == NULL && whereToSendOutput == DestRemote)
     574                 :           0 :                         whereToSendOutput = DestNone;
     575                 :             : 
     576                 :             :                 /*
     577                 :             :                  * fflush here is just to improve the odds that we get to see the
     578                 :             :                  * error message, in case things are so hosed that proc_exit crashes.
     579                 :             :                  * Any other code you might be tempted to add here should probably be
     580                 :             :                  * in an on_proc_exit or on_shmem_exit callback instead.
     581                 :             :                  */
     582                 :           1 :                 fflush(NULL);
     583                 :             : 
     584                 :             :                 /*
     585                 :             :                  * Let the cumulative stats system know. Only mark the session as
     586                 :             :                  * terminated by fatal error if there is no other known cause.
     587                 :             :                  */
     588         [ +  - ]:           1 :                 if (pgStatSessionEndCause == DISCONNECT_NORMAL)
     589                 :           0 :                         pgStatSessionEndCause = DISCONNECT_FATAL;
     590                 :             : 
     591                 :             :                 /*
     592                 :             :                  * Do normal process-exit cleanup, then return exit code 1 to indicate
     593                 :             :                  * FATAL termination.  The postmaster may or may not consider this
     594                 :             :                  * worthy of panic, depending on which subprocess returns it.
     595                 :             :                  */
     596                 :           1 :                 proc_exit(1);
     597                 :             :         }
     598                 :             : 
     599         [ +  - ]:       61336 :         if (elevel >= PANIC)
     600                 :             :         {
     601                 :             :                 /*
     602                 :             :                  * Serious crash time. Postmaster will observe SIGABRT process exit
     603                 :             :                  * status and kill the other backends too.
     604                 :             :                  *
     605                 :             :                  * XXX: what if we are *in* the postmaster?  abort() won't kill our
     606                 :             :                  * children...
     607                 :             :                  */
     608                 :           0 :                 fflush(NULL);
     609                 :           0 :                 abort();
     610                 :             :         }
     611                 :             : 
     612                 :             :         /*
     613                 :             :          * Check for cancel/die interrupt first --- this is so that the user can
     614                 :             :          * stop a query emitting tons of notice or warning messages, even if it's
     615                 :             :          * in a loop that otherwise fails to check for interrupts.
     616                 :             :          */
     617         [ +  + ]:       61336 :         CHECK_FOR_INTERRUPTS();
     618                 :       61336 : }
     619                 :             : 
     620                 :             : 
     621                 :             : /*
     622                 :             :  * errsave_start --- begin a "soft" error-reporting cycle
     623                 :             :  *
     624                 :             :  * If "context" isn't an ErrorSaveContext node, this behaves as
     625                 :             :  * errstart(ERROR, domain), and the errsave() macro ends up acting
     626                 :             :  * exactly like ereport(ERROR, ...).
     627                 :             :  *
     628                 :             :  * If "context" is an ErrorSaveContext node, but the node creator only wants
     629                 :             :  * notification of the fact of a soft error without any details, we just set
     630                 :             :  * the error_occurred flag in the ErrorSaveContext node and return false,
     631                 :             :  * which will cause us to skip the remaining error processing steps.
     632                 :             :  *
     633                 :             :  * Otherwise, create and initialize error stack entry and return true.
     634                 :             :  * Subsequently, errmsg() and perhaps other routines will be called to further
     635                 :             :  * populate the stack entry.  Finally, errsave_finish() will be called to
     636                 :             :  * tidy up.
     637                 :             :  */
     638                 :             : bool
     639                 :        8519 : errsave_start(struct Node *context, const char *domain)
     640                 :             : {
     641                 :        8519 :         ErrorSaveContext *escontext;
     642                 :        8519 :         ErrorData  *edata;
     643                 :             : 
     644                 :             :         /*
     645                 :             :          * Do we have a context for soft error reporting?  If not, just punt to
     646                 :             :          * errstart().
     647                 :             :          */
     648   [ +  +  -  + ]:        8519 :         if (context == NULL || !IsA(context, ErrorSaveContext))
     649                 :        1143 :                 return errstart(ERROR, domain);
     650                 :             : 
     651                 :             :         /* Report that a soft error was detected */
     652                 :        7376 :         escontext = (ErrorSaveContext *) context;
     653                 :        7376 :         escontext->error_occurred = true;
     654                 :             : 
     655                 :             :         /* Nothing else to do if caller wants no further details */
     656         [ +  + ]:        7376 :         if (!escontext->details_wanted)
     657                 :        7167 :                 return false;
     658                 :             : 
     659                 :             :         /*
     660                 :             :          * Okay, crank up a stack entry to store the info in.
     661                 :             :          */
     662                 :             : 
     663                 :         209 :         recursion_depth++;
     664                 :             : 
     665                 :             :         /* Initialize data for this error frame */
     666                 :         209 :         edata = get_error_stack_entry();
     667                 :         209 :         edata->elevel = LOG;         /* signal all is well to errsave_finish */
     668                 :         209 :         set_stack_entry_domain(edata, domain);
     669                 :             :         /* Select default errcode based on the assumed elevel of ERROR */
     670                 :         209 :         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
     671                 :             : 
     672                 :             :         /*
     673                 :             :          * Any allocations for this error state level should go into the caller's
     674                 :             :          * context.  We don't need to pollute ErrorContext, or even require it to
     675                 :             :          * exist, in this code path.
     676                 :             :          */
     677                 :         209 :         edata->assoc_context = CurrentMemoryContext;
     678                 :             : 
     679                 :         209 :         recursion_depth--;
     680                 :         209 :         return true;
     681                 :        8519 : }
     682                 :             : 
     683                 :             : /*
     684                 :             :  * errsave_finish --- end a "soft" error-reporting cycle
     685                 :             :  *
     686                 :             :  * If errsave_start() decided this was a regular error, behave as
     687                 :             :  * errfinish().  Otherwise, package up the error details and save
     688                 :             :  * them in the ErrorSaveContext node.
     689                 :             :  */
     690                 :             : void
     691                 :        1352 : errsave_finish(struct Node *context, const char *filename, int lineno,
     692                 :             :                            const char *funcname)
     693                 :             : {
     694                 :        1352 :         ErrorSaveContext *escontext = (ErrorSaveContext *) context;
     695                 :        1352 :         ErrorData  *edata = &errordata[errordata_stack_depth];
     696                 :             : 
     697                 :             :         /* verify stack depth before accessing *edata */
     698   [ +  -  #  #  :        1352 :         CHECK_STACK_DEPTH();
                   #  # ]
     699                 :             : 
     700                 :             :         /*
     701                 :             :          * If errsave_start punted to errstart, then elevel will be ERROR or
     702                 :             :          * perhaps even PANIC.  Punt likewise to errfinish.
     703                 :             :          */
     704         [ +  + ]:        1352 :         if (edata->elevel >= ERROR)
     705                 :             :         {
     706                 :        1143 :                 errfinish(filename, lineno, funcname);
     707                 :        1143 :                 pg_unreachable();
     708                 :             :         }
     709                 :             : 
     710                 :             :         /*
     711                 :             :          * Else, we should package up the stack entry contents and deliver them to
     712                 :             :          * the caller.
     713                 :             :          */
     714                 :         209 :         recursion_depth++;
     715                 :             : 
     716                 :             :         /* Save the last few bits of error state into the stack entry */
     717                 :         209 :         set_stack_entry_location(edata, filename, lineno, funcname);
     718                 :             : 
     719                 :             :         /* Replace the LOG value that errsave_start inserted */
     720                 :         209 :         edata->elevel = ERROR;
     721                 :             : 
     722                 :             :         /*
     723                 :             :          * We skip calling backtrace and context functions, which are more likely
     724                 :             :          * to cause trouble than provide useful context; they might act on the
     725                 :             :          * assumption that a transaction abort is about to occur.
     726                 :             :          */
     727                 :             : 
     728                 :             :         /*
     729                 :             :          * Make a copy of the error info for the caller.  All the subsidiary
     730                 :             :          * strings are already in the caller's context, so it's sufficient to
     731                 :             :          * flat-copy the stack entry.
     732                 :             :          */
     733                 :         209 :         escontext->error_data = palloc_object(ErrorData);
     734                 :         209 :         memcpy(escontext->error_data, edata, sizeof(ErrorData));
     735                 :             : 
     736                 :             :         /* Exit error-handling context */
     737                 :         209 :         errordata_stack_depth--;
     738                 :         209 :         recursion_depth--;
     739                 :         209 : }
     740                 :             : 
     741                 :             : 
     742                 :             : /*
     743                 :             :  * get_error_stack_entry --- allocate and initialize a new stack entry
     744                 :             :  *
     745                 :             :  * The entry should be freed, when we're done with it, by calling
     746                 :             :  * FreeErrorDataContents() and then decrementing errordata_stack_depth.
     747                 :             :  *
     748                 :             :  * Returning the entry's address is just a notational convenience,
     749                 :             :  * since it had better be errordata[errordata_stack_depth].
     750                 :             :  *
     751                 :             :  * Although the error stack is not large, we don't expect to run out of space.
     752                 :             :  * Using more than one entry implies a new error report during error recovery,
     753                 :             :  * which is possible but already suggests we're in trouble.  If we exhaust the
     754                 :             :  * stack, almost certainly we are in an infinite loop of errors during error
     755                 :             :  * recovery, so we give up and PANIC.
     756                 :             :  *
     757                 :             :  * (Note that this is distinct from the recursion_depth checks, which
     758                 :             :  * guard against recursion while handling a single stack entry.)
     759                 :             :  */
     760                 :             : static ErrorData *
     761                 :       69343 : get_error_stack_entry(void)
     762                 :             : {
     763                 :       69343 :         ErrorData  *edata;
     764                 :             : 
     765                 :             :         /* Allocate error frame */
     766                 :       69343 :         errordata_stack_depth++;
     767         [ +  - ]:       69343 :         if (unlikely(errordata_stack_depth >= ERRORDATA_STACK_SIZE))
     768                 :             :         {
     769                 :             :                 /* Wups, stack not big enough */
     770                 :           0 :                 errordata_stack_depth = -1; /* make room on stack */
     771   [ #  #  #  # ]:           0 :                 ereport(PANIC, (errmsg_internal("ERRORDATA_STACK_SIZE exceeded")));
     772                 :           0 :         }
     773                 :             : 
     774                 :             :         /* Initialize error frame to all zeroes/NULLs */
     775                 :       69343 :         edata = &errordata[errordata_stack_depth];
     776                 :       69343 :         memset(edata, 0, sizeof(ErrorData));
     777                 :             : 
     778                 :             :         /* Save errno immediately to ensure error parameter eval can't change it */
     779                 :       69343 :         edata->saved_errno = errno;
     780                 :             : 
     781                 :      138686 :         return edata;
     782                 :       69343 : }
     783                 :             : 
     784                 :             : /*
     785                 :             :  * set_stack_entry_domain --- fill in the internationalization domain
     786                 :             :  */
     787                 :             : static void
     788                 :       69329 : set_stack_entry_domain(ErrorData *edata, const char *domain)
     789                 :             : {
     790                 :             :         /* the default text domain is the backend's */
     791         [ +  + ]:       69329 :         edata->domain = domain ? domain : PG_TEXTDOMAIN("postgres");
     792                 :             :         /* initialize context_domain the same way (see set_errcontext_domain()) */
     793                 :       69329 :         edata->context_domain = edata->domain;
     794                 :       69329 : }
     795                 :             : 
     796                 :             : /*
     797                 :             :  * set_stack_entry_location --- fill in code-location details
     798                 :             :  *
     799                 :             :  * Store the values of __FILE__, __LINE__, and __func__ from the call site.
     800                 :             :  * We make an effort to normalize __FILE__, since compilers are inconsistent
     801                 :             :  * about how much of the path they'll include, and we'd prefer that the
     802                 :             :  * behavior not depend on that (especially, that it not vary with build path).
     803                 :             :  */
     804                 :             : static void
     805                 :       69329 : set_stack_entry_location(ErrorData *edata,
     806                 :             :                                                  const char *filename, int lineno,
     807                 :             :                                                  const char *funcname)
     808                 :             : {
     809         [ -  + ]:       69329 :         if (filename)
     810                 :             :         {
     811                 :       69329 :                 const char *slash;
     812                 :             : 
     813                 :             :                 /* keep only base name, useful especially for vpath builds */
     814                 :       69329 :                 slash = strrchr(filename, '/');
     815         [ +  + ]:       69329 :                 if (slash)
     816                 :       69326 :                         filename = slash + 1;
     817                 :             :                 /* Some Windows compilers use backslashes in __FILE__ strings */
     818                 :       69329 :                 slash = strrchr(filename, '\\');
     819         [ +  - ]:       69329 :                 if (slash)
     820                 :           0 :                         filename = slash + 1;
     821                 :       69329 :         }
     822                 :             : 
     823                 :       69329 :         edata->filename = filename;
     824                 :       69329 :         edata->lineno = lineno;
     825                 :       69329 :         edata->funcname = funcname;
     826                 :       69329 : }
     827                 :             : 
     828                 :             : /*
     829                 :             :  * matches_backtrace_functions --- checks whether the given funcname matches
     830                 :             :  * backtrace_functions
     831                 :             :  *
     832                 :             :  * See check_backtrace_functions.
     833                 :             :  */
     834                 :             : static bool
     835                 :       69120 : matches_backtrace_functions(const char *funcname)
     836                 :             : {
     837                 :       69120 :         const char *p;
     838                 :             : 
     839   [ -  +  #  #  :       69120 :         if (!backtrace_function_list || funcname == NULL || funcname[0] == '\0')
                   #  # ]
     840                 :       69120 :                 return false;
     841                 :             : 
     842                 :           0 :         p = backtrace_function_list;
     843                 :           0 :         for (;;)
     844                 :             :         {
     845         [ #  # ]:           0 :                 if (*p == '\0')                 /* end of backtrace_function_list */
     846                 :           0 :                         break;
     847                 :             : 
     848         [ #  # ]:           0 :                 if (strcmp(funcname, p) == 0)
     849                 :           0 :                         return true;
     850                 :           0 :                 p += strlen(p) + 1;
     851                 :             :         }
     852                 :             : 
     853                 :           0 :         return false;
     854                 :       69120 : }
     855                 :             : 
     856                 :             : 
     857                 :             : /*
     858                 :             :  * errcode --- add SQLSTATE error code to the current error
     859                 :             :  *
     860                 :             :  * The code is expected to be represented as per MAKE_SQLSTATE().
     861                 :             :  */
     862                 :             : int
     863                 :        8223 : errcode(int sqlerrcode)
     864                 :             : {
     865                 :        8223 :         ErrorData  *edata = &errordata[errordata_stack_depth];
     866                 :             : 
     867                 :             :         /* we don't bother incrementing recursion_depth */
     868   [ +  -  #  #  :        8223 :         CHECK_STACK_DEPTH();
                   #  # ]
     869                 :             : 
     870                 :        8223 :         edata->sqlerrcode = sqlerrcode;
     871                 :             : 
     872                 :        8223 :         return 0;                                       /* return value does not matter */
     873                 :        8223 : }
     874                 :             : 
     875                 :             : 
     876                 :             : /*
     877                 :             :  * errcode_for_file_access --- add SQLSTATE error code to the current error
     878                 :             :  *
     879                 :             :  * The SQLSTATE code is chosen based on the saved errno value.  We assume
     880                 :             :  * that the failing operation was some type of disk file access.
     881                 :             :  *
     882                 :             :  * NOTE: the primary error message string should generally include %m
     883                 :             :  * when this is used.
     884                 :             :  */
     885                 :             : int
     886                 :           5 : errcode_for_file_access(void)
     887                 :             : {
     888                 :           5 :         ErrorData  *edata = &errordata[errordata_stack_depth];
     889                 :             : 
     890                 :             :         /* we don't bother incrementing recursion_depth */
     891   [ +  -  #  #  :           5 :         CHECK_STACK_DEPTH();
                   #  # ]
     892                 :             : 
     893   [ -  -  -  -  :           5 :         switch (edata->saved_errno)
          +  -  -  -  -  
                      - ]
     894                 :             :         {
     895                 :             :                         /* Permission-denied failures */
     896                 :             :                 case EPERM:                             /* Not super-user */
     897                 :             :                 case EACCES:                    /* Permission denied */
     898                 :             : #ifdef EROFS
     899                 :             :                 case EROFS:                             /* Read only file system */
     900                 :             : #endif
     901                 :           0 :                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_PRIVILEGE;
     902                 :           0 :                         break;
     903                 :             : 
     904                 :             :                         /* File not found */
     905                 :             :                 case ENOENT:                    /* No such file or directory */
     906                 :           5 :                         edata->sqlerrcode = ERRCODE_UNDEFINED_FILE;
     907                 :           5 :                         break;
     908                 :             : 
     909                 :             :                         /* Duplicate file */
     910                 :             :                 case EEXIST:                    /* File exists */
     911                 :           0 :                         edata->sqlerrcode = ERRCODE_DUPLICATE_FILE;
     912                 :           0 :                         break;
     913                 :             : 
     914                 :             :                         /* Wrong object type or state */
     915                 :             :                 case ENOTDIR:                   /* Not a directory */
     916                 :             :                 case EISDIR:                    /* Is a directory */
     917                 :             :                 case ENOTEMPTY:                 /* Directory not empty */
     918                 :           0 :                         edata->sqlerrcode = ERRCODE_WRONG_OBJECT_TYPE;
     919                 :           0 :                         break;
     920                 :             : 
     921                 :             :                         /* Insufficient resources */
     922                 :             :                 case ENOSPC:                    /* No space left on device */
     923                 :           0 :                         edata->sqlerrcode = ERRCODE_DISK_FULL;
     924                 :           0 :                         break;
     925                 :             : 
     926                 :             :                 case ENOMEM:                    /* Out of memory */
     927                 :           0 :                         edata->sqlerrcode = ERRCODE_OUT_OF_MEMORY;
     928                 :           0 :                         break;
     929                 :             : 
     930                 :             :                 case ENFILE:                    /* File table overflow */
     931                 :             :                 case EMFILE:                    /* Too many open files */
     932                 :           0 :                         edata->sqlerrcode = ERRCODE_INSUFFICIENT_RESOURCES;
     933                 :           0 :                         break;
     934                 :             : 
     935                 :             :                         /* Hardware failure */
     936                 :             :                 case EIO:                               /* I/O error */
     937                 :           0 :                         edata->sqlerrcode = ERRCODE_IO_ERROR;
     938                 :           0 :                         break;
     939                 :             : 
     940                 :             :                 case ENAMETOOLONG:              /* File name too long */
     941                 :           0 :                         edata->sqlerrcode = ERRCODE_FILE_NAME_TOO_LONG;
     942                 :           0 :                         break;
     943                 :             : 
     944                 :             :                         /* All else is classified as internal errors */
     945                 :             :                 default:
     946                 :           0 :                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
     947                 :           0 :                         break;
     948                 :             :         }
     949                 :             : 
     950                 :           5 :         return 0;                                       /* return value does not matter */
     951                 :           5 : }
     952                 :             : 
     953                 :             : /*
     954                 :             :  * errcode_for_socket_access --- add SQLSTATE error code to the current error
     955                 :             :  *
     956                 :             :  * The SQLSTATE code is chosen based on the saved errno value.  We assume
     957                 :             :  * that the failing operation was some type of socket access.
     958                 :             :  *
     959                 :             :  * NOTE: the primary error message string should generally include %m
     960                 :             :  * when this is used.
     961                 :             :  */
     962                 :             : int
     963                 :           0 : errcode_for_socket_access(void)
     964                 :             : {
     965                 :           0 :         ErrorData  *edata = &errordata[errordata_stack_depth];
     966                 :             : 
     967                 :             :         /* we don't bother incrementing recursion_depth */
     968   [ #  #  #  #  :           0 :         CHECK_STACK_DEPTH();
                   #  # ]
     969                 :             : 
     970         [ #  # ]:           0 :         switch (edata->saved_errno)
     971                 :             :         {
     972                 :             :                         /* Loss of connection */
     973                 :             :                 case ALL_CONNECTION_FAILURE_ERRNOS:
     974                 :           0 :                         edata->sqlerrcode = ERRCODE_CONNECTION_FAILURE;
     975                 :           0 :                         break;
     976                 :             : 
     977                 :             :                         /* All else is classified as internal errors */
     978                 :             :                 default:
     979                 :           0 :                         edata->sqlerrcode = ERRCODE_INTERNAL_ERROR;
     980                 :           0 :                         break;
     981                 :             :         }
     982                 :             : 
     983                 :           0 :         return 0;                                       /* return value does not matter */
     984                 :           0 : }
     985                 :             : 
     986                 :             : 
     987                 :             : /*
     988                 :             :  * This macro handles expansion of a format string and associated parameters;
     989                 :             :  * it's common code for errmsg(), errdetail(), etc.  Must be called inside
     990                 :             :  * a routine that is declared like "const char *fmt, ..." and has an edata
     991                 :             :  * pointer set up.  The message is assigned to edata->targetfield, or
     992                 :             :  * appended to it if appendval is true.  The message is subject to translation
     993                 :             :  * if translateit is true.
     994                 :             :  *
     995                 :             :  * Note: we pstrdup the buffer rather than just transferring its storage
     996                 :             :  * to the edata field because the buffer might be considerably larger than
     997                 :             :  * really necessary.
     998                 :             :  */
     999                 :             : #define EVALUATE_MESSAGE(domain, targetfield, appendval, translateit)   \
    1000                 :             :         { \
    1001                 :             :                 StringInfoData  buf; \
    1002                 :             :                 /* Internationalize the error format string */ \
    1003                 :             :                 if ((translateit) && !in_error_recursion_trouble()) \
    1004                 :             :                         fmt = dgettext((domain), fmt);                            \
    1005                 :             :                 initStringInfo(&buf); \
    1006                 :             :                 if ((appendval) && edata->targetfield) { \
    1007                 :             :                         appendStringInfoString(&buf, edata->targetfield); \
    1008                 :             :                         appendStringInfoChar(&buf, '\n'); \
    1009                 :             :                 } \
    1010                 :             :                 /* Generate actual output --- have to use appendStringInfoVA */ \
    1011                 :             :                 for (;;) \
    1012                 :             :                 { \
    1013                 :             :                         va_list         args; \
    1014                 :             :                         int                     needed; \
    1015                 :             :                         errno = edata->saved_errno; \
    1016                 :             :                         va_start(args, fmt); \
    1017                 :             :                         needed = appendStringInfoVA(&buf, fmt, args); \
    1018                 :             :                         va_end(args); \
    1019                 :             :                         if (needed == 0) \
    1020                 :             :                                 break; \
    1021                 :             :                         enlargeStringInfo(&buf, needed); \
    1022                 :             :                 } \
    1023                 :             :                 /* Save the completed message into the stack item */ \
    1024                 :             :                 if (edata->targetfield) \
    1025                 :             :                         pfree(edata->targetfield); \
    1026                 :             :                 edata->targetfield = pstrdup(buf.data); \
    1027                 :             :                 pfree(buf.data); \
    1028                 :             :         }
    1029                 :             : 
    1030                 :             : /*
    1031                 :             :  * Same as above, except for pluralized error messages.  The calling routine
    1032                 :             :  * must be declared like "const char *fmt_singular, const char *fmt_plural,
    1033                 :             :  * unsigned long n, ...".  Translation is assumed always wanted.
    1034                 :             :  */
    1035                 :             : #define EVALUATE_MESSAGE_PLURAL(domain, targetfield, appendval)  \
    1036                 :             :         { \
    1037                 :             :                 const char         *fmt; \
    1038                 :             :                 StringInfoData  buf; \
    1039                 :             :                 /* Internationalize the error format string */ \
    1040                 :             :                 if (!in_error_recursion_trouble()) \
    1041                 :             :                         fmt = dngettext((domain), fmt_singular, fmt_plural, n); \
    1042                 :             :                 else \
    1043                 :             :                         fmt = (n == 1 ? fmt_singular : fmt_plural); \
    1044                 :             :                 initStringInfo(&buf); \
    1045                 :             :                 if ((appendval) && edata->targetfield) { \
    1046                 :             :                         appendStringInfoString(&buf, edata->targetfield); \
    1047                 :             :                         appendStringInfoChar(&buf, '\n'); \
    1048                 :             :                 } \
    1049                 :             :                 /* Generate actual output --- have to use appendStringInfoVA */ \
    1050                 :             :                 for (;;) \
    1051                 :             :                 { \
    1052                 :             :                         va_list         args; \
    1053                 :             :                         int                     needed; \
    1054                 :             :                         errno = edata->saved_errno; \
    1055                 :             :                         va_start(args, n); \
    1056                 :             :                         needed = appendStringInfoVA(&buf, fmt, args); \
    1057                 :             :                         va_end(args); \
    1058                 :             :                         if (needed == 0) \
    1059                 :             :                                 break; \
    1060                 :             :                         enlargeStringInfo(&buf, needed); \
    1061                 :             :                 } \
    1062                 :             :                 /* Save the completed message into the stack item */ \
    1063                 :             :                 if (edata->targetfield) \
    1064                 :             :                         pfree(edata->targetfield); \
    1065                 :             :                 edata->targetfield = pstrdup(buf.data); \
    1066                 :             :                 pfree(buf.data); \
    1067                 :             :         }
    1068                 :             : 
    1069                 :             : 
    1070                 :             : /*
    1071                 :             :  * errmsg --- add a primary error message text to the current error
    1072                 :             :  *
    1073                 :             :  * In addition to the usual %-escapes recognized by printf, "%m" in
    1074                 :             :  * fmt is replaced by the error message for the caller's value of errno.
    1075                 :             :  *
    1076                 :             :  * Note: no newline is needed at the end of the fmt string, since
    1077                 :             :  * ereport will provide one for the output methods that need it.
    1078                 :             :  */
    1079                 :             : int
    1080                 :       66633 : errmsg(const char *fmt,...)
    1081                 :             : {
    1082                 :       66633 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1083                 :       66633 :         MemoryContext oldcontext;
    1084                 :             : 
    1085                 :       66633 :         recursion_depth++;
    1086   [ +  -  #  #  :       66633 :         CHECK_STACK_DEPTH();
                   #  # ]
    1087                 :       66633 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1088                 :             : 
    1089                 :       66633 :         edata->message_id = fmt;
    1090   [ -  +  +  +  :       66718 :         EVALUATE_MESSAGE(edata->domain, message, false, true);
             -  +  +  +  
                      + ]
    1091                 :             : 
    1092                 :       66633 :         MemoryContextSwitchTo(oldcontext);
    1093                 :       66633 :         recursion_depth--;
    1094                 :       66633 :         return 0;                                       /* return value does not matter */
    1095                 :       66633 : }
    1096                 :             : 
    1097                 :             : /*
    1098                 :             :  * Add a backtrace to the containing ereport() call.  This is intended to be
    1099                 :             :  * added temporarily during debugging.
    1100                 :             :  */
    1101                 :             : int
    1102                 :           0 : errbacktrace(void)
    1103                 :             : {
    1104                 :           0 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1105                 :           0 :         MemoryContext oldcontext;
    1106                 :             : 
    1107                 :           0 :         recursion_depth++;
    1108   [ #  #  #  #  :           0 :         CHECK_STACK_DEPTH();
                   #  # ]
    1109                 :           0 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1110                 :             : 
    1111                 :           0 :         set_backtrace(edata, 1);
    1112                 :             : 
    1113                 :           0 :         MemoryContextSwitchTo(oldcontext);
    1114                 :           0 :         recursion_depth--;
    1115                 :             : 
    1116                 :           0 :         return 0;
    1117                 :           0 : }
    1118                 :             : 
    1119                 :             : /*
    1120                 :             :  * Compute backtrace data and add it to the supplied ErrorData.  num_skip
    1121                 :             :  * specifies how many inner frames to skip.  Use this to avoid showing the
    1122                 :             :  * internal backtrace support functions in the backtrace.  This requires that
    1123                 :             :  * this and related functions are not inlined.
    1124                 :             :  */
    1125                 :             : static void
    1126                 :           0 : set_backtrace(ErrorData *edata, int num_skip)
    1127                 :             : {
    1128                 :           0 :         StringInfoData errtrace;
    1129                 :             : 
    1130                 :           0 :         initStringInfo(&errtrace);
    1131                 :             : 
    1132                 :             : #ifdef HAVE_BACKTRACE_SYMBOLS
    1133                 :             :         {
    1134                 :           0 :                 void       *buf[100];
    1135                 :           0 :                 int                     nframes;
    1136                 :           0 :                 char      **strfrms;
    1137                 :             : 
    1138                 :           0 :                 nframes = backtrace(buf, lengthof(buf));
    1139                 :           0 :                 strfrms = backtrace_symbols(buf, nframes);
    1140         [ #  # ]:           0 :                 if (strfrms != NULL)
    1141                 :             :                 {
    1142         [ #  # ]:           0 :                         for (int i = num_skip; i < nframes; i++)
    1143                 :           0 :                                 appendStringInfo(&errtrace, "\n%s", strfrms[i]);
    1144                 :           0 :                         free(strfrms);
    1145                 :           0 :                 }
    1146                 :             :                 else
    1147                 :           0 :                         appendStringInfoString(&errtrace,
    1148                 :             :                                                                    "insufficient memory for backtrace generation");
    1149                 :           0 :         }
    1150                 :             : #else
    1151                 :             :         appendStringInfoString(&errtrace,
    1152                 :             :                                                    "backtrace generation is not supported by this installation");
    1153                 :             : #endif
    1154                 :             : 
    1155                 :           0 :         edata->backtrace = errtrace.data;
    1156                 :           0 : }
    1157                 :             : 
    1158                 :             : /*
    1159                 :             :  * errmsg_internal --- add a primary error message text to the current error
    1160                 :             :  *
    1161                 :             :  * This is exactly like errmsg() except that strings passed to errmsg_internal
    1162                 :             :  * are not translated, and are customarily left out of the
    1163                 :             :  * internationalization message dictionary.  This should be used for "can't
    1164                 :             :  * happen" cases that are probably not worth spending translation effort on.
    1165                 :             :  * We also use this for certain cases where we *must* not try to translate
    1166                 :             :  * the message because the translation would fail and result in infinite
    1167                 :             :  * error recursion.
    1168                 :             :  */
    1169                 :             : int
    1170                 :        2599 : errmsg_internal(const char *fmt,...)
    1171                 :             : {
    1172                 :        2599 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1173                 :        2599 :         MemoryContext oldcontext;
    1174                 :             : 
    1175                 :        2599 :         recursion_depth++;
    1176   [ +  -  #  #  :        2599 :         CHECK_STACK_DEPTH();
                   #  # ]
    1177                 :        2599 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1178                 :             : 
    1179                 :        2599 :         edata->message_id = fmt;
    1180   [ -  +  -  -  :        2599 :         EVALUATE_MESSAGE(edata->domain, message, false, false);
                +  +  - ]
    1181                 :             : 
    1182                 :        2599 :         MemoryContextSwitchTo(oldcontext);
    1183                 :        2599 :         recursion_depth--;
    1184                 :        2599 :         return 0;                                       /* return value does not matter */
    1185                 :        2599 : }
    1186                 :             : 
    1187                 :             : 
    1188                 :             : /*
    1189                 :             :  * errmsg_plural --- add a primary error message text to the current error,
    1190                 :             :  * with support for pluralization of the message text
    1191                 :             :  */
    1192                 :             : int
    1193                 :          95 : errmsg_plural(const char *fmt_singular, const char *fmt_plural,
    1194                 :             :                           unsigned long n,...)
    1195                 :             : {
    1196                 :          95 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1197                 :          95 :         MemoryContext oldcontext;
    1198                 :             : 
    1199                 :          95 :         recursion_depth++;
    1200   [ +  -  #  #  :          95 :         CHECK_STACK_DEPTH();
                   #  # ]
    1201                 :          95 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1202                 :             : 
    1203                 :          95 :         edata->message_id = fmt_singular;
    1204   [ -  +  #  #  :          95 :         EVALUATE_MESSAGE_PLURAL(edata->domain, message, false);
          -  +  -  -  +  
                   +  - ]
    1205                 :             : 
    1206                 :          95 :         MemoryContextSwitchTo(oldcontext);
    1207                 :          95 :         recursion_depth--;
    1208                 :          95 :         return 0;                                       /* return value does not matter */
    1209                 :          95 : }
    1210                 :             : 
    1211                 :             : 
    1212                 :             : /*
    1213                 :             :  * errdetail --- add a detail error message text to the current error
    1214                 :             :  */
    1215                 :             : int
    1216                 :        1732 : errdetail(const char *fmt,...)
    1217                 :             : {
    1218                 :        1732 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1219                 :        1732 :         MemoryContext oldcontext;
    1220                 :             : 
    1221                 :        1732 :         recursion_depth++;
    1222   [ +  -  #  #  :        1732 :         CHECK_STACK_DEPTH();
                   #  # ]
    1223                 :        1732 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1224                 :             : 
    1225   [ -  +  -  +  :        1732 :         EVALUATE_MESSAGE(edata->domain, detail, false, true);
             -  -  +  +  
                      - ]
    1226                 :             : 
    1227                 :        1732 :         MemoryContextSwitchTo(oldcontext);
    1228                 :        1732 :         recursion_depth--;
    1229                 :        1732 :         return 0;                                       /* return value does not matter */
    1230                 :        1732 : }
    1231                 :             : 
    1232                 :             : 
    1233                 :             : /*
    1234                 :             :  * errdetail_internal --- add a detail error message text to the current error
    1235                 :             :  *
    1236                 :             :  * This is exactly like errdetail() except that strings passed to
    1237                 :             :  * errdetail_internal are not translated, and are customarily left out of the
    1238                 :             :  * internationalization message dictionary.  This should be used for detail
    1239                 :             :  * messages that seem not worth translating for one reason or another
    1240                 :             :  * (typically, that they don't seem to be useful to average users).
    1241                 :             :  */
    1242                 :             : int
    1243                 :         381 : errdetail_internal(const char *fmt,...)
    1244                 :             : {
    1245                 :         381 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1246                 :         381 :         MemoryContext oldcontext;
    1247                 :             : 
    1248                 :         381 :         recursion_depth++;
    1249   [ +  -  #  #  :         381 :         CHECK_STACK_DEPTH();
                   #  # ]
    1250                 :         381 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1251                 :             : 
    1252   [ +  +  -  +  :         384 :         EVALUATE_MESSAGE(edata->domain, detail, false, false);
                +  +  - ]
    1253                 :             : 
    1254                 :         381 :         MemoryContextSwitchTo(oldcontext);
    1255                 :         381 :         recursion_depth--;
    1256                 :         381 :         return 0;                                       /* return value does not matter */
    1257                 :         381 : }
    1258                 :             : 
    1259                 :             : 
    1260                 :             : /*
    1261                 :             :  * errdetail_log --- add a detail_log error message text to the current error
    1262                 :             :  */
    1263                 :             : int
    1264                 :         161 : errdetail_log(const char *fmt,...)
    1265                 :             : {
    1266                 :         161 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1267                 :         161 :         MemoryContext oldcontext;
    1268                 :             : 
    1269                 :         161 :         recursion_depth++;
    1270   [ +  -  #  #  :         161 :         CHECK_STACK_DEPTH();
                   #  # ]
    1271                 :         161 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1272                 :             : 
    1273   [ -  +  +  +  :         164 :         EVALUATE_MESSAGE(edata->domain, detail_log, false, true);
             -  +  +  +  
                      - ]
    1274                 :             : 
    1275                 :         161 :         MemoryContextSwitchTo(oldcontext);
    1276                 :         161 :         recursion_depth--;
    1277                 :         161 :         return 0;                                       /* return value does not matter */
    1278                 :         161 : }
    1279                 :             : 
    1280                 :             : /*
    1281                 :             :  * errdetail_log_plural --- add a detail_log error message text to the current error
    1282                 :             :  * with support for pluralization of the message text
    1283                 :             :  */
    1284                 :             : int
    1285                 :           2 : errdetail_log_plural(const char *fmt_singular, const char *fmt_plural,
    1286                 :             :                                          unsigned long n,...)
    1287                 :             : {
    1288                 :           2 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1289                 :           2 :         MemoryContext oldcontext;
    1290                 :             : 
    1291                 :           2 :         recursion_depth++;
    1292   [ +  -  #  #  :           2 :         CHECK_STACK_DEPTH();
                   #  # ]
    1293                 :           2 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1294                 :             : 
    1295   [ -  +  #  #  :           2 :         EVALUATE_MESSAGE_PLURAL(edata->domain, detail_log, false);
          -  +  -  -  +  
                   +  - ]
    1296                 :             : 
    1297                 :           2 :         MemoryContextSwitchTo(oldcontext);
    1298                 :           2 :         recursion_depth--;
    1299                 :           2 :         return 0;                                       /* return value does not matter */
    1300                 :           2 : }
    1301                 :             : 
    1302                 :             : 
    1303                 :             : /*
    1304                 :             :  * errdetail_plural --- add a detail error message text to the current error,
    1305                 :             :  * with support for pluralization of the message text
    1306                 :             :  */
    1307                 :             : int
    1308                 :           8 : errdetail_plural(const char *fmt_singular, const char *fmt_plural,
    1309                 :             :                                  unsigned long n,...)
    1310                 :             : {
    1311                 :           8 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1312                 :           8 :         MemoryContext oldcontext;
    1313                 :             : 
    1314                 :           8 :         recursion_depth++;
    1315   [ +  -  #  #  :           8 :         CHECK_STACK_DEPTH();
                   #  # ]
    1316                 :           8 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1317                 :             : 
    1318   [ -  +  #  #  :           8 :         EVALUATE_MESSAGE_PLURAL(edata->domain, detail, false);
          -  +  -  -  +  
                   +  - ]
    1319                 :             : 
    1320                 :           8 :         MemoryContextSwitchTo(oldcontext);
    1321                 :           8 :         recursion_depth--;
    1322                 :           8 :         return 0;                                       /* return value does not matter */
    1323                 :           8 : }
    1324                 :             : 
    1325                 :             : 
    1326                 :             : /*
    1327                 :             :  * errhint --- add a hint error message text to the current error
    1328                 :             :  */
    1329                 :             : int
    1330                 :         706 : errhint(const char *fmt,...)
    1331                 :             : {
    1332                 :         706 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1333                 :         706 :         MemoryContext oldcontext;
    1334                 :             : 
    1335                 :         706 :         recursion_depth++;
    1336   [ +  -  #  #  :         706 :         CHECK_STACK_DEPTH();
                   #  # ]
    1337                 :         706 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1338                 :             : 
    1339   [ -  +  -  +  :         706 :         EVALUATE_MESSAGE(edata->domain, hint, false, true);
             -  -  +  +  
                      - ]
    1340                 :             : 
    1341                 :         706 :         MemoryContextSwitchTo(oldcontext);
    1342                 :         706 :         recursion_depth--;
    1343                 :         706 :         return 0;                                       /* return value does not matter */
    1344                 :         706 : }
    1345                 :             : 
    1346                 :             : /*
    1347                 :             :  * errhint_internal --- add a hint error message text to the current error
    1348                 :             :  *
    1349                 :             :  * Non-translated version of errhint(), see also errmsg_internal().
    1350                 :             :  */
    1351                 :             : int
    1352                 :           1 : errhint_internal(const char *fmt,...)
    1353                 :             : {
    1354                 :           1 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1355                 :           1 :         MemoryContext oldcontext;
    1356                 :             : 
    1357                 :           1 :         recursion_depth++;
    1358   [ +  -  #  #  :           1 :         CHECK_STACK_DEPTH();
                   #  # ]
    1359                 :           1 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1360                 :             : 
    1361   [ -  +  -  -  :           1 :         EVALUATE_MESSAGE(edata->domain, hint, false, false);
                +  +  - ]
    1362                 :             : 
    1363                 :           1 :         MemoryContextSwitchTo(oldcontext);
    1364                 :           1 :         recursion_depth--;
    1365                 :           1 :         return 0;                                       /* return value does not matter */
    1366                 :           1 : }
    1367                 :             : 
    1368                 :             : /*
    1369                 :             :  * errhint_plural --- add a hint error message text to the current error,
    1370                 :             :  * with support for pluralization of the message text
    1371                 :             :  */
    1372                 :             : int
    1373                 :           0 : errhint_plural(const char *fmt_singular, const char *fmt_plural,
    1374                 :             :                            unsigned long n,...)
    1375                 :             : {
    1376                 :           0 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1377                 :           0 :         MemoryContext oldcontext;
    1378                 :             : 
    1379                 :           0 :         recursion_depth++;
    1380   [ #  #  #  #  :           0 :         CHECK_STACK_DEPTH();
                   #  # ]
    1381                 :           0 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1382                 :             : 
    1383   [ #  #  #  #  :           0 :         EVALUATE_MESSAGE_PLURAL(edata->domain, hint, false);
          #  #  #  #  #  
                   #  # ]
    1384                 :             : 
    1385                 :           0 :         MemoryContextSwitchTo(oldcontext);
    1386                 :           0 :         recursion_depth--;
    1387                 :           0 :         return 0;                                       /* return value does not matter */
    1388                 :           0 : }
    1389                 :             : 
    1390                 :             : 
    1391                 :             : /*
    1392                 :             :  * errcontext_msg --- add a context error message text to the current error
    1393                 :             :  *
    1394                 :             :  * Unlike other cases, multiple calls are allowed to build up a stack of
    1395                 :             :  * context information.  We assume earlier calls represent more-closely-nested
    1396                 :             :  * states.
    1397                 :             :  */
    1398                 :             : int
    1399                 :        8228 : errcontext_msg(const char *fmt,...)
    1400                 :             : {
    1401                 :        8228 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1402                 :        8228 :         MemoryContext oldcontext;
    1403                 :             : 
    1404                 :        8228 :         recursion_depth++;
    1405   [ +  -  #  #  :        8228 :         CHECK_STACK_DEPTH();
                   #  # ]
    1406                 :        8228 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1407                 :             : 
    1408   [ -  +  +  +  :        8236 :         EVALUATE_MESSAGE(edata->context_domain, context, true, true);
          +  +  -  +  +  
                   +  + ]
    1409                 :             : 
    1410                 :        8228 :         MemoryContextSwitchTo(oldcontext);
    1411                 :        8228 :         recursion_depth--;
    1412                 :        8228 :         return 0;                                       /* return value does not matter */
    1413                 :        8228 : }
    1414                 :             : 
    1415                 :             : /*
    1416                 :             :  * set_errcontext_domain --- set message domain to be used by errcontext()
    1417                 :             :  *
    1418                 :             :  * errcontext_msg() can be called from a different module than the original
    1419                 :             :  * ereport(), so we cannot use the message domain passed in errstart() to
    1420                 :             :  * translate it.  Instead, each errcontext_msg() call should be preceded by
    1421                 :             :  * a set_errcontext_domain() call to specify the domain.  This is usually
    1422                 :             :  * done transparently by the errcontext() macro.
    1423                 :             :  */
    1424                 :             : int
    1425                 :        8228 : set_errcontext_domain(const char *domain)
    1426                 :             : {
    1427                 :        8228 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1428                 :             : 
    1429                 :             :         /* we don't bother incrementing recursion_depth */
    1430   [ +  -  #  #  :        8228 :         CHECK_STACK_DEPTH();
                   #  # ]
    1431                 :             : 
    1432                 :             :         /* the default text domain is the backend's */
    1433         [ +  + ]:        8228 :         edata->context_domain = domain ? domain : PG_TEXTDOMAIN("postgres");
    1434                 :             : 
    1435                 :        8228 :         return 0;                                       /* return value does not matter */
    1436                 :        8228 : }
    1437                 :             : 
    1438                 :             : 
    1439                 :             : /*
    1440                 :             :  * errhidestmt --- optionally suppress STATEMENT: field of log entry
    1441                 :             :  *
    1442                 :             :  * This should be called if the message text already includes the statement.
    1443                 :             :  */
    1444                 :             : int
    1445                 :       57642 : errhidestmt(bool hide_stmt)
    1446                 :             : {
    1447                 :       57642 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1448                 :             : 
    1449                 :             :         /* we don't bother incrementing recursion_depth */
    1450   [ +  -  #  #  :       57642 :         CHECK_STACK_DEPTH();
                   #  # ]
    1451                 :             : 
    1452                 :       57642 :         edata->hide_stmt = hide_stmt;
    1453                 :             : 
    1454                 :       57642 :         return 0;                                       /* return value does not matter */
    1455                 :       57642 : }
    1456                 :             : 
    1457                 :             : /*
    1458                 :             :  * errhidecontext --- optionally suppress CONTEXT: field of log entry
    1459                 :             :  *
    1460                 :             :  * This should only be used for verbose debugging messages where the repeated
    1461                 :             :  * inclusion of context would bloat the log volume too much.
    1462                 :             :  */
    1463                 :             : int
    1464                 :         262 : errhidecontext(bool hide_ctx)
    1465                 :             : {
    1466                 :         262 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1467                 :             : 
    1468                 :             :         /* we don't bother incrementing recursion_depth */
    1469   [ +  -  #  #  :         262 :         CHECK_STACK_DEPTH();
                   #  # ]
    1470                 :             : 
    1471                 :         262 :         edata->hide_ctx = hide_ctx;
    1472                 :             : 
    1473                 :         262 :         return 0;                                       /* return value does not matter */
    1474                 :         262 : }
    1475                 :             : 
    1476                 :             : /*
    1477                 :             :  * errposition --- add cursor position to the current error
    1478                 :             :  */
    1479                 :             : int
    1480                 :        1830 : errposition(int cursorpos)
    1481                 :             : {
    1482                 :        1830 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1483                 :             : 
    1484                 :             :         /* we don't bother incrementing recursion_depth */
    1485   [ +  -  #  #  :        1830 :         CHECK_STACK_DEPTH();
                   #  # ]
    1486                 :             : 
    1487                 :        1830 :         edata->cursorpos = cursorpos;
    1488                 :             : 
    1489                 :        1830 :         return 0;                                       /* return value does not matter */
    1490                 :        1830 : }
    1491                 :             : 
    1492                 :             : /*
    1493                 :             :  * internalerrposition --- add internal cursor position to the current error
    1494                 :             :  */
    1495                 :             : int
    1496                 :          57 : internalerrposition(int cursorpos)
    1497                 :             : {
    1498                 :          57 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1499                 :             : 
    1500                 :             :         /* we don't bother incrementing recursion_depth */
    1501   [ +  -  #  #  :          57 :         CHECK_STACK_DEPTH();
                   #  # ]
    1502                 :             : 
    1503                 :          57 :         edata->internalpos = cursorpos;
    1504                 :             : 
    1505                 :          57 :         return 0;                                       /* return value does not matter */
    1506                 :          57 : }
    1507                 :             : 
    1508                 :             : /*
    1509                 :             :  * internalerrquery --- add internal query text to the current error
    1510                 :             :  *
    1511                 :             :  * Can also pass NULL to drop the internal query text entry.  This case
    1512                 :             :  * is intended for use in error callback subroutines that are editorializing
    1513                 :             :  * on the layout of the error report.
    1514                 :             :  */
    1515                 :             : int
    1516                 :          55 : internalerrquery(const char *query)
    1517                 :             : {
    1518                 :          55 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1519                 :             : 
    1520                 :             :         /* we don't bother incrementing recursion_depth */
    1521   [ +  -  #  #  :          55 :         CHECK_STACK_DEPTH();
                   #  # ]
    1522                 :             : 
    1523         [ +  + ]:          55 :         if (edata->internalquery)
    1524                 :             :         {
    1525                 :          21 :                 pfree(edata->internalquery);
    1526                 :          21 :                 edata->internalquery = NULL;
    1527                 :          21 :         }
    1528                 :             : 
    1529         [ +  + ]:          55 :         if (query)
    1530                 :          31 :                 edata->internalquery = MemoryContextStrdup(edata->assoc_context, query);
    1531                 :             : 
    1532                 :          55 :         return 0;                                       /* return value does not matter */
    1533                 :          55 : }
    1534                 :             : 
    1535                 :             : /*
    1536                 :             :  * err_generic_string -- used to set individual ErrorData string fields
    1537                 :             :  * identified by PG_DIAG_xxx codes.
    1538                 :             :  *
    1539                 :             :  * This intentionally only supports fields that don't use localized strings,
    1540                 :             :  * so that there are no translation considerations.
    1541                 :             :  *
    1542                 :             :  * Most potential callers should not use this directly, but instead prefer
    1543                 :             :  * higher-level abstractions, such as errtablecol() (see relcache.c).
    1544                 :             :  */
    1545                 :             : int
    1546                 :        1852 : err_generic_string(int field, const char *str)
    1547                 :             : {
    1548                 :        1852 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1549                 :             : 
    1550                 :             :         /* we don't bother incrementing recursion_depth */
    1551   [ +  -  #  #  :        1852 :         CHECK_STACK_DEPTH();
                   #  # ]
    1552                 :             : 
    1553   [ +  +  +  +  :        1852 :         switch (field)
                   +  - ]
    1554                 :             :         {
    1555                 :             :                 case PG_DIAG_SCHEMA_NAME:
    1556                 :         653 :                         set_errdata_field(edata->assoc_context, &edata->schema_name, str);
    1557                 :         653 :                         break;
    1558                 :             :                 case PG_DIAG_TABLE_NAME:
    1559                 :         545 :                         set_errdata_field(edata->assoc_context, &edata->table_name, str);
    1560                 :         545 :                         break;
    1561                 :             :                 case PG_DIAG_COLUMN_NAME:
    1562                 :          92 :                         set_errdata_field(edata->assoc_context, &edata->column_name, str);
    1563                 :          92 :                         break;
    1564                 :             :                 case PG_DIAG_DATATYPE_NAME:
    1565                 :         109 :                         set_errdata_field(edata->assoc_context, &edata->datatype_name, str);
    1566                 :         109 :                         break;
    1567                 :             :                 case PG_DIAG_CONSTRAINT_NAME:
    1568                 :         453 :                         set_errdata_field(edata->assoc_context, &edata->constraint_name, str);
    1569                 :         453 :                         break;
    1570                 :             :                 default:
    1571   [ #  #  #  # ]:           0 :                         elog(ERROR, "unsupported ErrorData field id: %d", field);
    1572                 :           0 :                         break;
    1573                 :             :         }
    1574                 :             : 
    1575                 :        1852 :         return 0;                                       /* return value does not matter */
    1576                 :        1852 : }
    1577                 :             : 
    1578                 :             : /*
    1579                 :             :  * set_errdata_field --- set an ErrorData string field
    1580                 :             :  */
    1581                 :             : static void
    1582                 :        1852 : set_errdata_field(MemoryContextData *cxt, char **ptr, const char *str)
    1583                 :             : {
    1584         [ +  - ]:        1852 :         Assert(*ptr == NULL);
    1585                 :        1852 :         *ptr = MemoryContextStrdup(cxt, str);
    1586                 :        1852 : }
    1587                 :             : 
    1588                 :             : /*
    1589                 :             :  * geterrcode --- return the currently set SQLSTATE error code
    1590                 :             :  *
    1591                 :             :  * This is only intended for use in error callback subroutines, since there
    1592                 :             :  * is no other place outside elog.c where the concept is meaningful.
    1593                 :             :  */
    1594                 :             : int
    1595                 :         872 : geterrcode(void)
    1596                 :             : {
    1597                 :         872 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1598                 :             : 
    1599                 :             :         /* we don't bother incrementing recursion_depth */
    1600   [ +  -  #  #  :         872 :         CHECK_STACK_DEPTH();
                   #  # ]
    1601                 :             : 
    1602                 :        1744 :         return edata->sqlerrcode;
    1603                 :         872 : }
    1604                 :             : 
    1605                 :             : /*
    1606                 :             :  * geterrposition --- return the currently set error position (0 if none)
    1607                 :             :  *
    1608                 :             :  * This is only intended for use in error callback subroutines, since there
    1609                 :             :  * is no other place outside elog.c where the concept is meaningful.
    1610                 :             :  */
    1611                 :             : int
    1612                 :        4843 : geterrposition(void)
    1613                 :             : {
    1614                 :        4843 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1615                 :             : 
    1616                 :             :         /* we don't bother incrementing recursion_depth */
    1617   [ +  -  #  #  :        4843 :         CHECK_STACK_DEPTH();
                   #  # ]
    1618                 :             : 
    1619                 :        9686 :         return edata->cursorpos;
    1620                 :        4843 : }
    1621                 :             : 
    1622                 :             : /*
    1623                 :             :  * getinternalerrposition --- same for internal error position
    1624                 :             :  *
    1625                 :             :  * This is only intended for use in error callback subroutines, since there
    1626                 :             :  * is no other place outside elog.c where the concept is meaningful.
    1627                 :             :  */
    1628                 :             : int
    1629                 :          30 : getinternalerrposition(void)
    1630                 :             : {
    1631                 :          30 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1632                 :             : 
    1633                 :             :         /* we don't bother incrementing recursion_depth */
    1634   [ +  -  #  #  :          30 :         CHECK_STACK_DEPTH();
                   #  # ]
    1635                 :             : 
    1636                 :          60 :         return edata->internalpos;
    1637                 :          30 : }
    1638                 :             : 
    1639                 :             : 
    1640                 :             : /*
    1641                 :             :  * Functions to allow construction of error message strings separately from
    1642                 :             :  * the ereport() call itself.
    1643                 :             :  *
    1644                 :             :  * The expected calling convention is
    1645                 :             :  *
    1646                 :             :  *      pre_format_elog_string(errno, domain), var = format_elog_string(format,...)
    1647                 :             :  *
    1648                 :             :  * which can be hidden behind a macro such as GUC_check_errdetail().  We
    1649                 :             :  * assume that any functions called in the arguments of format_elog_string()
    1650                 :             :  * cannot result in re-entrant use of these functions --- otherwise the wrong
    1651                 :             :  * text domain might be used, or the wrong errno substituted for %m.  This is
    1652                 :             :  * okay for the current usage with GUC check hooks, but might need further
    1653                 :             :  * effort someday.
    1654                 :             :  *
    1655                 :             :  * The result of format_elog_string() is stored in ErrorContext, and will
    1656                 :             :  * therefore survive until FlushErrorState() is called.
    1657                 :             :  */
    1658                 :             : static int      save_format_errnumber;
    1659                 :             : static const char *save_format_domain;
    1660                 :             : 
    1661                 :             : void
    1662                 :          26 : pre_format_elog_string(int errnumber, const char *domain)
    1663                 :             : {
    1664                 :             :         /* Save errno before evaluation of argument functions can change it */
    1665                 :          26 :         save_format_errnumber = errnumber;
    1666                 :             :         /* Save caller's text domain */
    1667                 :          26 :         save_format_domain = domain;
    1668                 :          26 : }
    1669                 :             : 
    1670                 :             : char *
    1671                 :          26 : format_elog_string(const char *fmt,...)
    1672                 :             : {
    1673                 :          26 :         ErrorData       errdata;
    1674                 :          26 :         ErrorData  *edata;
    1675                 :          26 :         MemoryContext oldcontext;
    1676                 :             : 
    1677                 :             :         /* Initialize a mostly-dummy error frame */
    1678                 :          26 :         edata = &errdata;
    1679   [ +  -  +  -  :         624 :         MemSet(edata, 0, sizeof(ErrorData));
          +  -  -  +  +  
                      + ]
    1680                 :             :         /* the default text domain is the backend's */
    1681         [ -  + ]:          26 :         edata->domain = save_format_domain ? save_format_domain : PG_TEXTDOMAIN("postgres");
    1682                 :             :         /* set the errno to be used to interpret %m */
    1683                 :          26 :         edata->saved_errno = save_format_errnumber;
    1684                 :             : 
    1685                 :          26 :         oldcontext = MemoryContextSwitchTo(ErrorContext);
    1686                 :             : 
    1687                 :          26 :         edata->message_id = fmt;
    1688   [ -  +  -  +  :          26 :         EVALUATE_MESSAGE(edata->domain, message, false, true);
             -  -  +  +  
                      - ]
    1689                 :             : 
    1690                 :          26 :         MemoryContextSwitchTo(oldcontext);
    1691                 :             : 
    1692                 :          52 :         return edata->message;
    1693                 :          26 : }
    1694                 :             : 
    1695                 :             : 
    1696                 :             : /*
    1697                 :             :  * Actual output of the top-of-stack error message
    1698                 :             :  *
    1699                 :             :  * In the ereport(ERROR) case this is called from PostgresMain (or not at all,
    1700                 :             :  * if the error is caught by somebody).  For all other severity levels this
    1701                 :             :  * is called by errfinish.
    1702                 :             :  */
    1703                 :             : void
    1704                 :       68102 : EmitErrorReport(void)
    1705                 :             : {
    1706                 :       68102 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1707                 :       68102 :         MemoryContext oldcontext;
    1708                 :             : 
    1709                 :       68102 :         recursion_depth++;
    1710   [ +  -  #  #  :       68102 :         CHECK_STACK_DEPTH();
                   #  # ]
    1711                 :       68102 :         oldcontext = MemoryContextSwitchTo(edata->assoc_context);
    1712                 :             : 
    1713                 :             :         /*
    1714                 :             :          * Reset the formatted timestamp fields before emitting any logs.  This
    1715                 :             :          * includes all the log destinations and emit_log_hook, as the latter
    1716                 :             :          * could use log_line_prefix or the formatted timestamps.
    1717                 :             :          */
    1718                 :       68102 :         saved_timeval_set = false;
    1719                 :       68102 :         formatted_log_time[0] = '\0';
    1720                 :             : 
    1721                 :             :         /*
    1722                 :             :          * Call hook before sending message to log.  The hook function is allowed
    1723                 :             :          * to turn off edata->output_to_server, so we must recheck that afterward.
    1724                 :             :          * Making any other change in the content of edata is not considered
    1725                 :             :          * supported.
    1726                 :             :          *
    1727                 :             :          * Note: the reason why the hook can only turn off output_to_server, and
    1728                 :             :          * not turn it on, is that it'd be unreliable: we will never get here at
    1729                 :             :          * all if errstart() deems the message uninteresting.  A hook that could
    1730                 :             :          * make decisions in that direction would have to hook into errstart(),
    1731                 :             :          * where it would have much less information available.  emit_log_hook is
    1732                 :             :          * intended for custom log filtering and custom log message transmission
    1733                 :             :          * mechanisms.
    1734                 :             :          *
    1735                 :             :          * The log hook has access to both the translated and original English
    1736                 :             :          * error message text, which is passed through to allow it to be used as a
    1737                 :             :          * message identifier. Note that the original text is not available for
    1738                 :             :          * detail, detail_log, hint and context text elements.
    1739                 :             :          */
    1740   [ +  +  +  - ]:       68102 :         if (edata->output_to_server && emit_log_hook)
    1741                 :           0 :                 (*emit_log_hook) (edata);
    1742                 :             : 
    1743                 :             :         /* Send to server log, if enabled */
    1744         [ +  + ]:       68102 :         if (edata->output_to_server)
    1745                 :       65674 :                 send_message_to_server_log(edata);
    1746                 :             : 
    1747                 :             :         /* Send to client, if enabled */
    1748         [ +  + ]:       68102 :         if (edata->output_to_client)
    1749                 :        9633 :                 send_message_to_frontend(edata);
    1750                 :             : 
    1751                 :       68102 :         MemoryContextSwitchTo(oldcontext);
    1752                 :       68102 :         recursion_depth--;
    1753                 :       68102 : }
    1754                 :             : 
    1755                 :             : /*
    1756                 :             :  * CopyErrorData --- obtain a copy of the topmost error stack entry
    1757                 :             :  *
    1758                 :             :  * This is only for use in error handler code.  The data is copied into the
    1759                 :             :  * current memory context, so callers should always switch away from
    1760                 :             :  * ErrorContext first; otherwise it will be lost when FlushErrorState is done.
    1761                 :             :  */
    1762                 :             : ErrorData *
    1763                 :        1024 : CopyErrorData(void)
    1764                 :             : {
    1765                 :        1024 :         ErrorData  *edata = &errordata[errordata_stack_depth];
    1766                 :        1024 :         ErrorData  *newedata;
    1767                 :             : 
    1768                 :             :         /*
    1769                 :             :          * we don't increment recursion_depth because out-of-memory here does not
    1770                 :             :          * indicate a problem within the error subsystem.
    1771                 :             :          */
    1772   [ +  -  #  #  :        1024 :         CHECK_STACK_DEPTH();
                   #  # ]
    1773                 :             : 
    1774         [ +  - ]:        1024 :         Assert(CurrentMemoryContext != ErrorContext);
    1775                 :             : 
    1776                 :             :         /* Copy the struct itself */
    1777                 :        1024 :         newedata = palloc_object(ErrorData);
    1778                 :        1024 :         memcpy(newedata, edata, sizeof(ErrorData));
    1779                 :             : 
    1780                 :             :         /*
    1781                 :             :          * Make copies of separately-allocated strings.  Note that we copy even
    1782                 :             :          * theoretically-constant strings such as filename.  This is because those
    1783                 :             :          * could point into JIT-created code segments that might get unloaded at
    1784                 :             :          * transaction cleanup.  In some cases we need the copied ErrorData to
    1785                 :             :          * survive transaction boundaries, so we'd better copy those strings too.
    1786                 :             :          */
    1787         [ -  + ]:        1024 :         if (newedata->filename)
    1788                 :        1024 :                 newedata->filename = pstrdup(newedata->filename);
    1789         [ -  + ]:        1024 :         if (newedata->funcname)
    1790                 :        1024 :                 newedata->funcname = pstrdup(newedata->funcname);
    1791         [ -  + ]:        1024 :         if (newedata->domain)
    1792                 :        1024 :                 newedata->domain = pstrdup(newedata->domain);
    1793         [ -  + ]:        1024 :         if (newedata->context_domain)
    1794                 :        1024 :                 newedata->context_domain = pstrdup(newedata->context_domain);
    1795         [ -  + ]:        1024 :         if (newedata->message)
    1796                 :        1024 :                 newedata->message = pstrdup(newedata->message);
    1797         [ +  + ]:        1024 :         if (newedata->detail)
    1798                 :          18 :                 newedata->detail = pstrdup(newedata->detail);
    1799         [ +  - ]:        1024 :         if (newedata->detail_log)
    1800                 :           0 :                 newedata->detail_log = pstrdup(newedata->detail_log);
    1801         [ +  + ]:        1024 :         if (newedata->hint)
    1802                 :           4 :                 newedata->hint = pstrdup(newedata->hint);
    1803         [ -  + ]:        1024 :         if (newedata->context)
    1804                 :        1024 :                 newedata->context = pstrdup(newedata->context);
    1805         [ +  - ]:        1024 :         if (newedata->backtrace)
    1806                 :           0 :                 newedata->backtrace = pstrdup(newedata->backtrace);
    1807         [ -  + ]:        1024 :         if (newedata->message_id)
    1808                 :        1024 :                 newedata->message_id = pstrdup(newedata->message_id);
    1809         [ +  + ]:        1024 :         if (newedata->schema_name)
    1810                 :           1 :                 newedata->schema_name = pstrdup(newedata->schema_name);
    1811         [ +  + ]:        1024 :         if (newedata->table_name)
    1812                 :           1 :                 newedata->table_name = pstrdup(newedata->table_name);
    1813         [ +  + ]:        1024 :         if (newedata->column_name)
    1814                 :           1 :                 newedata->column_name = pstrdup(newedata->column_name);
    1815         [ +  + ]:        1024 :         if (newedata->datatype_name)
    1816                 :           1 :                 newedata->datatype_name = pstrdup(newedata->datatype_name);
    1817         [ +  + ]:        1024 :         if (newedata->constraint_name)
    1818                 :           1 :                 newedata->constraint_name = pstrdup(newedata->constraint_name);
    1819         [ +  - ]:        1024 :         if (newedata->internalquery)
    1820                 :           0 :                 newedata->internalquery = pstrdup(newedata->internalquery);
    1821                 :             : 
    1822                 :             :         /* Use the calling context for string allocation */
    1823                 :        1024 :         newedata->assoc_context = CurrentMemoryContext;
    1824                 :             : 
    1825                 :        2048 :         return newedata;
    1826                 :        1024 : }
    1827                 :             : 
    1828                 :             : /*
    1829                 :             :  * FreeErrorData --- free the structure returned by CopyErrorData.
    1830                 :             :  *
    1831                 :             :  * Error handlers should use this in preference to assuming they know all
    1832                 :             :  * the separately-allocated fields.
    1833                 :             :  */
    1834                 :             : void
    1835                 :           0 : FreeErrorData(ErrorData *edata)
    1836                 :             : {
    1837                 :           0 :         FreeErrorDataContents(edata);
    1838                 :           0 :         pfree(edata);
    1839                 :           0 : }
    1840                 :             : 
    1841                 :             : /*
    1842                 :             :  * FreeErrorDataContents --- free the subsidiary data of an ErrorData.
    1843                 :             :  *
    1844                 :             :  * This can be used on either an error stack entry or a copied ErrorData.
    1845                 :             :  */
    1846                 :             : static void
    1847                 :           0 : FreeErrorDataContents(ErrorData *edata)
    1848                 :             : {
    1849         [ #  # ]:           0 :         if (edata->message)
    1850                 :           0 :                 pfree(edata->message);
    1851         [ #  # ]:           0 :         if (edata->detail)
    1852                 :           0 :                 pfree(edata->detail);
    1853         [ #  # ]:           0 :         if (edata->detail_log)
    1854                 :           0 :                 pfree(edata->detail_log);
    1855         [ #  # ]:           0 :         if (edata->hint)
    1856                 :           0 :                 pfree(edata->hint);
    1857         [ #  # ]:           0 :         if (edata->context)
    1858                 :           0 :                 pfree(edata->context);
    1859         [ #  # ]:           0 :         if (edata->backtrace)
    1860                 :           0 :                 pfree(edata->backtrace);
    1861         [ #  # ]:           0 :         if (edata->schema_name)
    1862                 :           0 :                 pfree(edata->schema_name);
    1863         [ #  # ]:           0 :         if (edata->table_name)
    1864                 :           0 :                 pfree(edata->table_name);
    1865         [ #  # ]:           0 :         if (edata->column_name)
    1866                 :           0 :                 pfree(edata->column_name);
    1867         [ #  # ]:           0 :         if (edata->datatype_name)
    1868                 :           0 :                 pfree(edata->datatype_name);
    1869         [ #  # ]:           0 :         if (edata->constraint_name)
    1870                 :           0 :                 pfree(edata->constraint_name);
    1871         [ #  # ]:           0 :         if (edata->internalquery)
    1872                 :           0 :                 pfree(edata->internalquery);
    1873                 :           0 : }
    1874                 :             : 
    1875                 :             : /*
    1876                 :             :  * FlushErrorState --- flush the error state after error recovery
    1877                 :             :  *
    1878                 :             :  * This should be called by an error handler after it's done processing
    1879                 :             :  * the error; or as soon as it's done CopyErrorData, if it intends to
    1880                 :             :  * do stuff that is likely to provoke another error.  You are not "out" of
    1881                 :             :  * the error subsystem until you have done this.
    1882                 :             :  */
    1883                 :             : void
    1884                 :        7787 : FlushErrorState(void)
    1885                 :             : {
    1886                 :             :         /*
    1887                 :             :          * Reset stack to empty.  The only case where it would be more than one
    1888                 :             :          * deep is if we serviced an error that interrupted construction of
    1889                 :             :          * another message.  We assume control escaped out of that message
    1890                 :             :          * construction and won't ever go back.
    1891                 :             :          */
    1892                 :        7787 :         errordata_stack_depth = -1;
    1893                 :        7787 :         recursion_depth = 0;
    1894                 :             :         /* Delete all data in ErrorContext */
    1895                 :        7787 :         MemoryContextReset(ErrorContext);
    1896                 :        7787 : }
    1897                 :             : 
    1898                 :             : /*
    1899                 :             :  * ThrowErrorData --- report an error described by an ErrorData structure
    1900                 :             :  *
    1901                 :             :  * This function should be called on an ErrorData structure that isn't stored
    1902                 :             :  * on the errordata stack and hasn't been processed yet. It will call
    1903                 :             :  * errstart() and errfinish() as needed, so those should not have already been
    1904                 :             :  * called.
    1905                 :             :  *
    1906                 :             :  * ThrowErrorData() is useful for handling soft errors. It's also useful for
    1907                 :             :  * re-reporting errors originally reported by background worker processes and
    1908                 :             :  * then propagated (with or without modification) to the backend responsible
    1909                 :             :  * for them.
    1910                 :             :  */
    1911                 :             : void
    1912                 :           3 : ThrowErrorData(ErrorData *edata)
    1913                 :             : {
    1914                 :           3 :         ErrorData  *newedata;
    1915                 :           3 :         MemoryContext oldcontext;
    1916                 :             : 
    1917         [ +  - ]:           3 :         if (!errstart(edata->elevel, edata->domain))
    1918                 :           0 :                 return;                                 /* error is not to be reported at all */
    1919                 :             : 
    1920                 :           3 :         newedata = &errordata[errordata_stack_depth];
    1921                 :           3 :         recursion_depth++;
    1922                 :           3 :         oldcontext = MemoryContextSwitchTo(newedata->assoc_context);
    1923                 :             : 
    1924                 :             :         /* Copy the supplied fields to the error stack entry. */
    1925         [ -  + ]:           3 :         if (edata->sqlerrcode != 0)
    1926                 :           3 :                 newedata->sqlerrcode = edata->sqlerrcode;
    1927         [ -  + ]:           3 :         if (edata->message)
    1928                 :           3 :                 newedata->message = pstrdup(edata->message);
    1929         [ +  - ]:           3 :         if (edata->detail)
    1930                 :           0 :                 newedata->detail = pstrdup(edata->detail);
    1931         [ +  - ]:           3 :         if (edata->detail_log)
    1932                 :           0 :                 newedata->detail_log = pstrdup(edata->detail_log);
    1933         [ +  - ]:           3 :         if (edata->hint)
    1934                 :           0 :                 newedata->hint = pstrdup(edata->hint);
    1935         [ +  + ]:           3 :         if (edata->context)
    1936                 :           2 :                 newedata->context = pstrdup(edata->context);
    1937         [ +  - ]:           3 :         if (edata->backtrace)
    1938                 :           0 :                 newedata->backtrace = pstrdup(edata->backtrace);
    1939                 :             :         /* assume message_id is not available */
    1940         [ +  - ]:           3 :         if (edata->schema_name)
    1941                 :           0 :                 newedata->schema_name = pstrdup(edata->schema_name);
    1942         [ +  - ]:           3 :         if (edata->table_name)
    1943                 :           0 :                 newedata->table_name = pstrdup(edata->table_name);
    1944         [ +  - ]:           3 :         if (edata->column_name)
    1945                 :           0 :                 newedata->column_name = pstrdup(edata->column_name);
    1946         [ +  - ]:           3 :         if (edata->datatype_name)
    1947                 :           0 :                 newedata->datatype_name = pstrdup(edata->datatype_name);
    1948         [ +  - ]:           3 :         if (edata->constraint_name)
    1949                 :           0 :                 newedata->constraint_name = pstrdup(edata->constraint_name);
    1950                 :           3 :         newedata->cursorpos = edata->cursorpos;
    1951                 :           3 :         newedata->internalpos = edata->internalpos;
    1952         [ +  - ]:           3 :         if (edata->internalquery)
    1953                 :           0 :                 newedata->internalquery = pstrdup(edata->internalquery);
    1954                 :             : 
    1955                 :           3 :         MemoryContextSwitchTo(oldcontext);
    1956                 :           3 :         recursion_depth--;
    1957                 :             : 
    1958                 :             :         /* Process the error. */
    1959                 :           3 :         errfinish(edata->filename, edata->lineno, edata->funcname);
    1960         [ -  + ]:           3 : }
    1961                 :             : 
    1962                 :             : /*
    1963                 :             :  * ReThrowError --- re-throw a previously copied error
    1964                 :             :  *
    1965                 :             :  * A handler can do CopyErrorData/FlushErrorState to get out of the error
    1966                 :             :  * subsystem, then do some processing, and finally ReThrowError to re-throw
    1967                 :             :  * the original error.  This is slower than just PG_RE_THROW() but should
    1968                 :             :  * be used if the "some processing" is likely to incur another error.
    1969                 :             :  */
    1970                 :             : void
    1971                 :           6 : ReThrowError(ErrorData *edata)
    1972                 :             : {
    1973                 :           6 :         ErrorData  *newedata;
    1974                 :             : 
    1975         [ +  - ]:           6 :         Assert(edata->elevel == ERROR);
    1976                 :             : 
    1977                 :             :         /* Push the data back into the error context */
    1978                 :           6 :         recursion_depth++;
    1979                 :           6 :         MemoryContextSwitchTo(ErrorContext);
    1980                 :             : 
    1981                 :           6 :         newedata = get_error_stack_entry();
    1982                 :           6 :         memcpy(newedata, edata, sizeof(ErrorData));
    1983                 :             : 
    1984                 :             :         /* Make copies of separately-allocated fields */
    1985         [ -  + ]:           6 :         if (newedata->message)
    1986                 :           6 :                 newedata->message = pstrdup(newedata->message);
    1987         [ +  + ]:           6 :         if (newedata->detail)
    1988                 :           4 :                 newedata->detail = pstrdup(newedata->detail);
    1989         [ +  - ]:           6 :         if (newedata->detail_log)
    1990                 :           0 :                 newedata->detail_log = pstrdup(newedata->detail_log);
    1991         [ +  - ]:           6 :         if (newedata->hint)
    1992                 :           0 :                 newedata->hint = pstrdup(newedata->hint);
    1993         [ -  + ]:           6 :         if (newedata->context)
    1994                 :           6 :                 newedata->context = pstrdup(newedata->context);
    1995         [ +  - ]:           6 :         if (newedata->backtrace)
    1996                 :           0 :                 newedata->backtrace = pstrdup(newedata->backtrace);
    1997         [ +  - ]:           6 :         if (newedata->schema_name)
    1998                 :           0 :                 newedata->schema_name = pstrdup(newedata->schema_name);
    1999         [ +  - ]:           6 :         if (newedata->table_name)
    2000                 :           0 :                 newedata->table_name = pstrdup(newedata->table_name);
    2001         [ +  - ]:           6 :         if (newedata->column_name)
    2002                 :           0 :                 newedata->column_name = pstrdup(newedata->column_name);
    2003         [ +  - ]:           6 :         if (newedata->datatype_name)
    2004                 :           0 :                 newedata->datatype_name = pstrdup(newedata->datatype_name);
    2005         [ +  - ]:           6 :         if (newedata->constraint_name)
    2006                 :           0 :                 newedata->constraint_name = pstrdup(newedata->constraint_name);
    2007         [ +  - ]:           6 :         if (newedata->internalquery)
    2008                 :           0 :                 newedata->internalquery = pstrdup(newedata->internalquery);
    2009                 :             : 
    2010                 :             :         /* Reset the assoc_context to be ErrorContext */
    2011                 :           6 :         newedata->assoc_context = ErrorContext;
    2012                 :             : 
    2013                 :           6 :         recursion_depth--;
    2014                 :           6 :         PG_RE_THROW();
    2015                 :             : }
    2016                 :             : 
    2017                 :             : /*
    2018                 :             :  * pg_re_throw --- out-of-line implementation of PG_RE_THROW() macro
    2019                 :             :  */
    2020                 :             : void
    2021                 :       14757 : pg_re_throw(void)
    2022                 :             : {
    2023                 :             :         /* If possible, throw the error to the next outer setjmp handler */
    2024         [ +  - ]:       14757 :         if (PG_exception_stack != NULL)
    2025                 :       14757 :                 siglongjmp(*PG_exception_stack, 1);
    2026                 :             :         else
    2027                 :             :         {
    2028                 :             :                 /*
    2029                 :             :                  * If we get here, elog(ERROR) was thrown inside a PG_TRY block, which
    2030                 :             :                  * we have now exited only to discover that there is no outer setjmp
    2031                 :             :                  * handler to pass the error to.  Had the error been thrown outside
    2032                 :             :                  * the block to begin with, we'd have promoted the error to FATAL, so
    2033                 :             :                  * the correct behavior is to make it FATAL now; that is, emit it and
    2034                 :             :                  * then call proc_exit.
    2035                 :             :                  */
    2036                 :           0 :                 ErrorData  *edata = &errordata[errordata_stack_depth];
    2037                 :             : 
    2038         [ #  # ]:           0 :                 Assert(errordata_stack_depth >= 0);
    2039         [ #  # ]:           0 :                 Assert(edata->elevel == ERROR);
    2040                 :           0 :                 edata->elevel = FATAL;
    2041                 :             : 
    2042                 :             :                 /*
    2043                 :             :                  * At least in principle, the increase in severity could have changed
    2044                 :             :                  * where-to-output decisions, so recalculate.
    2045                 :             :                  */
    2046                 :           0 :                 edata->output_to_server = should_output_to_server(FATAL);
    2047                 :           0 :                 edata->output_to_client = should_output_to_client(FATAL);
    2048                 :             : 
    2049                 :             :                 /*
    2050                 :             :                  * We can use errfinish() for the rest, but we don't want it to call
    2051                 :             :                  * any error context routines a second time.  Since we know we are
    2052                 :             :                  * about to exit, it should be OK to just clear the context stack.
    2053                 :             :                  */
    2054                 :           0 :                 error_context_stack = NULL;
    2055                 :             : 
    2056                 :           0 :                 errfinish(edata->filename, edata->lineno, edata->funcname);
    2057                 :           0 :         }
    2058                 :             : 
    2059                 :             :         /* Doesn't return ... */
    2060                 :           0 :         ExceptionalCondition("pg_re_throw tried to return", __FILE__, __LINE__);
    2061                 :             : }
    2062                 :             : 
    2063                 :             : 
    2064                 :             : /*
    2065                 :             :  * GetErrorContextStack - Return the context stack, for display/diags
    2066                 :             :  *
    2067                 :             :  * Returns a pstrdup'd string in the caller's context which includes the PG
    2068                 :             :  * error call stack.  It is the caller's responsibility to ensure this string
    2069                 :             :  * is pfree'd (or its context cleaned up) when done.
    2070                 :             :  *
    2071                 :             :  * This information is collected by traversing the error contexts and calling
    2072                 :             :  * each context's callback function, each of which is expected to call
    2073                 :             :  * errcontext() to return a string which can be presented to the user.
    2074                 :             :  */
    2075                 :             : char *
    2076                 :           8 : GetErrorContextStack(void)
    2077                 :             : {
    2078                 :           8 :         ErrorData  *edata;
    2079                 :           8 :         ErrorContextCallback *econtext;
    2080                 :             : 
    2081                 :             :         /*
    2082                 :             :          * Crank up a stack entry to store the info in.
    2083                 :             :          */
    2084                 :           8 :         recursion_depth++;
    2085                 :             : 
    2086                 :           8 :         edata = get_error_stack_entry();
    2087                 :             : 
    2088                 :             :         /*
    2089                 :             :          * Set up assoc_context to be the caller's context, so any allocations
    2090                 :             :          * done (which will include edata->context) will use their context.
    2091                 :             :          */
    2092                 :           8 :         edata->assoc_context = CurrentMemoryContext;
    2093                 :             : 
    2094                 :             :         /*
    2095                 :             :          * Call any context callback functions to collect the context information
    2096                 :             :          * into edata->context.
    2097                 :             :          *
    2098                 :             :          * Errors occurring in callback functions should go through the regular
    2099                 :             :          * error handling code which should handle any recursive errors, though we
    2100                 :             :          * double-check above, just in case.
    2101                 :             :          */
    2102         [ +  + ]:          32 :         for (econtext = error_context_stack;
    2103                 :          32 :                  econtext != NULL;
    2104                 :          24 :                  econtext = econtext->previous)
    2105                 :          24 :                 econtext->callback(econtext->arg);
    2106                 :             : 
    2107                 :             :         /*
    2108                 :             :          * Clean ourselves off the stack, any allocations done should have been
    2109                 :             :          * using edata->assoc_context, which we set up earlier to be the caller's
    2110                 :             :          * context, so we're free to just remove our entry off the stack and
    2111                 :             :          * decrement recursion depth and exit.
    2112                 :             :          */
    2113                 :           8 :         errordata_stack_depth--;
    2114                 :           8 :         recursion_depth--;
    2115                 :             : 
    2116                 :             :         /*
    2117                 :             :          * Return a pointer to the string the caller asked for, which should have
    2118                 :             :          * been allocated in their context.
    2119                 :             :          */
    2120                 :          16 :         return edata->context;
    2121                 :           8 : }
    2122                 :             : 
    2123                 :             : 
    2124                 :             : /*
    2125                 :             :  * Initialization of error output file
    2126                 :             :  */
    2127                 :             : void
    2128                 :         806 : DebugFileOpen(void)
    2129                 :             : {
    2130                 :         806 :         int                     fd,
    2131                 :             :                                 istty;
    2132                 :             : 
    2133         [ +  - ]:         806 :         if (OutputFileName[0])
    2134                 :             :         {
    2135                 :             :                 /*
    2136                 :             :                  * A debug-output file name was given.
    2137                 :             :                  *
    2138                 :             :                  * Make sure we can write the file, and find out if it's a tty.
    2139                 :             :                  */
    2140                 :           0 :                 if ((fd = open(OutputFileName, O_CREAT | O_APPEND | O_WRONLY,
    2141         [ #  # ]:           0 :                                            0666)) < 0)
    2142   [ #  #  #  # ]:           0 :                         ereport(FATAL,
    2143                 :             :                                         (errcode_for_file_access(),
    2144                 :             :                                          errmsg("could not open file \"%s\": %m", OutputFileName)));
    2145                 :           0 :                 istty = isatty(fd);
    2146                 :           0 :                 close(fd);
    2147                 :             : 
    2148                 :             :                 /*
    2149                 :             :                  * Redirect our stderr to the debug output file.
    2150                 :             :                  */
    2151         [ #  # ]:           0 :                 if (!freopen(OutputFileName, "a", stderr))
    2152   [ #  #  #  # ]:           0 :                         ereport(FATAL,
    2153                 :             :                                         (errcode_for_file_access(),
    2154                 :             :                                          errmsg("could not reopen file \"%s\" as stderr: %m",
    2155                 :             :                                                         OutputFileName)));
    2156                 :             : 
    2157                 :             :                 /*
    2158                 :             :                  * If the file is a tty and we're running under the postmaster, try to
    2159                 :             :                  * send stdout there as well (if it isn't a tty then stderr will block
    2160                 :             :                  * out stdout, so we may as well let stdout go wherever it was going
    2161                 :             :                  * before).
    2162                 :             :                  */
    2163   [ #  #  #  # ]:           0 :                 if (istty && IsUnderPostmaster)
    2164         [ #  # ]:           0 :                         if (!freopen(OutputFileName, "a", stdout))
    2165   [ #  #  #  # ]:           0 :                                 ereport(FATAL,
    2166                 :             :                                                 (errcode_for_file_access(),
    2167                 :             :                                                  errmsg("could not reopen file \"%s\" as stdout: %m",
    2168                 :             :                                                                 OutputFileName)));
    2169                 :           0 :         }
    2170                 :         806 : }
    2171                 :             : 
    2172                 :             : 
    2173                 :             : /*
    2174                 :             :  * GUC check_hook for backtrace_functions
    2175                 :             :  *
    2176                 :             :  * We split the input string, where commas separate function names
    2177                 :             :  * and certain whitespace chars are ignored, into a \0-separated (and
    2178                 :             :  * \0\0-terminated) list of function names.  This formulation allows
    2179                 :             :  * easy scanning when an error is thrown while avoiding the use of
    2180                 :             :  * non-reentrant strtok(), as well as keeping the output data in a
    2181                 :             :  * single palloc() chunk.
    2182                 :             :  */
    2183                 :             : bool
    2184                 :           6 : check_backtrace_functions(char **newval, void **extra, GucSource source)
    2185                 :             : {
    2186                 :           6 :         int                     newvallen = strlen(*newval);
    2187                 :           6 :         char       *someval;
    2188                 :           6 :         int                     validlen;
    2189                 :           6 :         int                     i;
    2190                 :           6 :         int                     j;
    2191                 :             : 
    2192                 :             :         /*
    2193                 :             :          * Allow characters that can be C identifiers and commas as separators, as
    2194                 :             :          * well as some whitespace for readability.
    2195                 :             :          */
    2196                 :           6 :         validlen = strspn(*newval,
    2197                 :             :                                           "0123456789_"
    2198                 :             :                                           "abcdefghijklmnopqrstuvwxyz"
    2199                 :             :                                           "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    2200                 :             :                                           ", \n\t");
    2201         [ -  + ]:           6 :         if (validlen != newvallen)
    2202                 :             :         {
    2203                 :           0 :                 GUC_check_errdetail("Invalid character.");
    2204                 :           0 :                 return false;
    2205                 :             :         }
    2206                 :             : 
    2207         [ -  + ]:           6 :         if (*newval[0] == '\0')
    2208                 :             :         {
    2209                 :           6 :                 *extra = NULL;
    2210                 :           6 :                 return true;
    2211                 :             :         }
    2212                 :             : 
    2213                 :             :         /*
    2214                 :             :          * Allocate space for the output and create the copy.  We could discount
    2215                 :             :          * whitespace chars to save some memory, but it doesn't seem worth the
    2216                 :             :          * trouble.
    2217                 :             :          */
    2218                 :           0 :         someval = guc_malloc(LOG, newvallen + 1 + 1);
    2219         [ #  # ]:           0 :         if (!someval)
    2220                 :           0 :                 return false;
    2221         [ #  # ]:           0 :         for (i = 0, j = 0; i < newvallen; i++)
    2222                 :             :         {
    2223         [ #  # ]:           0 :                 if ((*newval)[i] == ',')
    2224                 :           0 :                         someval[j++] = '\0';    /* next item */
    2225         [ #  # ]:           0 :                 else if ((*newval)[i] == ' ' ||
    2226   [ #  #  #  # ]:           0 :                                  (*newval)[i] == '\n' ||
    2227                 :           0 :                                  (*newval)[i] == '\t')
    2228                 :             :                         ;                                       /* ignore these */
    2229                 :             :                 else
    2230                 :           0 :                         someval[j++] = (*newval)[i];    /* copy anything else */
    2231                 :           0 :         }
    2232                 :             : 
    2233                 :             :         /* two \0s end the setting */
    2234                 :           0 :         someval[j] = '\0';
    2235                 :           0 :         someval[j + 1] = '\0';
    2236                 :             : 
    2237                 :           0 :         *extra = someval;
    2238                 :           0 :         return true;
    2239                 :           6 : }
    2240                 :             : 
    2241                 :             : /*
    2242                 :             :  * GUC assign_hook for backtrace_functions
    2243                 :             :  */
    2244                 :             : void
    2245                 :           6 : assign_backtrace_functions(const char *newval, void *extra)
    2246                 :             : {
    2247                 :           6 :         backtrace_function_list = (char *) extra;
    2248                 :           6 : }
    2249                 :             : 
    2250                 :             : /*
    2251                 :             :  * GUC check_hook for log_destination
    2252                 :             :  */
    2253                 :             : bool
    2254                 :           6 : check_log_destination(char **newval, void **extra, GucSource source)
    2255                 :             : {
    2256                 :           6 :         char       *rawstring;
    2257                 :           6 :         List       *elemlist;
    2258                 :           6 :         ListCell   *l;
    2259                 :           6 :         int                     newlogdest = 0;
    2260                 :           6 :         int                *myextra;
    2261                 :             : 
    2262                 :             :         /* Need a modifiable copy of string */
    2263                 :           6 :         rawstring = pstrdup(*newval);
    2264                 :             : 
    2265                 :             :         /* Parse string into list of identifiers */
    2266         [ +  - ]:           6 :         if (!SplitIdentifierString(rawstring, ',', &elemlist))
    2267                 :             :         {
    2268                 :             :                 /* syntax error in list */
    2269                 :           0 :                 GUC_check_errdetail("List syntax is invalid.");
    2270                 :           0 :                 pfree(rawstring);
    2271                 :           0 :                 list_free(elemlist);
    2272                 :           0 :                 return false;
    2273                 :             :         }
    2274                 :             : 
    2275   [ +  -  +  +  :          12 :         foreach(l, elemlist)
             +  +  -  + ]
    2276                 :             :         {
    2277                 :           6 :                 char       *tok = (char *) lfirst(l);
    2278                 :             : 
    2279         [ -  + ]:           6 :                 if (pg_strcasecmp(tok, "stderr") == 0)
    2280                 :           6 :                         newlogdest |= LOG_DESTINATION_STDERR;
    2281         [ #  # ]:           0 :                 else if (pg_strcasecmp(tok, "csvlog") == 0)
    2282                 :           0 :                         newlogdest |= LOG_DESTINATION_CSVLOG;
    2283         [ #  # ]:           0 :                 else if (pg_strcasecmp(tok, "jsonlog") == 0)
    2284                 :           0 :                         newlogdest |= LOG_DESTINATION_JSONLOG;
    2285                 :             : #ifdef HAVE_SYSLOG
    2286         [ #  # ]:           0 :                 else if (pg_strcasecmp(tok, "syslog") == 0)
    2287                 :           0 :                         newlogdest |= LOG_DESTINATION_SYSLOG;
    2288                 :             : #endif
    2289                 :             : #ifdef WIN32
    2290                 :             :                 else if (pg_strcasecmp(tok, "eventlog") == 0)
    2291                 :             :                         newlogdest |= LOG_DESTINATION_EVENTLOG;
    2292                 :             : #endif
    2293                 :             :                 else
    2294                 :             :                 {
    2295                 :           0 :                         GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
    2296                 :           0 :                         pfree(rawstring);
    2297                 :           0 :                         list_free(elemlist);
    2298                 :           0 :                         return false;
    2299                 :             :                 }
    2300         [ -  + ]:           6 :         }
    2301                 :             : 
    2302                 :           6 :         pfree(rawstring);
    2303                 :           6 :         list_free(elemlist);
    2304                 :             : 
    2305                 :           6 :         myextra = (int *) guc_malloc(LOG, sizeof(int));
    2306         [ +  - ]:           6 :         if (!myextra)
    2307                 :           0 :                 return false;
    2308                 :           6 :         *myextra = newlogdest;
    2309                 :           6 :         *extra = myextra;
    2310                 :             : 
    2311                 :           6 :         return true;
    2312                 :           6 : }
    2313                 :             : 
    2314                 :             : /*
    2315                 :             :  * GUC assign_hook for log_destination
    2316                 :             :  */
    2317                 :             : void
    2318                 :           6 : assign_log_destination(const char *newval, void *extra)
    2319                 :             : {
    2320                 :           6 :         Log_destination = *((int *) extra);
    2321                 :           6 : }
    2322                 :             : 
    2323                 :             : /*
    2324                 :             :  * GUC assign_hook for syslog_ident
    2325                 :             :  */
    2326                 :             : void
    2327                 :           6 : assign_syslog_ident(const char *newval, void *extra)
    2328                 :             : {
    2329                 :             : #ifdef HAVE_SYSLOG
    2330                 :             :         /*
    2331                 :             :          * guc.c is likely to call us repeatedly with same parameters, so don't
    2332                 :             :          * thrash the syslog connection unnecessarily.  Also, we do not re-open
    2333                 :             :          * the connection until needed, since this routine will get called whether
    2334                 :             :          * or not Log_destination actually mentions syslog.
    2335                 :             :          *
    2336                 :             :          * Note that we make our own copy of the ident string rather than relying
    2337                 :             :          * on guc.c's.  This may be overly paranoid, but it ensures that we cannot
    2338                 :             :          * accidentally free a string that syslog is still using.
    2339                 :             :          */
    2340   [ -  +  #  # ]:           6 :         if (syslog_ident == NULL || strcmp(syslog_ident, newval) != 0)
    2341                 :             :         {
    2342         [ +  - ]:           6 :                 if (openlog_done)
    2343                 :             :                 {
    2344                 :           0 :                         closelog();
    2345                 :           0 :                         openlog_done = false;
    2346                 :           0 :                 }
    2347                 :           6 :                 free(syslog_ident);
    2348                 :           6 :                 syslog_ident = strdup(newval);
    2349                 :             :                 /* if the strdup fails, we will cope in write_syslog() */
    2350                 :           6 :         }
    2351                 :             : #endif
    2352                 :             :         /* Without syslog support, just ignore it */
    2353                 :           6 : }
    2354                 :             : 
    2355                 :             : /*
    2356                 :             :  * GUC assign_hook for syslog_facility
    2357                 :             :  */
    2358                 :             : void
    2359                 :           6 : assign_syslog_facility(int newval, void *extra)
    2360                 :             : {
    2361                 :             : #ifdef HAVE_SYSLOG
    2362                 :             :         /*
    2363                 :             :          * As above, don't thrash the syslog connection unnecessarily.
    2364                 :             :          */
    2365         [ +  - ]:           6 :         if (syslog_facility != newval)
    2366                 :             :         {
    2367         [ #  # ]:           0 :                 if (openlog_done)
    2368                 :             :                 {
    2369                 :           0 :                         closelog();
    2370                 :           0 :                         openlog_done = false;
    2371                 :           0 :                 }
    2372                 :           0 :                 syslog_facility = newval;
    2373                 :           0 :         }
    2374                 :             : #endif
    2375                 :             :         /* Without syslog support, just ignore it */
    2376                 :           6 : }
    2377                 :             : 
    2378                 :             : #ifdef HAVE_SYSLOG
    2379                 :             : 
    2380                 :             : /*
    2381                 :             :  * Write a message line to syslog
    2382                 :             :  */
    2383                 :             : static void
    2384                 :           0 : write_syslog(int level, const char *line)
    2385                 :             : {
    2386                 :             :         static unsigned long seq = 0;
    2387                 :             : 
    2388                 :           0 :         int                     len;
    2389                 :           0 :         const char *nlpos;
    2390                 :             : 
    2391                 :             :         /* Open syslog connection if not done yet */
    2392         [ #  # ]:           0 :         if (!openlog_done)
    2393                 :             :         {
    2394         [ #  # ]:           0 :                 openlog(syslog_ident ? syslog_ident : "postgres",
    2395                 :             :                                 LOG_PID | LOG_NDELAY | LOG_NOWAIT,
    2396                 :           0 :                                 syslog_facility);
    2397                 :           0 :                 openlog_done = true;
    2398                 :           0 :         }
    2399                 :             : 
    2400                 :             :         /*
    2401                 :             :          * We add a sequence number to each log message to suppress "same"
    2402                 :             :          * messages.
    2403                 :             :          */
    2404                 :           0 :         seq++;
    2405                 :             : 
    2406                 :             :         /*
    2407                 :             :          * Our problem here is that many syslog implementations don't handle long
    2408                 :             :          * messages in an acceptable manner. While this function doesn't help that
    2409                 :             :          * fact, it does work around by splitting up messages into smaller pieces.
    2410                 :             :          *
    2411                 :             :          * We divide into multiple syslog() calls if message is too long or if the
    2412                 :             :          * message contains embedded newline(s).
    2413                 :             :          */
    2414                 :           0 :         len = strlen(line);
    2415                 :           0 :         nlpos = strchr(line, '\n');
    2416   [ #  #  #  #  :           0 :         if (syslog_split_messages && (len > PG_SYSLOG_LIMIT || nlpos != NULL))
                   #  # ]
    2417                 :             :         {
    2418                 :           0 :                 int                     chunk_nr = 0;
    2419                 :             : 
    2420         [ #  # ]:           0 :                 while (len > 0)
    2421                 :             :                 {
    2422                 :           0 :                         char            buf[PG_SYSLOG_LIMIT + 1];
    2423                 :           0 :                         int                     buflen;
    2424                 :           0 :                         int                     i;
    2425                 :             : 
    2426                 :             :                         /* if we start at a newline, move ahead one char */
    2427         [ #  # ]:           0 :                         if (line[0] == '\n')
    2428                 :             :                         {
    2429                 :           0 :                                 line++;
    2430                 :           0 :                                 len--;
    2431                 :             :                                 /* we need to recompute the next newline's position, too */
    2432                 :           0 :                                 nlpos = strchr(line, '\n');
    2433                 :           0 :                                 continue;
    2434                 :             :                         }
    2435                 :             : 
    2436                 :             :                         /* copy one line, or as much as will fit, to buf */
    2437         [ #  # ]:           0 :                         if (nlpos != NULL)
    2438                 :           0 :                                 buflen = nlpos - line;
    2439                 :             :                         else
    2440                 :           0 :                                 buflen = len;
    2441         [ #  # ]:           0 :                         buflen = Min(buflen, PG_SYSLOG_LIMIT);
    2442                 :           0 :                         memcpy(buf, line, buflen);
    2443                 :           0 :                         buf[buflen] = '\0';
    2444                 :             : 
    2445                 :             :                         /* trim to multibyte letter boundary */
    2446                 :           0 :                         buflen = pg_mbcliplen(buf, buflen, buflen);
    2447         [ #  # ]:           0 :                         if (buflen <= 0)
    2448                 :           0 :                                 return;
    2449                 :           0 :                         buf[buflen] = '\0';
    2450                 :             : 
    2451                 :             :                         /* already word boundary? */
    2452   [ #  #  #  # ]:           0 :                         if (line[buflen] != '\0' &&
    2453                 :           0 :                                 !isspace((unsigned char) line[buflen]))
    2454                 :             :                         {
    2455                 :             :                                 /* try to divide at word boundary */
    2456                 :           0 :                                 i = buflen - 1;
    2457   [ #  #  #  # ]:           0 :                                 while (i > 0 && !isspace((unsigned char) buf[i]))
    2458                 :           0 :                                         i--;
    2459                 :             : 
    2460         [ #  # ]:           0 :                                 if (i > 0)           /* else couldn't divide word boundary */
    2461                 :             :                                 {
    2462                 :           0 :                                         buflen = i;
    2463                 :           0 :                                         buf[i] = '\0';
    2464                 :           0 :                                 }
    2465                 :           0 :                         }
    2466                 :             : 
    2467                 :           0 :                         chunk_nr++;
    2468                 :             : 
    2469         [ #  # ]:           0 :                         if (syslog_sequence_numbers)
    2470                 :           0 :                                 syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf);
    2471                 :             :                         else
    2472                 :           0 :                                 syslog(level, "[%d] %s", chunk_nr, buf);
    2473                 :             : 
    2474                 :           0 :                         line += buflen;
    2475                 :           0 :                         len -= buflen;
    2476      [ #  #  # ]:           0 :                 }
    2477         [ #  # ]:           0 :         }
    2478                 :             :         else
    2479                 :             :         {
    2480                 :             :                 /* message short enough */
    2481         [ #  # ]:           0 :                 if (syslog_sequence_numbers)
    2482                 :           0 :                         syslog(level, "[%lu] %s", seq, line);
    2483                 :             :                 else
    2484                 :           0 :                         syslog(level, "%s", line);
    2485                 :             :         }
    2486         [ #  # ]:           0 : }
    2487                 :             : #endif                                                  /* HAVE_SYSLOG */
    2488                 :             : 
    2489                 :             : #ifdef WIN32
    2490                 :             : /*
    2491                 :             :  * Get the PostgreSQL equivalent of the Windows ANSI code page.  "ANSI" system
    2492                 :             :  * interfaces (e.g. CreateFileA()) expect string arguments in this encoding.
    2493                 :             :  * Every process in a given system will find the same value at all times.
    2494                 :             :  */
    2495                 :             : static int
    2496                 :             : GetACPEncoding(void)
    2497                 :             : {
    2498                 :             :         static int      encoding = -2;
    2499                 :             : 
    2500                 :             :         if (encoding == -2)
    2501                 :             :                 encoding = pg_codepage_to_encoding(GetACP());
    2502                 :             : 
    2503                 :             :         return encoding;
    2504                 :             : }
    2505                 :             : 
    2506                 :             : /*
    2507                 :             :  * Write a message line to the windows event log
    2508                 :             :  */
    2509                 :             : static void
    2510                 :             : write_eventlog(int level, const char *line, int len)
    2511                 :             : {
    2512                 :             :         WCHAR      *utf16;
    2513                 :             :         int                     eventlevel = EVENTLOG_ERROR_TYPE;
    2514                 :             :         static HANDLE evtHandle = INVALID_HANDLE_VALUE;
    2515                 :             : 
    2516                 :             :         if (evtHandle == INVALID_HANDLE_VALUE)
    2517                 :             :         {
    2518                 :             :                 evtHandle = RegisterEventSource(NULL,
    2519                 :             :                                                                                 event_source ? event_source : DEFAULT_EVENT_SOURCE);
    2520                 :             :                 if (evtHandle == NULL)
    2521                 :             :                 {
    2522                 :             :                         evtHandle = INVALID_HANDLE_VALUE;
    2523                 :             :                         return;
    2524                 :             :                 }
    2525                 :             :         }
    2526                 :             : 
    2527                 :             :         switch (level)
    2528                 :             :         {
    2529                 :             :                 case DEBUG5:
    2530                 :             :                 case DEBUG4:
    2531                 :             :                 case DEBUG3:
    2532                 :             :                 case DEBUG2:
    2533                 :             :                 case DEBUG1:
    2534                 :             :                 case LOG:
    2535                 :             :                 case LOG_SERVER_ONLY:
    2536                 :             :                 case INFO:
    2537                 :             :                 case NOTICE:
    2538                 :             :                         eventlevel = EVENTLOG_INFORMATION_TYPE;
    2539                 :             :                         break;
    2540                 :             :                 case WARNING:
    2541                 :             :                 case WARNING_CLIENT_ONLY:
    2542                 :             :                         eventlevel = EVENTLOG_WARNING_TYPE;
    2543                 :             :                         break;
    2544                 :             :                 case ERROR:
    2545                 :             :                 case FATAL:
    2546                 :             :                 case PANIC:
    2547                 :             :                 default:
    2548                 :             :                         eventlevel = EVENTLOG_ERROR_TYPE;
    2549                 :             :                         break;
    2550                 :             :         }
    2551                 :             : 
    2552                 :             :         /*
    2553                 :             :          * If message character encoding matches the encoding expected by
    2554                 :             :          * ReportEventA(), call it to avoid the hazards of conversion.  Otherwise,
    2555                 :             :          * try to convert the message to UTF16 and write it with ReportEventW().
    2556                 :             :          * Fall back on ReportEventA() if conversion failed.
    2557                 :             :          *
    2558                 :             :          * Since we palloc the structure required for conversion, also fall
    2559                 :             :          * through to writing unconverted if we have not yet set up
    2560                 :             :          * CurrentMemoryContext.
    2561                 :             :          *
    2562                 :             :          * Also verify that we are not on our way into error recursion trouble due
    2563                 :             :          * to error messages thrown deep inside pgwin32_message_to_UTF16().
    2564                 :             :          */
    2565                 :             :         if (!in_error_recursion_trouble() &&
    2566                 :             :                 CurrentMemoryContext != NULL &&
    2567                 :             :                 GetMessageEncoding() != GetACPEncoding())
    2568                 :             :         {
    2569                 :             :                 utf16 = pgwin32_message_to_UTF16(line, len, NULL);
    2570                 :             :                 if (utf16)
    2571                 :             :                 {
    2572                 :             :                         ReportEventW(evtHandle,
    2573                 :             :                                                  eventlevel,
    2574                 :             :                                                  0,
    2575                 :             :                                                  0,             /* All events are Id 0 */
    2576                 :             :                                                  NULL,
    2577                 :             :                                                  1,
    2578                 :             :                                                  0,
    2579                 :             :                                                  (LPCWSTR *) &utf16,
    2580                 :             :                                                  NULL);
    2581                 :             :                         /* XXX Try ReportEventA() when ReportEventW() fails? */
    2582                 :             : 
    2583                 :             :                         pfree(utf16);
    2584                 :             :                         return;
    2585                 :             :                 }
    2586                 :             :         }
    2587                 :             :         ReportEventA(evtHandle,
    2588                 :             :                                  eventlevel,
    2589                 :             :                                  0,
    2590                 :             :                                  0,                             /* All events are Id 0 */
    2591                 :             :                                  NULL,
    2592                 :             :                                  1,
    2593                 :             :                                  0,
    2594                 :             :                                  &line,
    2595                 :             :                                  NULL);
    2596                 :             : }
    2597                 :             : #endif                                                  /* WIN32 */
    2598                 :             : 
    2599                 :             : static void
    2600                 :       65674 : write_console(const char *line, int len)
    2601                 :             : {
    2602                 :       65674 :         int                     rc;
    2603                 :             : 
    2604                 :             : #ifdef WIN32
    2605                 :             : 
    2606                 :             :         /*
    2607                 :             :          * Try to convert the message to UTF16 and write it with WriteConsoleW().
    2608                 :             :          * Fall back on write() if anything fails.
    2609                 :             :          *
    2610                 :             :          * In contrast to write_eventlog(), don't skip straight to write() based
    2611                 :             :          * on the applicable encodings.  Unlike WriteConsoleW(), write() depends
    2612                 :             :          * on the suitability of the console output code page.  Since we put
    2613                 :             :          * stderr into binary mode in SubPostmasterMain(), write() skips the
    2614                 :             :          * necessary translation anyway.
    2615                 :             :          *
    2616                 :             :          * WriteConsoleW() will fail if stderr is redirected, so just fall through
    2617                 :             :          * to writing unconverted to the logfile in this case.
    2618                 :             :          *
    2619                 :             :          * Since we palloc the structure required for conversion, also fall
    2620                 :             :          * through to writing unconverted if we have not yet set up
    2621                 :             :          * CurrentMemoryContext.
    2622                 :             :          */
    2623                 :             :         if (!in_error_recursion_trouble() &&
    2624                 :             :                 !redirection_done &&
    2625                 :             :                 CurrentMemoryContext != NULL)
    2626                 :             :         {
    2627                 :             :                 WCHAR      *utf16;
    2628                 :             :                 int                     utf16len;
    2629                 :             : 
    2630                 :             :                 utf16 = pgwin32_message_to_UTF16(line, len, &utf16len);
    2631                 :             :                 if (utf16 != NULL)
    2632                 :             :                 {
    2633                 :             :                         HANDLE          stdHandle;
    2634                 :             :                         DWORD           written;
    2635                 :             : 
    2636                 :             :                         stdHandle = GetStdHandle(STD_ERROR_HANDLE);
    2637                 :             :                         if (WriteConsoleW(stdHandle, utf16, utf16len, &written, NULL))
    2638                 :             :                         {
    2639                 :             :                                 pfree(utf16);
    2640                 :             :                                 return;
    2641                 :             :                         }
    2642                 :             : 
    2643                 :             :                         /*
    2644                 :             :                          * In case WriteConsoleW() failed, fall back to writing the
    2645                 :             :                          * message unconverted.
    2646                 :             :                          */
    2647                 :             :                         pfree(utf16);
    2648                 :             :                 }
    2649                 :             :         }
    2650                 :             : #else
    2651                 :             : 
    2652                 :             :         /*
    2653                 :             :          * Conversion on non-win32 platforms is not implemented yet. It requires
    2654                 :             :          * non-throw version of pg_do_encoding_conversion(), that converts
    2655                 :             :          * unconvertible characters to '?' without errors.
    2656                 :             :          *
    2657                 :             :          * XXX: We have a no-throw version now. It doesn't convert to '?' though.
    2658                 :             :          */
    2659                 :             : #endif
    2660                 :             : 
    2661                 :             :         /*
    2662                 :             :          * We ignore any error from write() here.  We have no useful way to report
    2663                 :             :          * it ... certainly whining on stderr isn't likely to be productive.
    2664                 :             :          */
    2665                 :       65674 :         rc = write(fileno(stderr), line, len);
    2666                 :       65674 :         (void) rc;
    2667                 :       65674 : }
    2668                 :             : 
    2669                 :             : /*
    2670                 :             :  * get_formatted_log_time -- compute and get the log timestamp.
    2671                 :             :  *
    2672                 :             :  * The timestamp is computed if not set yet, so as it is kept consistent
    2673                 :             :  * among all the log destinations that require it to be consistent.  Note
    2674                 :             :  * that the computed timestamp is returned in a static buffer, not
    2675                 :             :  * palloc()'d.
    2676                 :             :  */
    2677                 :             : char *
    2678                 :       75577 : get_formatted_log_time(void)
    2679                 :             : {
    2680                 :       75577 :         pg_time_t       stamp_time;
    2681                 :       75577 :         char            msbuf[13];
    2682                 :             : 
    2683                 :             :         /* leave if already computed */
    2684         [ -  + ]:       75577 :         if (formatted_log_time[0] != '\0')
    2685                 :           0 :                 return formatted_log_time;
    2686                 :             : 
    2687         [ +  + ]:       75577 :         if (!saved_timeval_set)
    2688                 :             :         {
    2689                 :       65674 :                 gettimeofday(&saved_timeval, NULL);
    2690                 :       65674 :                 saved_timeval_set = true;
    2691                 :       65674 :         }
    2692                 :             : 
    2693                 :       75577 :         stamp_time = (pg_time_t) saved_timeval.tv_sec;
    2694                 :             : 
    2695                 :             :         /*
    2696                 :             :          * Note: we expect that guc.c will ensure that log_timezone is set up (at
    2697                 :             :          * least with a minimal GMT value) before Log_line_prefix can become
    2698                 :             :          * nonempty or CSV/JSON mode can be selected.
    2699                 :             :          */
    2700                 :       75577 :         pg_strftime(formatted_log_time, FORMATTED_TS_LEN,
    2701                 :             :         /* leave room for milliseconds... */
    2702                 :             :                                 "%Y-%m-%d %H:%M:%S     %Z",
    2703                 :       75577 :                                 pg_localtime(&stamp_time, log_timezone));
    2704                 :             : 
    2705                 :             :         /* 'paste' milliseconds into place... */
    2706                 :       75577 :         sprintf(msbuf, ".%03d", (int) (saved_timeval.tv_usec / 1000));
    2707                 :       75577 :         memcpy(formatted_log_time + 19, msbuf, 4);
    2708                 :             : 
    2709                 :       75577 :         return formatted_log_time;
    2710                 :       75577 : }
    2711                 :             : 
    2712                 :             : /*
    2713                 :             :  * reset_formatted_start_time -- reset the start timestamp
    2714                 :             :  */
    2715                 :             : void
    2716                 :         318 : reset_formatted_start_time(void)
    2717                 :             : {
    2718                 :         318 :         formatted_start_time[0] = '\0';
    2719                 :         318 : }
    2720                 :             : 
    2721                 :             : /*
    2722                 :             :  * get_formatted_start_time -- compute and get the start timestamp.
    2723                 :             :  *
    2724                 :             :  * The timestamp is computed if not set yet.  Note that the computed
    2725                 :             :  * timestamp is returned in a static buffer, not palloc()'d.
    2726                 :             :  */
    2727                 :             : char *
    2728                 :           0 : get_formatted_start_time(void)
    2729                 :             : {
    2730                 :           0 :         pg_time_t       stamp_time = (pg_time_t) MyStartTime;
    2731                 :             : 
    2732                 :             :         /* leave if already computed */
    2733         [ #  # ]:           0 :         if (formatted_start_time[0] != '\0')
    2734                 :           0 :                 return formatted_start_time;
    2735                 :             : 
    2736                 :             :         /*
    2737                 :             :          * Note: we expect that guc.c will ensure that log_timezone is set up (at
    2738                 :             :          * least with a minimal GMT value) before Log_line_prefix can become
    2739                 :             :          * nonempty or CSV/JSON mode can be selected.
    2740                 :             :          */
    2741                 :           0 :         pg_strftime(formatted_start_time, FORMATTED_TS_LEN,
    2742                 :             :                                 "%Y-%m-%d %H:%M:%S %Z",
    2743                 :           0 :                                 pg_localtime(&stamp_time, log_timezone));
    2744                 :             : 
    2745                 :           0 :         return formatted_start_time;
    2746                 :           0 : }
    2747                 :             : 
    2748                 :             : /*
    2749                 :             :  * check_log_of_query -- check if a query can be logged
    2750                 :             :  */
    2751                 :             : bool
    2752                 :       65674 : check_log_of_query(ErrorData *edata)
    2753                 :             : {
    2754                 :             :         /* log required? */
    2755         [ +  + ]:       65674 :         if (!is_log_level_output(edata->elevel, log_min_error_statement))
    2756                 :         975 :                 return false;
    2757                 :             : 
    2758                 :             :         /* query log wanted? */
    2759         [ +  + ]:       64699 :         if (edata->hide_stmt)
    2760                 :       57642 :                 return false;
    2761                 :             : 
    2762                 :             :         /* query string available? */
    2763         [ +  + ]:        7057 :         if (debug_query_string == NULL)
    2764                 :         283 :                 return false;
    2765                 :             : 
    2766                 :        6774 :         return true;
    2767                 :       65674 : }
    2768                 :             : 
    2769                 :             : /*
    2770                 :             :  * get_backend_type_for_log -- backend type for log entries
    2771                 :             :  *
    2772                 :             :  * Returns a pointer to a static buffer, not palloc()'d.
    2773                 :             :  */
    2774                 :             : const char *
    2775                 :       75575 : get_backend_type_for_log(void)
    2776                 :             : {
    2777                 :       75575 :         const char *backend_type_str;
    2778                 :             : 
    2779         [ +  + ]:       75575 :         if (MyProcPid == PostmasterPid)
    2780                 :          15 :                 backend_type_str = "postmaster";
    2781         [ +  + ]:       75560 :         else if (MyBackendType == B_BG_WORKER)
    2782                 :           7 :                 backend_type_str = MyBgworkerEntry->bgw_type;
    2783                 :             :         else
    2784                 :       75553 :                 backend_type_str = GetBackendTypeDesc(MyBackendType);
    2785                 :             : 
    2786                 :      151150 :         return backend_type_str;
    2787                 :       75575 : }
    2788                 :             : 
    2789                 :             : /*
    2790                 :             :  * process_log_prefix_padding --- helper function for processing the format
    2791                 :             :  * string in log_line_prefix
    2792                 :             :  *
    2793                 :             :  * Note: This function returns NULL if it finds something which
    2794                 :             :  * it deems invalid in the format string.
    2795                 :             :  */
    2796                 :             : static const char *
    2797                 :           0 : process_log_prefix_padding(const char *p, int *ppadding)
    2798                 :             : {
    2799                 :           0 :         int                     paddingsign = 1;
    2800                 :           0 :         int                     padding = 0;
    2801                 :             : 
    2802         [ #  # ]:           0 :         if (*p == '-')
    2803                 :             :         {
    2804                 :           0 :                 p++;
    2805                 :             : 
    2806         [ #  # ]:           0 :                 if (*p == '\0')                 /* Did the buf end in %- ? */
    2807                 :           0 :                         return NULL;
    2808                 :           0 :                 paddingsign = -1;
    2809                 :           0 :         }
    2810                 :             : 
    2811                 :             :         /* generate an int version of the numerical string */
    2812   [ #  #  #  # ]:           0 :         while (*p >= '0' && *p <= '9')
    2813                 :           0 :                 padding = padding * 10 + (*p++ - '0');
    2814                 :             : 
    2815                 :             :         /* format is invalid if it ends with the padding number */
    2816         [ #  # ]:           0 :         if (*p == '\0')
    2817                 :           0 :                 return NULL;
    2818                 :             : 
    2819                 :           0 :         padding *= paddingsign;
    2820                 :           0 :         *ppadding = padding;
    2821                 :           0 :         return p;
    2822                 :           0 : }
    2823                 :             : 
    2824                 :             : /*
    2825                 :             :  * Format log status information using Log_line_prefix.
    2826                 :             :  */
    2827                 :             : static void
    2828                 :       75577 : log_line_prefix(StringInfo buf, ErrorData *edata)
    2829                 :             : {
    2830                 :       75577 :         log_status_format(buf, Log_line_prefix, edata);
    2831                 :       75577 : }
    2832                 :             : 
    2833                 :             : /*
    2834                 :             :  * Format log status info; append to the provided buffer.
    2835                 :             :  */
    2836                 :             : void
    2837                 :       75577 : log_status_format(StringInfo buf, const char *format, ErrorData *edata)
    2838                 :             : {
    2839                 :             :         /* static counter for line numbers */
    2840                 :             :         static long log_line_number = 0;
    2841                 :             : 
    2842                 :             :         /* has counter been reset in current process? */
    2843                 :             :         static int      log_my_pid = 0;
    2844                 :       75577 :         int                     padding;
    2845                 :       75577 :         const char *p;
    2846                 :             : 
    2847                 :             :         /*
    2848                 :             :          * This is one of the few places where we'd rather not inherit a static
    2849                 :             :          * variable's value from the postmaster.  But since we will, reset it when
    2850                 :             :          * MyProcPid changes. MyStartTime also changes when MyProcPid does, so
    2851                 :             :          * reset the formatted start timestamp too.
    2852                 :             :          */
    2853         [ +  + ]:       75577 :         if (log_my_pid != MyProcPid)
    2854                 :             :         {
    2855                 :         318 :                 log_line_number = 0;
    2856                 :         318 :                 log_my_pid = MyProcPid;
    2857                 :         318 :                 reset_formatted_start_time();
    2858                 :         318 :         }
    2859                 :       75577 :         log_line_number++;
    2860                 :             : 
    2861         [ +  - ]:       75577 :         if (format == NULL)
    2862                 :           0 :                 return;                                 /* in case guc hasn't run yet */
    2863                 :             : 
    2864         [ +  + ]:      831258 :         for (p = format; *p != '\0'; p++)
    2865                 :             :         {
    2866         [ +  + ]:      755708 :                 if (*p != '%')
    2867                 :             :                 {
    2868                 :             :                         /* literal char, just copy */
    2869                 :      377856 :                         appendStringInfoChar(buf, *p);
    2870                 :      377856 :                         continue;
    2871                 :             :                 }
    2872                 :             : 
    2873                 :             :                 /* must be a '%', so skip to the next char */
    2874                 :      377852 :                 p++;
    2875         [ -  + ]:      377852 :                 if (*p == '\0')
    2876                 :           0 :                         break;                          /* format error - ignore it */
    2877         [ -  + ]:      377852 :                 else if (*p == '%')
    2878                 :             :                 {
    2879                 :             :                         /* string contains %% */
    2880                 :           0 :                         appendStringInfoChar(buf, '%');
    2881                 :           0 :                         continue;
    2882                 :             :                 }
    2883                 :             : 
    2884                 :             : 
    2885                 :             :                 /*
    2886                 :             :                  * Process any formatting which may exist after the '%'.  Note that
    2887                 :             :                  * process_log_prefix_padding moves p past the padding number if it
    2888                 :             :                  * exists.
    2889                 :             :                  *
    2890                 :             :                  * Note: Since only '-', '0' to '9' are valid formatting characters we
    2891                 :             :                  * can do a quick check here to pre-check for formatting. If the char
    2892                 :             :                  * is not formatting then we can skip a useless function call.
    2893                 :             :                  *
    2894                 :             :                  * Further note: At least on some platforms, passing %*s rather than
    2895                 :             :                  * %s to appendStringInfo() is substantially slower, so many of the
    2896                 :             :                  * cases below avoid doing that unless non-zero padding is in fact
    2897                 :             :                  * specified.
    2898                 :             :                  */
    2899         [ +  - ]:      377852 :                 if (*p > '9')
    2900                 :      377852 :                         padding = 0;
    2901         [ #  # ]:           0 :                 else if ((p = process_log_prefix_padding(p, &padding)) == NULL)
    2902                 :           0 :                         break;
    2903                 :             : 
    2904                 :             :                 /* process the option */
    2905   [ -  +  +  -  :      377852 :                 switch (*p)
          -  -  +  -  -  
          +  -  -  -  -  
          -  -  -  +  -  
                -  -  - ]
    2906                 :             :                 {
    2907                 :             :                         case 'a':
    2908         [ +  - ]:       75548 :                                 if (MyProcPort)
    2909                 :             :                                 {
    2910                 :       75548 :                                         const char *appname = application_name;
    2911                 :             : 
    2912   [ +  -  +  - ]:       75548 :                                         if (appname == NULL || *appname == '\0')
    2913                 :           0 :                                                 appname = _("[unknown]");
    2914         [ -  + ]:       75548 :                                         if (padding != 0)
    2915                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, appname);
    2916                 :             :                                         else
    2917                 :       75548 :                                                 appendStringInfoString(buf, appname);
    2918                 :       75548 :                                 }
    2919         [ #  # ]:           0 :                                 else if (padding != 0)
    2920                 :           0 :                                         appendStringInfoSpaces(buf,
    2921         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    2922                 :             : 
    2923                 :       75548 :                                 break;
    2924                 :             :                         case 'b':
    2925                 :             :                                 {
    2926                 :       75575 :                                         const char *backend_type_str = get_backend_type_for_log();
    2927                 :             : 
    2928         [ -  + ]:       75575 :                                         if (padding != 0)
    2929                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, backend_type_str);
    2930                 :             :                                         else
    2931                 :       75575 :                                                 appendStringInfoString(buf, backend_type_str);
    2932                 :             :                                         break;
    2933                 :       75575 :                                 }
    2934                 :             :                         case 'u':
    2935         [ #  # ]:           0 :                                 if (MyProcPort)
    2936                 :             :                                 {
    2937                 :           0 :                                         const char *username = MyProcPort->user_name;
    2938                 :             : 
    2939   [ #  #  #  # ]:           0 :                                         if (username == NULL || *username == '\0')
    2940                 :           0 :                                                 username = _("[unknown]");
    2941         [ #  # ]:           0 :                                         if (padding != 0)
    2942                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, username);
    2943                 :             :                                         else
    2944                 :           0 :                                                 appendStringInfoString(buf, username);
    2945                 :           0 :                                 }
    2946         [ #  # ]:           0 :                                 else if (padding != 0)
    2947                 :           0 :                                         appendStringInfoSpaces(buf,
    2948         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    2949                 :           0 :                                 break;
    2950                 :             :                         case 'd':
    2951         [ #  # ]:           0 :                                 if (MyProcPort)
    2952                 :             :                                 {
    2953                 :           0 :                                         const char *dbname = MyProcPort->database_name;
    2954                 :             : 
    2955   [ #  #  #  # ]:           0 :                                         if (dbname == NULL || *dbname == '\0')
    2956                 :           0 :                                                 dbname = _("[unknown]");
    2957         [ #  # ]:           0 :                                         if (padding != 0)
    2958                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, dbname);
    2959                 :             :                                         else
    2960                 :           0 :                                                 appendStringInfoString(buf, dbname);
    2961                 :           0 :                                 }
    2962         [ #  # ]:           0 :                                 else if (padding != 0)
    2963                 :           0 :                                         appendStringInfoSpaces(buf,
    2964         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    2965                 :           0 :                                 break;
    2966                 :             :                         case 'c':
    2967         [ #  # ]:           0 :                                 if (padding != 0)
    2968                 :             :                                 {
    2969                 :           0 :                                         char            strfbuf[128];
    2970                 :             : 
    2971                 :           0 :                                         snprintf(strfbuf, sizeof(strfbuf) - 1, "%" PRIx64 ".%x",
    2972                 :           0 :                                                          MyStartTime, MyProcPid);
    2973                 :           0 :                                         appendStringInfo(buf, "%*s", padding, strfbuf);
    2974                 :           0 :                                 }
    2975                 :             :                                 else
    2976                 :           0 :                                         appendStringInfo(buf, "%" PRIx64 ".%x", MyStartTime, MyProcPid);
    2977                 :           0 :                                 break;
    2978                 :             :                         case 'p':
    2979         [ -  + ]:       75577 :                                 if (padding != 0)
    2980                 :           0 :                                         appendStringInfo(buf, "%*d", padding, MyProcPid);
    2981                 :             :                                 else
    2982                 :       75577 :                                         appendStringInfo(buf, "%d", MyProcPid);
    2983                 :       75577 :                                 break;
    2984                 :             : 
    2985                 :             :                         case 'P':
    2986         [ #  # ]:           0 :                                 if (MyProc)
    2987                 :             :                                 {
    2988                 :           0 :                                         PGPROC     *leader = MyProc->lockGroupLeader;
    2989                 :             : 
    2990                 :             :                                         /*
    2991                 :             :                                          * Show the leader only for active parallel workers. This
    2992                 :             :                                          * leaves out the leader of a parallel group.
    2993                 :             :                                          */
    2994   [ #  #  #  # ]:           0 :                                         if (leader == NULL || leader->pid == MyProcPid)
    2995                 :           0 :                                                 appendStringInfoSpaces(buf,
    2996         [ #  # ]:           0 :                                                                                            padding > 0 ? padding : -padding);
    2997         [ #  # ]:           0 :                                         else if (padding != 0)
    2998                 :           0 :                                                 appendStringInfo(buf, "%*d", padding, leader->pid);
    2999                 :             :                                         else
    3000                 :           0 :                                                 appendStringInfo(buf, "%d", leader->pid);
    3001                 :           0 :                                 }
    3002         [ #  # ]:           0 :                                 else if (padding != 0)
    3003                 :           0 :                                         appendStringInfoSpaces(buf,
    3004         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    3005                 :           0 :                                 break;
    3006                 :             : 
    3007                 :             :                         case 'l':
    3008         [ #  # ]:           0 :                                 if (padding != 0)
    3009                 :           0 :                                         appendStringInfo(buf, "%*ld", padding, log_line_number);
    3010                 :             :                                 else
    3011                 :           0 :                                         appendStringInfo(buf, "%ld", log_line_number);
    3012                 :           0 :                                 break;
    3013                 :             :                         case 'm':
    3014                 :             :                                 /* force a log timestamp reset */
    3015                 :       75577 :                                 formatted_log_time[0] = '\0';
    3016                 :       75577 :                                 (void) get_formatted_log_time();
    3017                 :             : 
    3018         [ +  - ]:       75577 :                                 if (padding != 0)
    3019                 :           0 :                                         appendStringInfo(buf, "%*s", padding, formatted_log_time);
    3020                 :             :                                 else
    3021                 :       75577 :                                         appendStringInfoString(buf, formatted_log_time);
    3022                 :       75577 :                                 break;
    3023                 :             :                         case 't':
    3024                 :             :                                 {
    3025                 :           0 :                                         pg_time_t       stamp_time = (pg_time_t) time(NULL);
    3026                 :           0 :                                         char            strfbuf[128];
    3027                 :             : 
    3028                 :           0 :                                         pg_strftime(strfbuf, sizeof(strfbuf),
    3029                 :             :                                                                 "%Y-%m-%d %H:%M:%S %Z",
    3030                 :           0 :                                                                 pg_localtime(&stamp_time, log_timezone));
    3031         [ #  # ]:           0 :                                         if (padding != 0)
    3032                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, strfbuf);
    3033                 :             :                                         else
    3034                 :           0 :                                                 appendStringInfoString(buf, strfbuf);
    3035                 :           0 :                                 }
    3036                 :           0 :                                 break;
    3037                 :             :                         case 'n':
    3038                 :             :                                 {
    3039                 :           0 :                                         char            strfbuf[128];
    3040                 :             : 
    3041         [ #  # ]:           0 :                                         if (!saved_timeval_set)
    3042                 :             :                                         {
    3043                 :           0 :                                                 gettimeofday(&saved_timeval, NULL);
    3044                 :           0 :                                                 saved_timeval_set = true;
    3045                 :           0 :                                         }
    3046                 :             : 
    3047                 :           0 :                                         snprintf(strfbuf, sizeof(strfbuf), "%ld.%03d",
    3048                 :           0 :                                                          (long) saved_timeval.tv_sec,
    3049                 :           0 :                                                          (int) (saved_timeval.tv_usec / 1000));
    3050                 :             : 
    3051         [ #  # ]:           0 :                                         if (padding != 0)
    3052                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, strfbuf);
    3053                 :             :                                         else
    3054                 :           0 :                                                 appendStringInfoString(buf, strfbuf);
    3055                 :           0 :                                 }
    3056                 :           0 :                                 break;
    3057                 :             :                         case 's':
    3058                 :             :                                 {
    3059                 :           0 :                                         char       *start_time = get_formatted_start_time();
    3060                 :             : 
    3061         [ #  # ]:           0 :                                         if (padding != 0)
    3062                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, start_time);
    3063                 :             :                                         else
    3064                 :           0 :                                                 appendStringInfoString(buf, start_time);
    3065                 :           0 :                                 }
    3066                 :           0 :                                 break;
    3067                 :             :                         case 'i':
    3068         [ #  # ]:           0 :                                 if (MyProcPort)
    3069                 :             :                                 {
    3070                 :           0 :                                         const char *psdisp;
    3071                 :           0 :                                         int                     displen;
    3072                 :             : 
    3073                 :           0 :                                         psdisp = get_ps_display(&displen);
    3074         [ #  # ]:           0 :                                         if (padding != 0)
    3075                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, psdisp);
    3076                 :             :                                         else
    3077                 :           0 :                                                 appendBinaryStringInfo(buf, psdisp, displen);
    3078                 :           0 :                                 }
    3079         [ #  # ]:           0 :                                 else if (padding != 0)
    3080                 :           0 :                                         appendStringInfoSpaces(buf,
    3081         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    3082                 :           0 :                                 break;
    3083                 :             :                         case 'L':
    3084                 :             :                                 {
    3085                 :           0 :                                         const char *local_host;
    3086                 :             : 
    3087         [ #  # ]:           0 :                                         if (MyProcPort)
    3088                 :             :                                         {
    3089         [ #  # ]:           0 :                                                 if (MyProcPort->local_host[0] == '\0')
    3090                 :             :                                                 {
    3091                 :             :                                                         /*
    3092                 :             :                                                          * First time through: cache the lookup, since it
    3093                 :             :                                                          * might not have trivial cost.
    3094                 :             :                                                          */
    3095                 :           0 :                                                         (void) pg_getnameinfo_all(&MyProcPort->laddr.addr,
    3096                 :           0 :                                                                                                           MyProcPort->laddr.salen,
    3097                 :           0 :                                                                                                           MyProcPort->local_host,
    3098                 :             :                                                                                                           sizeof(MyProcPort->local_host),
    3099                 :             :                                                                                                           NULL, 0,
    3100                 :             :                                                                                                           NI_NUMERICHOST | NI_NUMERICSERV);
    3101                 :           0 :                                                 }
    3102                 :           0 :                                                 local_host = MyProcPort->local_host;
    3103                 :           0 :                                         }
    3104                 :             :                                         else
    3105                 :             :                                         {
    3106                 :             :                                                 /* Background process, or connection not yet made */
    3107                 :           0 :                                                 local_host = "[none]";
    3108                 :             :                                         }
    3109         [ #  # ]:           0 :                                         if (padding != 0)
    3110                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, local_host);
    3111                 :             :                                         else
    3112                 :           0 :                                                 appendStringInfoString(buf, local_host);
    3113                 :           0 :                                 }
    3114                 :           0 :                                 break;
    3115                 :             :                         case 'r':
    3116   [ #  #  #  # ]:           0 :                                 if (MyProcPort && MyProcPort->remote_host)
    3117                 :             :                                 {
    3118         [ #  # ]:           0 :                                         if (padding != 0)
    3119                 :             :                                         {
    3120   [ #  #  #  # ]:           0 :                                                 if (MyProcPort->remote_port && MyProcPort->remote_port[0] != '\0')
    3121                 :             :                                                 {
    3122                 :             :                                                         /*
    3123                 :             :                                                          * This option is slightly special as the port
    3124                 :             :                                                          * number may be appended onto the end. Here we
    3125                 :             :                                                          * need to build 1 string which contains the
    3126                 :             :                                                          * remote_host and optionally the remote_port (if
    3127                 :             :                                                          * set) so we can properly align the string.
    3128                 :             :                                                          */
    3129                 :             : 
    3130                 :           0 :                                                         char       *hostport;
    3131                 :             : 
    3132                 :           0 :                                                         hostport = psprintf("%s(%s)", MyProcPort->remote_host, MyProcPort->remote_port);
    3133                 :           0 :                                                         appendStringInfo(buf, "%*s", padding, hostport);
    3134                 :           0 :                                                         pfree(hostport);
    3135                 :           0 :                                                 }
    3136                 :             :                                                 else
    3137                 :           0 :                                                         appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
    3138                 :           0 :                                         }
    3139                 :             :                                         else
    3140                 :             :                                         {
    3141                 :             :                                                 /* padding is 0, so we don't need a temp buffer */
    3142                 :           0 :                                                 appendStringInfoString(buf, MyProcPort->remote_host);
    3143   [ #  #  #  # ]:           0 :                                                 if (MyProcPort->remote_port &&
    3144                 :           0 :                                                         MyProcPort->remote_port[0] != '\0')
    3145                 :           0 :                                                         appendStringInfo(buf, "(%s)",
    3146                 :           0 :                                                                                          MyProcPort->remote_port);
    3147                 :             :                                         }
    3148                 :           0 :                                 }
    3149         [ #  # ]:           0 :                                 else if (padding != 0)
    3150                 :           0 :                                         appendStringInfoSpaces(buf,
    3151         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    3152                 :           0 :                                 break;
    3153                 :             :                         case 'h':
    3154   [ #  #  #  # ]:           0 :                                 if (MyProcPort && MyProcPort->remote_host)
    3155                 :             :                                 {
    3156         [ #  # ]:           0 :                                         if (padding != 0)
    3157                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, MyProcPort->remote_host);
    3158                 :             :                                         else
    3159                 :           0 :                                                 appendStringInfoString(buf, MyProcPort->remote_host);
    3160                 :           0 :                                 }
    3161         [ #  # ]:           0 :                                 else if (padding != 0)
    3162                 :           0 :                                         appendStringInfoSpaces(buf,
    3163         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    3164                 :           0 :                                 break;
    3165                 :             :                         case 'q':
    3166                 :             :                                 /* in postmaster and friends, stop if %q is seen */
    3167                 :             :                                 /* in a backend, just ignore */
    3168         [ +  + ]:       75575 :                                 if (MyProcPort == NULL)
    3169                 :          27 :                                         return;
    3170                 :       75548 :                                 break;
    3171                 :             :                         case 'v':
    3172                 :             :                                 /* keep VXID format in sync with lockfuncs.c */
    3173   [ #  #  #  # ]:           0 :                                 if (MyProc != NULL && MyProc->vxid.procNumber != INVALID_PROC_NUMBER)
    3174                 :             :                                 {
    3175         [ #  # ]:           0 :                                         if (padding != 0)
    3176                 :             :                                         {
    3177                 :           0 :                                                 char            strfbuf[128];
    3178                 :             : 
    3179                 :           0 :                                                 snprintf(strfbuf, sizeof(strfbuf) - 1, "%d/%u",
    3180                 :           0 :                                                                  MyProc->vxid.procNumber, MyProc->vxid.lxid);
    3181                 :           0 :                                                 appendStringInfo(buf, "%*s", padding, strfbuf);
    3182                 :           0 :                                         }
    3183                 :             :                                         else
    3184                 :           0 :                                                 appendStringInfo(buf, "%d/%u", MyProc->vxid.procNumber, MyProc->vxid.lxid);
    3185                 :           0 :                                 }
    3186         [ #  # ]:           0 :                                 else if (padding != 0)
    3187                 :           0 :                                         appendStringInfoSpaces(buf,
    3188         [ #  # ]:           0 :                                                                                    padding > 0 ? padding : -padding);
    3189                 :           0 :                                 break;
    3190                 :             :                         case 'x':
    3191         [ #  # ]:           0 :                                 if (padding != 0)
    3192                 :           0 :                                         appendStringInfo(buf, "%*u", padding, GetTopTransactionIdIfAny());
    3193                 :             :                                 else
    3194                 :           0 :                                         appendStringInfo(buf, "%u", GetTopTransactionIdIfAny());
    3195                 :           0 :                                 break;
    3196                 :             :                         case 'e':
    3197         [ #  # ]:           0 :                                 if (padding != 0)
    3198                 :           0 :                                         appendStringInfo(buf, "%*s", padding, unpack_sql_state(edata->sqlerrcode));
    3199                 :             :                                 else
    3200                 :           0 :                                         appendStringInfoString(buf, unpack_sql_state(edata->sqlerrcode));
    3201                 :           0 :                                 break;
    3202                 :             :                         case 'Q':
    3203         [ #  # ]:           0 :                                 if (padding != 0)
    3204                 :           0 :                                         appendStringInfo(buf, "%*" PRId64, padding,
    3205                 :           0 :                                                                          pgstat_get_my_query_id());
    3206                 :             :                                 else
    3207                 :           0 :                                         appendStringInfo(buf, "%" PRId64,
    3208                 :           0 :                                                                          pgstat_get_my_query_id());
    3209                 :           0 :                                 break;
    3210                 :             :                         default:
    3211                 :             :                                 /* format error - ignore it */
    3212                 :           0 :                                 break;
    3213                 :             :                 }
    3214                 :      377825 :         }
    3215         [ -  + ]:       75577 : }
    3216                 :             : 
    3217                 :             : /*
    3218                 :             :  * Unpack MAKE_SQLSTATE code. Note that this returns a pointer to a
    3219                 :             :  * static buffer.
    3220                 :             :  */
    3221                 :             : char *
    3222                 :       10853 : unpack_sql_state(int sql_state)
    3223                 :             : {
    3224                 :             :         static char buf[12];
    3225                 :       10853 :         int                     i;
    3226                 :             : 
    3227         [ +  + ]:       65118 :         for (i = 0; i < 5; i++)
    3228                 :             :         {
    3229                 :       54265 :                 buf[i] = PGUNSIXBIT(sql_state);
    3230                 :       54265 :                 sql_state >>= 6;
    3231                 :       54265 :         }
    3232                 :             : 
    3233                 :       10853 :         buf[i] = '\0';
    3234                 :       10853 :         return buf;
    3235                 :       10853 : }
    3236                 :             : 
    3237                 :             : 
    3238                 :             : /*
    3239                 :             :  * Write error report to server's log
    3240                 :             :  */
    3241                 :             : static void
    3242                 :       65674 : send_message_to_server_log(ErrorData *edata)
    3243                 :             : {
    3244                 :       65674 :         StringInfoData buf;
    3245                 :       65674 :         bool            fallback_to_stderr = false;
    3246                 :             : 
    3247                 :       65674 :         initStringInfo(&buf);
    3248                 :             : 
    3249                 :       65674 :         log_line_prefix(&buf, edata);
    3250                 :       65674 :         appendStringInfo(&buf, "%s:  ", _(error_severity(edata->elevel)));
    3251                 :             : 
    3252         [ +  - ]:       65674 :         if (Log_error_verbosity >= PGERROR_VERBOSE)
    3253                 :           0 :                 appendStringInfo(&buf, "%s: ", unpack_sql_state(edata->sqlerrcode));
    3254                 :             : 
    3255         [ +  - ]:       65674 :         if (edata->message)
    3256                 :       65674 :                 append_with_tabs(&buf, edata->message);
    3257                 :             :         else
    3258                 :           0 :                 append_with_tabs(&buf, _("missing error text"));
    3259                 :             : 
    3260         [ +  + ]:       65674 :         if (edata->cursorpos > 0)
    3261                 :        3572 :                 appendStringInfo(&buf, _(" at character %d"),
    3262                 :        1786 :                                                  edata->cursorpos);
    3263         [ +  + ]:       63888 :         else if (edata->internalpos > 0)
    3264                 :          20 :                 appendStringInfo(&buf, _(" at character %d"),
    3265                 :          10 :                                                  edata->internalpos);
    3266                 :             : 
    3267                 :       65674 :         appendStringInfoChar(&buf, '\n');
    3268                 :             : 
    3269         [ -  + ]:       65674 :         if (Log_error_verbosity >= PGERROR_DEFAULT)
    3270                 :             :         {
    3271         [ +  + ]:       65674 :                 if (edata->detail_log)
    3272                 :             :                 {
    3273                 :          72 :                         log_line_prefix(&buf, edata);
    3274                 :          72 :                         appendStringInfoString(&buf, _("DETAIL:  "));
    3275                 :          72 :                         append_with_tabs(&buf, edata->detail_log);
    3276                 :          72 :                         appendStringInfoChar(&buf, '\n');
    3277                 :          72 :                 }
    3278         [ +  + ]:       65602 :                 else if (edata->detail)
    3279                 :             :                 {
    3280                 :        1820 :                         log_line_prefix(&buf, edata);
    3281                 :        1820 :                         appendStringInfoString(&buf, _("DETAIL:  "));
    3282                 :        1820 :                         append_with_tabs(&buf, edata->detail);
    3283                 :        1820 :                         appendStringInfoChar(&buf, '\n');
    3284                 :        1820 :                 }
    3285         [ +  + ]:       65674 :                 if (edata->hint)
    3286                 :             :                 {
    3287                 :         702 :                         log_line_prefix(&buf, edata);
    3288                 :         702 :                         appendStringInfoString(&buf, _("HINT:  "));
    3289                 :         702 :                         append_with_tabs(&buf, edata->hint);
    3290                 :         702 :                         appendStringInfoChar(&buf, '\n');
    3291                 :         702 :                 }
    3292         [ +  + ]:       65674 :                 if (edata->internalquery)
    3293                 :             :                 {
    3294                 :          10 :                         log_line_prefix(&buf, edata);
    3295                 :          10 :                         appendStringInfoString(&buf, _("QUERY:  "));
    3296                 :          10 :                         append_with_tabs(&buf, edata->internalquery);
    3297                 :          10 :                         appendStringInfoChar(&buf, '\n');
    3298                 :          10 :                 }
    3299   [ +  +  -  + ]:       65674 :                 if (edata->context && !edata->hide_ctx)
    3300                 :             :                 {
    3301                 :         525 :                         log_line_prefix(&buf, edata);
    3302                 :         525 :                         appendStringInfoString(&buf, _("CONTEXT:  "));
    3303                 :         525 :                         append_with_tabs(&buf, edata->context);
    3304                 :         525 :                         appendStringInfoChar(&buf, '\n');
    3305                 :         525 :                 }
    3306         [ +  - ]:       65674 :                 if (Log_error_verbosity >= PGERROR_VERBOSE)
    3307                 :             :                 {
    3308                 :             :                         /* assume no newlines in funcname or filename... */
    3309   [ #  #  #  # ]:           0 :                         if (edata->funcname && edata->filename)
    3310                 :             :                         {
    3311                 :           0 :                                 log_line_prefix(&buf, edata);
    3312                 :           0 :                                 appendStringInfo(&buf, _("LOCATION:  %s, %s:%d\n"),
    3313                 :           0 :                                                                  edata->funcname, edata->filename,
    3314                 :           0 :                                                                  edata->lineno);
    3315                 :           0 :                         }
    3316         [ #  # ]:           0 :                         else if (edata->filename)
    3317                 :             :                         {
    3318                 :           0 :                                 log_line_prefix(&buf, edata);
    3319                 :           0 :                                 appendStringInfo(&buf, _("LOCATION:  %s:%d\n"),
    3320                 :           0 :                                                                  edata->filename, edata->lineno);
    3321                 :           0 :                         }
    3322                 :           0 :                 }
    3323         [ +  - ]:       65674 :                 if (edata->backtrace)
    3324                 :             :                 {
    3325                 :           0 :                         log_line_prefix(&buf, edata);
    3326                 :           0 :                         appendStringInfoString(&buf, _("BACKTRACE:  "));
    3327                 :           0 :                         append_with_tabs(&buf, edata->backtrace);
    3328                 :           0 :                         appendStringInfoChar(&buf, '\n');
    3329                 :           0 :                 }
    3330                 :       65674 :         }
    3331                 :             : 
    3332                 :             :         /*
    3333                 :             :          * If the user wants the query that generated this error logged, do it.
    3334                 :             :          */
    3335         [ +  + ]:       65674 :         if (check_log_of_query(edata))
    3336                 :             :         {
    3337                 :        6774 :                 log_line_prefix(&buf, edata);
    3338                 :        6774 :                 appendStringInfoString(&buf, _("STATEMENT:  "));
    3339                 :        6774 :                 append_with_tabs(&buf, debug_query_string);
    3340                 :        6774 :                 appendStringInfoChar(&buf, '\n');
    3341                 :        6774 :         }
    3342                 :             : 
    3343                 :             : #ifdef HAVE_SYSLOG
    3344                 :             :         /* Write to syslog, if enabled */
    3345         [ +  - ]:       65674 :         if (Log_destination & LOG_DESTINATION_SYSLOG)
    3346                 :             :         {
    3347                 :           0 :                 int                     syslog_level;
    3348                 :             : 
    3349   [ #  #  #  #  :           0 :                 switch (edata->elevel)
                #  #  # ]
    3350                 :             :                 {
    3351                 :             :                         case DEBUG5:
    3352                 :             :                         case DEBUG4:
    3353                 :             :                         case DEBUG3:
    3354                 :             :                         case DEBUG2:
    3355                 :             :                         case DEBUG1:
    3356                 :           0 :                                 syslog_level = LOG_DEBUG;
    3357                 :           0 :                                 break;
    3358                 :             :                         case LOG:
    3359                 :             :                         case LOG_SERVER_ONLY:
    3360                 :             :                         case INFO:
    3361                 :           0 :                                 syslog_level = LOG_INFO;
    3362                 :           0 :                                 break;
    3363                 :             :                         case NOTICE:
    3364                 :             :                         case WARNING:
    3365                 :             :                         case WARNING_CLIENT_ONLY:
    3366                 :           0 :                                 syslog_level = LOG_NOTICE;
    3367                 :           0 :                                 break;
    3368                 :             :                         case ERROR:
    3369                 :           0 :                                 syslog_level = LOG_WARNING;
    3370                 :           0 :                                 break;
    3371                 :             :                         case FATAL:
    3372                 :           0 :                                 syslog_level = LOG_ERR;
    3373                 :           0 :                                 break;
    3374                 :           0 :                         case PANIC:
    3375                 :             :                         default:
    3376                 :           0 :                                 syslog_level = LOG_CRIT;
    3377                 :           0 :                                 break;
    3378                 :             :                 }
    3379                 :             : 
    3380                 :           0 :                 write_syslog(syslog_level, buf.data);
    3381                 :           0 :         }
    3382                 :             : #endif                                                  /* HAVE_SYSLOG */
    3383                 :             : 
    3384                 :             : #ifdef WIN32
    3385                 :             :         /* Write to eventlog, if enabled */
    3386                 :             :         if (Log_destination & LOG_DESTINATION_EVENTLOG)
    3387                 :             :         {
    3388                 :             :                 write_eventlog(edata->elevel, buf.data, buf.len);
    3389                 :             :         }
    3390                 :             : #endif                                                  /* WIN32 */
    3391                 :             : 
    3392                 :             :         /* Write to csvlog, if enabled */
    3393         [ +  - ]:       65674 :         if (Log_destination & LOG_DESTINATION_CSVLOG)
    3394                 :             :         {
    3395                 :             :                 /*
    3396                 :             :                  * Send CSV data if it's safe to do so (syslogger doesn't need the
    3397                 :             :                  * pipe).  If this is not possible, fallback to an entry written to
    3398                 :             :                  * stderr.
    3399                 :             :                  */
    3400   [ #  #  #  # ]:           0 :                 if (redirection_done || MyBackendType == B_LOGGER)
    3401                 :           0 :                         write_csvlog(edata);
    3402                 :             :                 else
    3403                 :           0 :                         fallback_to_stderr = true;
    3404                 :           0 :         }
    3405                 :             : 
    3406                 :             :         /* Write to JSON log, if enabled */
    3407         [ +  - ]:       65674 :         if (Log_destination & LOG_DESTINATION_JSONLOG)
    3408                 :             :         {
    3409                 :             :                 /*
    3410                 :             :                  * Send JSON data if it's safe to do so (syslogger doesn't need the
    3411                 :             :                  * pipe).  If this is not possible, fallback to an entry written to
    3412                 :             :                  * stderr.
    3413                 :             :                  */
    3414   [ #  #  #  # ]:           0 :                 if (redirection_done || MyBackendType == B_LOGGER)
    3415                 :             :                 {
    3416                 :           0 :                         write_jsonlog(edata);
    3417                 :           0 :                 }
    3418                 :             :                 else
    3419                 :           0 :                         fallback_to_stderr = true;
    3420                 :           0 :         }
    3421                 :             : 
    3422                 :             :         /*
    3423                 :             :          * Write to stderr, if enabled or if required because of a previous
    3424                 :             :          * limitation.
    3425                 :             :          */
    3426         [ -  + ]:       65674 :         if ((Log_destination & LOG_DESTINATION_STDERR) ||
    3427   [ #  #  #  # ]:           0 :                 whereToSendOutput == DestDebug ||
    3428                 :           0 :                 fallback_to_stderr)
    3429                 :             :         {
    3430                 :             :                 /*
    3431                 :             :                  * Use the chunking protocol if we know the syslogger should be
    3432                 :             :                  * catching stderr output, and we are not ourselves the syslogger.
    3433                 :             :                  * Otherwise, just do a vanilla write to stderr.
    3434                 :             :                  */
    3435   [ -  +  #  # ]:       65674 :                 if (redirection_done && MyBackendType != B_LOGGER)
    3436                 :           0 :                         write_pipe_chunks(buf.data, buf.len, LOG_DESTINATION_STDERR);
    3437                 :             : #ifdef WIN32
    3438                 :             : 
    3439                 :             :                 /*
    3440                 :             :                  * In a win32 service environment, there is no usable stderr. Capture
    3441                 :             :                  * anything going there and write it to the eventlog instead.
    3442                 :             :                  *
    3443                 :             :                  * If stderr redirection is active, it was OK to write to stderr above
    3444                 :             :                  * because that's really a pipe to the syslogger process.
    3445                 :             :                  */
    3446                 :             :                 else if (pgwin32_is_service())
    3447                 :             :                         write_eventlog(edata->elevel, buf.data, buf.len);
    3448                 :             : #endif
    3449                 :             :                 else
    3450                 :       65674 :                         write_console(buf.data, buf.len);
    3451                 :       65674 :         }
    3452                 :             : 
    3453                 :             :         /* If in the syslogger process, try to write messages direct to file */
    3454         [ +  - ]:       65674 :         if (MyBackendType == B_LOGGER)
    3455                 :           0 :                 write_syslogger_file(buf.data, buf.len, LOG_DESTINATION_STDERR);
    3456                 :             : 
    3457                 :             :         /* No more need of the message formatted for stderr */
    3458                 :       65674 :         pfree(buf.data);
    3459                 :       65674 : }
    3460                 :             : 
    3461                 :             : /*
    3462                 :             :  * Send data to the syslogger using the chunked protocol
    3463                 :             :  *
    3464                 :             :  * Note: when there are multiple backends writing into the syslogger pipe,
    3465                 :             :  * it's critical that each write go into the pipe indivisibly, and not
    3466                 :             :  * get interleaved with data from other processes.  Fortunately, the POSIX
    3467                 :             :  * spec requires that writes to pipes be atomic so long as they are not
    3468                 :             :  * more than PIPE_BUF bytes long.  So we divide long messages into chunks
    3469                 :             :  * that are no more than that length, and send one chunk per write() call.
    3470                 :             :  * The collector process knows how to reassemble the chunks.
    3471                 :             :  *
    3472                 :             :  * Because of the atomic write requirement, there are only two possible
    3473                 :             :  * results from write() here: -1 for failure, or the requested number of
    3474                 :             :  * bytes.  There is not really anything we can do about a failure; retry would
    3475                 :             :  * probably be an infinite loop, and we can't even report the error usefully.
    3476                 :             :  * (There is noplace else we could send it!)  So we might as well just ignore
    3477                 :             :  * the result from write().  However, on some platforms you get a compiler
    3478                 :             :  * warning from ignoring write()'s result, so do a little dance with casting
    3479                 :             :  * rc to void to shut up the compiler.
    3480                 :             :  */
    3481                 :             : void
    3482                 :           0 : write_pipe_chunks(char *data, int len, int dest)
    3483                 :             : {
    3484                 :           0 :         PipeProtoChunk p;
    3485                 :           0 :         int                     fd = fileno(stderr);
    3486                 :           0 :         int                     rc;
    3487                 :             : 
    3488         [ #  # ]:           0 :         Assert(len > 0);
    3489                 :             : 
    3490                 :           0 :         p.proto.nuls[0] = p.proto.nuls[1] = '\0';
    3491                 :           0 :         p.proto.pid = MyProcPid;
    3492                 :           0 :         p.proto.flags = 0;
    3493         [ #  # ]:           0 :         if (dest == LOG_DESTINATION_STDERR)
    3494                 :           0 :                 p.proto.flags |= PIPE_PROTO_DEST_STDERR;
    3495         [ #  # ]:           0 :         else if (dest == LOG_DESTINATION_CSVLOG)
    3496                 :           0 :                 p.proto.flags |= PIPE_PROTO_DEST_CSVLOG;
    3497         [ #  # ]:           0 :         else if (dest == LOG_DESTINATION_JSONLOG)
    3498                 :           0 :                 p.proto.flags |= PIPE_PROTO_DEST_JSONLOG;
    3499                 :             : 
    3500                 :             :         /* write all but the last chunk */
    3501         [ #  # ]:           0 :         while (len > PIPE_MAX_PAYLOAD)
    3502                 :             :         {
    3503                 :             :                 /* no need to set PIPE_PROTO_IS_LAST yet */
    3504                 :           0 :                 p.proto.len = PIPE_MAX_PAYLOAD;
    3505                 :           0 :                 memcpy(p.proto.data, data, PIPE_MAX_PAYLOAD);
    3506                 :           0 :                 rc = write(fd, &p, PIPE_HEADER_SIZE + PIPE_MAX_PAYLOAD);
    3507                 :           0 :                 (void) rc;
    3508                 :           0 :                 data += PIPE_MAX_PAYLOAD;
    3509                 :           0 :                 len -= PIPE_MAX_PAYLOAD;
    3510                 :             :         }
    3511                 :             : 
    3512                 :             :         /* write the last chunk */
    3513                 :           0 :         p.proto.flags |= PIPE_PROTO_IS_LAST;
    3514                 :           0 :         p.proto.len = len;
    3515                 :           0 :         memcpy(p.proto.data, data, len);
    3516                 :           0 :         rc = write(fd, &p, PIPE_HEADER_SIZE + len);
    3517                 :           0 :         (void) rc;
    3518                 :           0 : }
    3519                 :             : 
    3520                 :             : 
    3521                 :             : /*
    3522                 :             :  * Append a text string to the error report being built for the client.
    3523                 :             :  *
    3524                 :             :  * This is ordinarily identical to pq_sendstring(), but if we are in
    3525                 :             :  * error recursion trouble we skip encoding conversion, because of the
    3526                 :             :  * possibility that the problem is a failure in the encoding conversion
    3527                 :             :  * subsystem itself.  Code elsewhere should ensure that the passed-in
    3528                 :             :  * strings will be plain 7-bit ASCII, and thus not in need of conversion,
    3529                 :             :  * in such cases.  (In particular, we disable localization of error messages
    3530                 :             :  * to help ensure that's true.)
    3531                 :             :  */
    3532                 :             : static void
    3533                 :       75714 : err_sendstring(StringInfo buf, const char *str)
    3534                 :             : {
    3535         [ -  + ]:       75714 :         if (in_error_recursion_trouble())
    3536                 :           0 :                 pq_send_ascii_string(buf, str);
    3537                 :             :         else
    3538                 :       75714 :                 pq_sendstring(buf, str);
    3539                 :       75714 : }
    3540                 :             : 
    3541                 :             : /*
    3542                 :             :  * Write error report to client
    3543                 :             :  */
    3544                 :             : static void
    3545                 :        9633 : send_message_to_frontend(ErrorData *edata)
    3546                 :             : {
    3547                 :        9633 :         StringInfoData msgbuf;
    3548                 :             : 
    3549                 :             :         /*
    3550                 :             :          * We no longer support pre-3.0 FE/BE protocol, except here.  If a client
    3551                 :             :          * tries to connect using an older protocol version, it's nice to send the
    3552                 :             :          * "protocol version not supported" error in a format the client
    3553                 :             :          * understands.  If protocol hasn't been set yet, early in backend
    3554                 :             :          * startup, assume modern protocol.
    3555                 :             :          */
    3556   [ -  +  #  # ]:        9633 :         if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3 || FrontendProtocol == 0)
    3557                 :             :         {
    3558                 :             :                 /* New style with separate fields */
    3559                 :        9633 :                 const char *sev;
    3560                 :        9633 :                 char            tbuf[12];
    3561                 :             : 
    3562                 :             :                 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
    3563         [ +  + ]:        9633 :                 if (edata->elevel < ERROR)
    3564                 :        2868 :                         pq_beginmessage(&msgbuf, PqMsg_NoticeResponse);
    3565                 :             :                 else
    3566                 :        6765 :                         pq_beginmessage(&msgbuf, PqMsg_ErrorResponse);
    3567                 :             : 
    3568                 :        9633 :                 sev = error_severity(edata->elevel);
    3569                 :        9633 :                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY);
    3570                 :        9633 :                 err_sendstring(&msgbuf, _(sev));
    3571                 :        9633 :                 pq_sendbyte(&msgbuf, PG_DIAG_SEVERITY_NONLOCALIZED);
    3572                 :        9633 :                 err_sendstring(&msgbuf, sev);
    3573                 :             : 
    3574                 :        9633 :                 pq_sendbyte(&msgbuf, PG_DIAG_SQLSTATE);
    3575                 :        9633 :                 err_sendstring(&msgbuf, unpack_sql_state(edata->sqlerrcode));
    3576                 :             : 
    3577                 :             :                 /* M field is required per protocol, so always send something */
    3578                 :        9633 :                 pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_PRIMARY);
    3579         [ +  - ]:        9633 :                 if (edata->message)
    3580                 :        9633 :                         err_sendstring(&msgbuf, edata->message);
    3581                 :             :                 else
    3582                 :           0 :                         err_sendstring(&msgbuf, _("missing error text"));
    3583                 :             : 
    3584         [ +  + ]:        9633 :                 if (edata->detail)
    3585                 :             :                 {
    3586                 :        1737 :                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_DETAIL);
    3587                 :        1737 :                         err_sendstring(&msgbuf, edata->detail);
    3588                 :        1737 :                 }
    3589                 :             : 
    3590                 :             :                 /* detail_log is intentionally not used here */
    3591                 :             : 
    3592         [ +  + ]:        9633 :                 if (edata->hint)
    3593                 :             :                 {
    3594                 :         635 :                         pq_sendbyte(&msgbuf, PG_DIAG_MESSAGE_HINT);
    3595                 :         635 :                         err_sendstring(&msgbuf, edata->hint);
    3596                 :         635 :                 }
    3597                 :             : 
    3598         [ +  + ]:        9633 :                 if (edata->context)
    3599                 :             :                 {
    3600                 :        2269 :                         pq_sendbyte(&msgbuf, PG_DIAG_CONTEXT);
    3601                 :        2269 :                         err_sendstring(&msgbuf, edata->context);
    3602                 :        2269 :                 }
    3603                 :             : 
    3604         [ +  + ]:        9633 :                 if (edata->schema_name)
    3605                 :             :                 {
    3606                 :         643 :                         pq_sendbyte(&msgbuf, PG_DIAG_SCHEMA_NAME);
    3607                 :         643 :                         err_sendstring(&msgbuf, edata->schema_name);
    3608                 :         643 :                 }
    3609                 :             : 
    3610         [ +  + ]:        9633 :                 if (edata->table_name)
    3611                 :             :                 {
    3612                 :         544 :                         pq_sendbyte(&msgbuf, PG_DIAG_TABLE_NAME);
    3613                 :         544 :                         err_sendstring(&msgbuf, edata->table_name);
    3614                 :         544 :                 }
    3615                 :             : 
    3616         [ +  + ]:        9633 :                 if (edata->column_name)
    3617                 :             :                 {
    3618                 :          91 :                         pq_sendbyte(&msgbuf, PG_DIAG_COLUMN_NAME);
    3619                 :          91 :                         err_sendstring(&msgbuf, edata->column_name);
    3620                 :          91 :                 }
    3621                 :             : 
    3622         [ +  + ]:        9633 :                 if (edata->datatype_name)
    3623                 :             :                 {
    3624                 :          99 :                         pq_sendbyte(&msgbuf, PG_DIAG_DATATYPE_NAME);
    3625                 :          99 :                         err_sendstring(&msgbuf, edata->datatype_name);
    3626                 :          99 :                 }
    3627                 :             : 
    3628         [ +  + ]:        9633 :                 if (edata->constraint_name)
    3629                 :             :                 {
    3630                 :         445 :                         pq_sendbyte(&msgbuf, PG_DIAG_CONSTRAINT_NAME);
    3631                 :         445 :                         err_sendstring(&msgbuf, edata->constraint_name);
    3632                 :         445 :                 }
    3633                 :             : 
    3634         [ +  + ]:        9633 :                 if (edata->cursorpos > 0)
    3635                 :             :                 {
    3636                 :        1800 :                         snprintf(tbuf, sizeof(tbuf), "%d", edata->cursorpos);
    3637                 :        1800 :                         pq_sendbyte(&msgbuf, PG_DIAG_STATEMENT_POSITION);
    3638                 :        1800 :                         err_sendstring(&msgbuf, tbuf);
    3639                 :        1800 :                 }
    3640                 :             : 
    3641         [ +  + ]:        9633 :                 if (edata->internalpos > 0)
    3642                 :             :                 {
    3643                 :          10 :                         snprintf(tbuf, sizeof(tbuf), "%d", edata->internalpos);
    3644                 :          10 :                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_POSITION);
    3645                 :          10 :                         err_sendstring(&msgbuf, tbuf);
    3646                 :          10 :                 }
    3647                 :             : 
    3648         [ +  + ]:        9633 :                 if (edata->internalquery)
    3649                 :             :                 {
    3650                 :          10 :                         pq_sendbyte(&msgbuf, PG_DIAG_INTERNAL_QUERY);
    3651                 :          10 :                         err_sendstring(&msgbuf, edata->internalquery);
    3652                 :          10 :                 }
    3653                 :             : 
    3654         [ -  + ]:        9633 :                 if (edata->filename)
    3655                 :             :                 {
    3656                 :        9633 :                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FILE);
    3657                 :        9633 :                         err_sendstring(&msgbuf, edata->filename);
    3658                 :        9633 :                 }
    3659                 :             : 
    3660         [ -  + ]:        9633 :                 if (edata->lineno > 0)
    3661                 :             :                 {
    3662                 :        9633 :                         snprintf(tbuf, sizeof(tbuf), "%d", edata->lineno);
    3663                 :        9633 :                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_LINE);
    3664                 :        9633 :                         err_sendstring(&msgbuf, tbuf);
    3665                 :        9633 :                 }
    3666                 :             : 
    3667         [ -  + ]:        9633 :                 if (edata->funcname)
    3668                 :             :                 {
    3669                 :        9633 :                         pq_sendbyte(&msgbuf, PG_DIAG_SOURCE_FUNCTION);
    3670                 :        9633 :                         err_sendstring(&msgbuf, edata->funcname);
    3671                 :        9633 :                 }
    3672                 :             : 
    3673                 :        9633 :                 pq_sendbyte(&msgbuf, '\0'); /* terminator */
    3674                 :             : 
    3675                 :        9633 :                 pq_endmessage(&msgbuf);
    3676                 :        9633 :         }
    3677                 :             :         else
    3678                 :             :         {
    3679                 :             :                 /* Old style --- gin up a backwards-compatible message */
    3680                 :           0 :                 StringInfoData buf;
    3681                 :             : 
    3682                 :           0 :                 initStringInfo(&buf);
    3683                 :             : 
    3684                 :           0 :                 appendStringInfo(&buf, "%s:  ", _(error_severity(edata->elevel)));
    3685                 :             : 
    3686         [ #  # ]:           0 :                 if (edata->message)
    3687                 :           0 :                         appendStringInfoString(&buf, edata->message);
    3688                 :             :                 else
    3689                 :           0 :                         appendStringInfoString(&buf, _("missing error text"));
    3690                 :             : 
    3691                 :           0 :                 appendStringInfoChar(&buf, '\n');
    3692                 :             : 
    3693                 :             :                 /* 'N' (Notice) is for nonfatal conditions, 'E' is for errors */
    3694                 :           0 :                 pq_putmessage_v2((edata->elevel < ERROR) ? 'N' : 'E', buf.data, buf.len + 1);
    3695                 :             : 
    3696                 :           0 :                 pfree(buf.data);
    3697                 :           0 :         }
    3698                 :             : 
    3699                 :             :         /*
    3700                 :             :          * This flush is normally not necessary, since postgres.c will flush out
    3701                 :             :          * waiting data when control returns to the main loop. But it seems best
    3702                 :             :          * to leave it here, so that the client has some clue what happened if the
    3703                 :             :          * backend dies before getting back to the main loop ... error/notice
    3704                 :             :          * messages should not be a performance-critical path anyway, so an extra
    3705                 :             :          * flush won't hurt much ...
    3706                 :             :          */
    3707                 :        9633 :         pq_flush();
    3708                 :        9633 : }
    3709                 :             : 
    3710                 :             : 
    3711                 :             : /*
    3712                 :             :  * Support routines for formatting error messages.
    3713                 :             :  */
    3714                 :             : 
    3715                 :             : 
    3716                 :             : /*
    3717                 :             :  * error_severity --- get string representing elevel
    3718                 :             :  *
    3719                 :             :  * The string is not localized here, but we mark the strings for translation
    3720                 :             :  * so that callers can invoke _() on the result.
    3721                 :             :  */
    3722                 :             : const char *
    3723                 :       75307 : error_severity(int elevel)
    3724                 :             : {
    3725                 :       75307 :         const char *prefix;
    3726                 :             : 
    3727   [ -  +  +  -  :       75307 :         switch (elevel)
             +  +  +  +  
                      - ]
    3728                 :             :         {
    3729                 :             :                 case DEBUG1:
    3730                 :             :                 case DEBUG2:
    3731                 :             :                 case DEBUG3:
    3732                 :             :                 case DEBUG4:
    3733                 :             :                 case DEBUG5:
    3734                 :           0 :                         prefix = gettext_noop("DEBUG");
    3735                 :           0 :                         break;
    3736                 :             :                 case LOG:
    3737                 :             :                 case LOG_SERVER_ONLY:
    3738                 :       57933 :                         prefix = gettext_noop("LOG");
    3739                 :       57933 :                         break;
    3740                 :             :                 case INFO:
    3741                 :          42 :                         prefix = gettext_noop("INFO");
    3742                 :          42 :                         break;
    3743                 :             :                 case NOTICE:
    3744                 :        2386 :                         prefix = gettext_noop("NOTICE");
    3745                 :        2386 :                         break;
    3746                 :             :                 case WARNING:
    3747                 :             :                 case WARNING_CLIENT_ONLY:
    3748                 :        1415 :                         prefix = gettext_noop("WARNING");
    3749                 :        1415 :                         break;
    3750                 :             :                 case ERROR:
    3751                 :       13530 :                         prefix = gettext_noop("ERROR");
    3752                 :       13530 :                         break;
    3753                 :             :                 case FATAL:
    3754                 :           1 :                         prefix = gettext_noop("FATAL");
    3755                 :           1 :                         break;
    3756                 :             :                 case PANIC:
    3757                 :           0 :                         prefix = gettext_noop("PANIC");
    3758                 :           0 :                         break;
    3759                 :             :                 default:
    3760                 :           0 :                         prefix = "???";
    3761                 :           0 :                         break;
    3762                 :             :         }
    3763                 :             : 
    3764                 :      150614 :         return prefix;
    3765                 :       75307 : }
    3766                 :             : 
    3767                 :             : 
    3768                 :             : /*
    3769                 :             :  *      append_with_tabs
    3770                 :             :  *
    3771                 :             :  *      Append the string to the StringInfo buffer, inserting a tab after any
    3772                 :             :  *      newline.
    3773                 :             :  */
    3774                 :             : static void
    3775                 :       75577 : append_with_tabs(StringInfo buf, const char *str)
    3776                 :             : {
    3777                 :       75577 :         char            ch;
    3778                 :             : 
    3779         [ +  + ]:     8800530 :         while ((ch = *str++) != '\0')
    3780                 :             :         {
    3781         [ +  + ]:     8724953 :                 appendStringInfoCharMacro(buf, ch);
    3782         [ +  + ]:     8724953 :                 if (ch == '\n')
    3783         [ +  + ]:       95310 :                         appendStringInfoCharMacro(buf, '\t');
    3784                 :             :         }
    3785                 :       75577 : }
    3786                 :             : 
    3787                 :             : 
    3788                 :             : /*
    3789                 :             :  * Write errors to stderr (or by equal means when stderr is
    3790                 :             :  * not available). Used before ereport/elog can be used
    3791                 :             :  * safely (memory context, GUC load etc)
    3792                 :             :  */
    3793                 :             : void
    3794                 :           0 : write_stderr(const char *fmt,...)
    3795                 :             : {
    3796                 :           0 :         va_list         ap;
    3797                 :             : 
    3798                 :           0 :         va_start(ap, fmt);
    3799                 :           0 :         vwrite_stderr(fmt, ap);
    3800                 :           0 :         va_end(ap);
    3801                 :           0 : }
    3802                 :             : 
    3803                 :             : 
    3804                 :             : /*
    3805                 :             :  * Write errors to stderr (or by equal means when stderr is
    3806                 :             :  * not available) - va_list version
    3807                 :             :  */
    3808                 :             : void
    3809                 :           0 : vwrite_stderr(const char *fmt, va_list ap)
    3810                 :             : {
    3811                 :             : #ifdef WIN32
    3812                 :             :         char            errbuf[2048];   /* Arbitrary size? */
    3813                 :             : #endif
    3814                 :             : 
    3815                 :           0 :         fmt = _(fmt);
    3816                 :             : #ifndef WIN32
    3817                 :             :         /* On Unix, we just fprintf to stderr */
    3818                 :           0 :         vfprintf(stderr, fmt, ap);
    3819                 :           0 :         fflush(stderr);
    3820                 :             : #else
    3821                 :             :         vsnprintf(errbuf, sizeof(errbuf), fmt, ap);
    3822                 :             : 
    3823                 :             :         /*
    3824                 :             :          * On Win32, we print to stderr if running on a console, or write to
    3825                 :             :          * eventlog if running as a service
    3826                 :             :          */
    3827                 :             :         if (pgwin32_is_service())       /* Running as a service */
    3828                 :             :         {
    3829                 :             :                 write_eventlog(ERROR, errbuf, strlen(errbuf));
    3830                 :             :         }
    3831                 :             :         else
    3832                 :             :         {
    3833                 :             :                 /* Not running as service, write to stderr */
    3834                 :             :                 write_console(errbuf, strlen(errbuf));
    3835                 :             :                 fflush(stderr);
    3836                 :             :         }
    3837                 :             : #endif
    3838                 :           0 : }
        

Generated by: LCOV version 2.3.2-1