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