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

Generated by: LCOV version 1.14