LCOV - differential code coverage report
Current view: top level - src/backend/utils/error - elog.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GNC CBC EUB DUB DCB
Current: 0e5ff9b9b45a657aea12440478dc002e9b01f138 vs 0123ce131fca454009439dfa3b2266d1d40737d7 Lines: 69.9 % 1367 955 18 1 1 392 1 98 856 1 6 5
Current Date: 2026-03-14 14:10:32 -0400 Functions: 91.7 % 84 77 2 5 8 69
Baseline: lcov-20260315-024220-baseline Branches: 51.5 % 969 499 14 1 455 2 58 439 4
Baseline Date: 2026-03-14 15:27:56 +0100 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(7,30] days: 16.7 % 6 1 5 1 1
(30,360] days: 74.0 % 146 108 13 25 97 11
(360..) days: 69.6 % 1215 846 1 1 367 1 845
Function coverage date bins:
(7,30] days: 0.0 % 1 0 1
(30,360] days: 80.0 % 5 4 1 3 1
(360..) days: 93.6 % 78 73 1 4 5 68
Branch coverage date bins:
(30,360] days: 68.9 % 90 62 14 14 58 4
(360..) days: 49.7 % 879 437 1 441 2 435

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

Generated by: LCOV version 2.4-beta