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