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

Generated by: LCOV version 1.16