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