LCOV - code coverage report
Current view: top level - src/backend/utils/error - elog.c (source / functions) Hit Total Coverage
Test: PostgreSQL 15devel Lines: 840 1239 67.8 %
Date: 2021-12-05 02:08:31 Functions: 60 66 90.9 %
Legend: Lines: hit not hit

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

Generated by: LCOV version 1.14