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